SemaDecl.cpp revision fec54013fcd0eb72642741584ca04c1bc292bef8
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 "SemaInherit.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/Analysis/CFG.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/SourceManager.h"
28// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/STLExtras.h"
34#include <algorithm>
35#include <functional>
36#include <queue>
37using namespace clang;
38
39/// getDeclName - Return a pretty name for the specified decl if possible, or
40/// an empty string if not.  This is used for pretty crash reporting.
41std::string Sema::getDeclName(DeclPtrTy d) {
42  Decl *D = d.getAs<Decl>();
43  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44    return DN->getQualifiedNameAsString();
45  return "";
46}
47
48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
52/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
57/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
60///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64                                Scope *S, const CXXScopeSpec *SS) {
65  // C++ [temp.res]p3:
66  //   A qualified-id that refers to a type and in which the
67  //   nested-name-specifier depends on a template-parameter (14.6.2)
68  //   shall be prefixed by the keyword typename to indicate that the
69  //   qualified-id denotes a type, forming an
70  //   elaborated-type-specifier (7.1.5.3).
71  //
72  // We therefore do not perform any name lookup if the result would
73  // refer to a member of an unknown specialization.
74  if (SS && isUnknownSpecialization(*SS))
75    return 0;
76
77  LookupResult Result
78    = LookupParsedName(S, SS, &II, LookupOrdinaryName, false, false);
79
80  NamedDecl *IIDecl = 0;
81  switch (Result.getKind()) {
82  case LookupResult::NotFound:
83  case LookupResult::FoundOverloaded:
84    return 0;
85
86  case LookupResult::AmbiguousBaseSubobjectTypes:
87  case LookupResult::AmbiguousBaseSubobjects:
88  case LookupResult::AmbiguousReference: {
89    // Look to see if we have a type anywhere in the list of results.
90    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
91         Res != ResEnd; ++Res) {
92      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
93        if (!IIDecl ||
94            (*Res)->getLocation().getRawEncoding() <
95              IIDecl->getLocation().getRawEncoding())
96          IIDecl = *Res;
97      }
98    }
99
100    if (!IIDecl) {
101      // None of the entities we found is a type, so there is no way
102      // to even assume that the result is a type. In this case, don't
103      // complain about the ambiguity. The parser will either try to
104      // perform this lookup again (e.g., as an object name), which
105      // will produce the ambiguity, or will complain that it expected
106      // a type name.
107      Result.Destroy();
108      return 0;
109    }
110
111    // We found a type within the ambiguous lookup; diagnose the
112    // ambiguity and then return that type. This might be the right
113    // answer, or it might not be, but it suppresses any attempt to
114    // perform the name lookup again.
115    DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
116    break;
117  }
118
119  case LookupResult::Found:
120    IIDecl = Result.getAsDecl();
121    break;
122  }
123
124  if (IIDecl) {
125    QualType T;
126
127    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
128      // Check whether we can use this type
129      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
130
131      if (getLangOptions().CPlusPlus) {
132        // C++ [temp.local]p2:
133        //   Within the scope of a class template specialization or
134        //   partial specialization, when the injected-class-name is
135        //   not followed by a <, it is equivalent to the
136        //   injected-class-name followed by the template-argument s
137        //   of the class template specialization or partial
138        //   specialization enclosed in <>.
139        if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
140          if (RD->isInjectedClassName())
141            if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
142              T = Template->getInjectedClassNameType(Context);
143      }
144
145      if (T.isNull())
146        T = Context.getTypeDeclType(TD);
147    } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
148      // Check whether we can use this interface.
149      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
150
151      T = Context.getObjCInterfaceType(IDecl);
152    } else
153      return 0;
154
155    if (SS)
156      T = getQualifiedNameType(*SS, T);
157
158    return T.getAsOpaquePtr();
159  }
160
161  return 0;
162}
163
164/// isTagName() - This method is called *for error recovery purposes only*
165/// to determine if the specified name is a valid tag name ("struct foo").  If
166/// so, this returns the TST for the tag corresponding to it (TST_enum,
167/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
168/// where the user forgot to specify the tag.
169DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
170  // Do a tag name lookup in this scope.
171  LookupResult R = LookupName(S, &II, LookupTagName, false, false);
172  if (R.getKind() == LookupResult::Found)
173    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
174      switch (TD->getTagKind()) {
175      case TagDecl::TK_struct: return DeclSpec::TST_struct;
176      case TagDecl::TK_union:  return DeclSpec::TST_union;
177      case TagDecl::TK_class:  return DeclSpec::TST_class;
178      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
179      }
180    }
181
182  return DeclSpec::TST_unspecified;
183}
184
185
186
187DeclContext *Sema::getContainingDC(DeclContext *DC) {
188  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
189    // A C++ out-of-line method will return to the file declaration context.
190    if (MD->isOutOfLine())
191      return MD->getLexicalDeclContext();
192
193    // A C++ inline method is parsed *after* the topmost class it was declared
194    // in is fully parsed (it's "complete").
195    // The parsing of a C++ inline method happens at the declaration context of
196    // the topmost (non-nested) class it is lexically declared in.
197    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
198    DC = MD->getParent();
199    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
200      DC = RD;
201
202    // Return the declaration context of the topmost class the inline method is
203    // declared in.
204    return DC;
205  }
206
207  if (isa<ObjCMethodDecl>(DC))
208    return Context.getTranslationUnitDecl();
209
210  return DC->getLexicalParent();
211}
212
213void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
214  assert(getContainingDC(DC) == CurContext &&
215      "The next DeclContext should be lexically contained in the current one.");
216  CurContext = DC;
217  S->setEntity(DC);
218}
219
220void Sema::PopDeclContext() {
221  assert(CurContext && "DeclContext imbalance!");
222
223  CurContext = getContainingDC(CurContext);
224}
225
226/// EnterDeclaratorContext - Used when we must lookup names in the context
227/// of a declarator's nested name specifier.
228void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
229  assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
230  PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
231  CurContext = DC;
232  assert(CurContext && "No context?");
233  S->setEntity(CurContext);
234}
235
236void Sema::ExitDeclaratorContext(Scope *S) {
237  S->setEntity(PreDeclaratorDC);
238  PreDeclaratorDC = 0;
239
240  // Reset CurContext to the nearest enclosing context.
241  while (!S->getEntity() && S->getParent())
242    S = S->getParent();
243  CurContext = static_cast<DeclContext*>(S->getEntity());
244  assert(CurContext && "No context?");
245}
246
247/// \brief Determine whether we allow overloading of the function
248/// PrevDecl with another declaration.
249///
250/// This routine determines whether overloading is possible, not
251/// whether some new function is actually an overload. It will return
252/// true in C++ (where we can always provide overloads) or, as an
253/// extension, in C when the previous function is already an
254/// overloaded function declaration or has the "overloadable"
255/// attribute.
256static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
257  if (Context.getLangOptions().CPlusPlus)
258    return true;
259
260  if (isa<OverloadedFunctionDecl>(PrevDecl))
261    return true;
262
263  return PrevDecl->getAttr<OverloadableAttr>() != 0;
264}
265
266/// Add this decl to the scope shadowed decl chains.
267void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
268  // Move up the scope chain until we find the nearest enclosing
269  // non-transparent context. The declaration will be introduced into this
270  // scope.
271  while (S->getEntity() &&
272         ((DeclContext *)S->getEntity())->isTransparentContext())
273    S = S->getParent();
274
275  S->AddDecl(DeclPtrTy::make(D));
276
277  // Add scoped declarations into their context, so that they can be
278  // found later. Declarations without a context won't be inserted
279  // into any context.
280  CurContext->addDecl(D);
281
282  // C++ [basic.scope]p4:
283  //   -- exactly one declaration shall declare a class name or
284  //   enumeration name that is not a typedef name and the other
285  //   declarations shall all refer to the same object or
286  //   enumerator, or all refer to functions and function templates;
287  //   in this case the class name or enumeration name is hidden.
288  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
289    // We are pushing the name of a tag (enum or class).
290    if (CurContext->getLookupContext()
291          == TD->getDeclContext()->getLookupContext()) {
292      // We're pushing the tag into the current context, which might
293      // require some reshuffling in the identifier resolver.
294      IdentifierResolver::iterator
295        I = IdResolver.begin(TD->getDeclName()),
296        IEnd = IdResolver.end();
297      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
298        NamedDecl *PrevDecl = *I;
299        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
300             PrevDecl = *I, ++I) {
301          if (TD->declarationReplaces(*I)) {
302            // This is a redeclaration. Remove it from the chain and
303            // break out, so that we'll add in the shadowed
304            // declaration.
305            S->RemoveDecl(DeclPtrTy::make(*I));
306            if (PrevDecl == *I) {
307              IdResolver.RemoveDecl(*I);
308              IdResolver.AddDecl(TD);
309              return;
310            } else {
311              IdResolver.RemoveDecl(*I);
312              break;
313            }
314          }
315        }
316
317        // There is already a declaration with the same name in the same
318        // scope, which is not a tag declaration. It must be found
319        // before we find the new declaration, so insert the new
320        // declaration at the end of the chain.
321        IdResolver.AddShadowedDecl(TD, PrevDecl);
322
323        return;
324      }
325    }
326  } else if ((isa<FunctionDecl>(D) &&
327              AllowOverloadingOfFunction(D, Context)) ||
328             isa<FunctionTemplateDecl>(D)) {
329    // We are pushing the name of a function or function template,
330    // which might be an overloaded name.
331    IdentifierResolver::iterator Redecl
332      = std::find_if(IdResolver.begin(D->getDeclName()),
333                     IdResolver.end(),
334                     std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
335                                  D));
336    if (Redecl != IdResolver.end() &&
337        S->isDeclScope(DeclPtrTy::make(*Redecl))) {
338      // There is already a declaration of a function on our
339      // IdResolver chain. Replace it with this declaration.
340      S->RemoveDecl(DeclPtrTy::make(*Redecl));
341      IdResolver.RemoveDecl(*Redecl);
342    }
343  } else if (isa<ObjCInterfaceDecl>(D)) {
344    // We're pushing an Objective-C interface into the current
345    // context. If there is already an alias declaration, remove it first.
346    for (IdentifierResolver::iterator
347           I = IdResolver.begin(D->getDeclName()), IEnd = IdResolver.end();
348         I != IEnd; ++I) {
349      if (isa<ObjCCompatibleAliasDecl>(*I)) {
350        S->RemoveDecl(DeclPtrTy::make(*I));
351        IdResolver.RemoveDecl(*I);
352        break;
353      }
354    }
355  }
356
357  IdResolver.AddDecl(D);
358}
359
360void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
361  if (S->decl_empty()) return;
362  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
363	 "Scope shouldn't contain decls!");
364
365  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
366       I != E; ++I) {
367    Decl *TmpD = (*I).getAs<Decl>();
368    assert(TmpD && "This decl didn't get pushed??");
369
370    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
371    NamedDecl *D = cast<NamedDecl>(TmpD);
372
373    if (!D->getDeclName()) continue;
374
375    // Remove this name from our lexical scope.
376    IdResolver.RemoveDecl(D);
377  }
378}
379
380/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
381/// return 0 if one not found.
382ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
383  // The third "scope" argument is 0 since we aren't enabling lazy built-in
384  // creation from this context.
385  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
386
387  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
388}
389
390/// getNonFieldDeclScope - Retrieves the innermost scope, starting
391/// from S, where a non-field would be declared. This routine copes
392/// with the difference between C and C++ scoping rules in structs and
393/// unions. For example, the following code is well-formed in C but
394/// ill-formed in C++:
395/// @code
396/// struct S6 {
397///   enum { BAR } e;
398/// };
399///
400/// void test_S6() {
401///   struct S6 a;
402///   a.e = BAR;
403/// }
404/// @endcode
405/// For the declaration of BAR, this routine will return a different
406/// scope. The scope S will be the scope of the unnamed enumeration
407/// within S6. In C++, this routine will return the scope associated
408/// with S6, because the enumeration's scope is a transparent
409/// context but structures can contain non-field names. In C, this
410/// routine will return the translation unit scope, since the
411/// enumeration's scope is a transparent context and structures cannot
412/// contain non-field names.
413Scope *Sema::getNonFieldDeclScope(Scope *S) {
414  while (((S->getFlags() & Scope::DeclScope) == 0) ||
415         (S->getEntity() &&
416          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
417         (S->isClassScope() && !getLangOptions().CPlusPlus))
418    S = S->getParent();
419  return S;
420}
421
422void Sema::InitBuiltinVaListType() {
423  if (!Context.getBuiltinVaListType().isNull())
424    return;
425
426  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
427  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
428  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
429  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
430}
431
432/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
433/// file scope.  lazily create a decl for it. ForRedeclaration is true
434/// if we're creating this built-in in anticipation of redeclaring the
435/// built-in.
436NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
437                                     Scope *S, bool ForRedeclaration,
438                                     SourceLocation Loc) {
439  Builtin::ID BID = (Builtin::ID)bid;
440
441  if (Context.BuiltinInfo.hasVAListUse(BID))
442    InitBuiltinVaListType();
443
444  ASTContext::GetBuiltinTypeError Error;
445  QualType R = Context.GetBuiltinType(BID, Error);
446  switch (Error) {
447  case ASTContext::GE_None:
448    // Okay
449    break;
450
451  case ASTContext::GE_Missing_stdio:
452    if (ForRedeclaration)
453      Diag(Loc, diag::err_implicit_decl_requires_stdio)
454        << Context.BuiltinInfo.GetName(BID);
455    return 0;
456
457  case ASTContext::GE_Missing_setjmp:
458    if (ForRedeclaration)
459      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
460        << Context.BuiltinInfo.GetName(BID);
461    return 0;
462  }
463
464  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
465    Diag(Loc, diag::ext_implicit_lib_function_decl)
466      << Context.BuiltinInfo.GetName(BID)
467      << R;
468    if (Context.BuiltinInfo.getHeaderName(BID) &&
469        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
470          != Diagnostic::Ignored)
471      Diag(Loc, diag::note_please_include_header)
472        << Context.BuiltinInfo.getHeaderName(BID)
473        << Context.BuiltinInfo.GetName(BID);
474  }
475
476  FunctionDecl *New = FunctionDecl::Create(Context,
477                                           Context.getTranslationUnitDecl(),
478                                           Loc, II, R,
479                                           FunctionDecl::Extern, false,
480                                           /*hasPrototype=*/true);
481  New->setImplicit();
482
483  // Create Decl objects for each parameter, adding them to the
484  // FunctionDecl.
485  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
486    llvm::SmallVector<ParmVarDecl*, 16> Params;
487    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
488      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
489                                           FT->getArgType(i), VarDecl::None, 0));
490    New->setParams(Context, Params.data(), Params.size());
491  }
492
493  AddKnownFunctionAttributes(New);
494
495  // TUScope is the translation-unit scope to insert this function into.
496  // FIXME: This is hideous. We need to teach PushOnScopeChains to
497  // relate Scopes to DeclContexts, and probably eliminate CurContext
498  // entirely, but we're not there yet.
499  DeclContext *SavedContext = CurContext;
500  CurContext = Context.getTranslationUnitDecl();
501  PushOnScopeChains(New, TUScope);
502  CurContext = SavedContext;
503  return New;
504}
505
506/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
507/// everything from the standard library is defined.
508NamespaceDecl *Sema::GetStdNamespace() {
509  if (!StdNamespace) {
510    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
511    DeclContext *Global = Context.getTranslationUnitDecl();
512    Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
513    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
514  }
515  return StdNamespace;
516}
517
518/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
519/// same name and scope as a previous declaration 'Old'.  Figure out
520/// how to resolve this situation, merging decls or emitting
521/// diagnostics as appropriate. If there was an error, set New to be invalid.
522///
523void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
524  // If either decl is known invalid already, set the new one to be invalid and
525  // don't bother doing any merging checks.
526  if (New->isInvalidDecl() || OldD->isInvalidDecl())
527    return New->setInvalidDecl();
528
529  // Allow multiple definitions for ObjC built-in typedefs.
530  // FIXME: Verify the underlying types are equivalent!
531  if (getLangOptions().ObjC1) {
532    const IdentifierInfo *TypeID = New->getIdentifier();
533    switch (TypeID->getLength()) {
534    default: break;
535    case 2:
536      if (!TypeID->isStr("id"))
537        break;
538      // Install the built-in type for 'id', ignoring the current definition.
539      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
540      return;
541    case 5:
542      if (!TypeID->isStr("Class"))
543        break;
544      // Install the built-in type for 'Class', ignoring the current definition.
545      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
546      return;
547    case 3:
548      if (!TypeID->isStr("SEL"))
549        break;
550      Context.setObjCSelType(Context.getTypeDeclType(New));
551      return;
552    case 8:
553      if (!TypeID->isStr("Protocol"))
554        break;
555      Context.setObjCProtoType(New->getUnderlyingType());
556      return;
557    }
558    // Fall through - the typedef name was not a builtin type.
559  }
560  // Verify the old decl was also a type.
561  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
562  if (!Old) {
563    Diag(New->getLocation(), diag::err_redefinition_different_kind)
564      << New->getDeclName();
565    if (OldD->getLocation().isValid())
566      Diag(OldD->getLocation(), diag::note_previous_definition);
567    return New->setInvalidDecl();
568  }
569
570  // Determine the "old" type we'll use for checking and diagnostics.
571  QualType OldType;
572  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
573    OldType = OldTypedef->getUnderlyingType();
574  else
575    OldType = Context.getTypeDeclType(Old);
576
577  // If the typedef types are not identical, reject them in all languages and
578  // with any extensions enabled.
579
580  if (OldType != New->getUnderlyingType() &&
581      Context.getCanonicalType(OldType) !=
582      Context.getCanonicalType(New->getUnderlyingType())) {
583    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
584      << New->getUnderlyingType() << OldType;
585    if (Old->getLocation().isValid())
586      Diag(Old->getLocation(), diag::note_previous_definition);
587    return New->setInvalidDecl();
588  }
589
590  if (getLangOptions().Microsoft)
591    return;
592
593  // C++ [dcl.typedef]p2:
594  //   In a given non-class scope, a typedef specifier can be used to
595  //   redefine the name of any type declared in that scope to refer
596  //   to the type to which it already refers.
597  if (getLangOptions().CPlusPlus) {
598    if (!isa<CXXRecordDecl>(CurContext))
599      return;
600    Diag(New->getLocation(), diag::err_redefinition)
601      << New->getDeclName();
602    Diag(Old->getLocation(), diag::note_previous_definition);
603    return New->setInvalidDecl();
604  }
605
606  // If we have a redefinition of a typedef in C, emit a warning.  This warning
607  // is normally mapped to an error, but can be controlled with
608  // -Wtypedef-redefinition.  If either the original or the redefinition is
609  // in a system header, don't emit this for compatibility with GCC.
610  if (PP.getDiagnostics().getSuppressSystemWarnings() &&
611      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
612       Context.getSourceManager().isInSystemHeader(New->getLocation())))
613    return;
614
615  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
616    << New->getDeclName();
617  Diag(Old->getLocation(), diag::note_previous_definition);
618  return;
619}
620
621/// DeclhasAttr - returns true if decl Declaration already has the target
622/// attribute.
623static bool
624DeclHasAttr(const Decl *decl, const Attr *target) {
625  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
626    if (attr->getKind() == target->getKind())
627      return true;
628
629  return false;
630}
631
632/// MergeAttributes - append attributes from the Old decl to the New one.
633static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
634  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
635    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
636      Attr *NewAttr = attr->clone(C);
637      NewAttr->setInherited(true);
638      New->addAttr(NewAttr);
639    }
640  }
641}
642
643/// Used in MergeFunctionDecl to keep track of function parameters in
644/// C.
645struct GNUCompatibleParamWarning {
646  ParmVarDecl *OldParm;
647  ParmVarDecl *NewParm;
648  QualType PromotedType;
649};
650
651/// MergeFunctionDecl - We just parsed a function 'New' from
652/// declarator D which has the same name and scope as a previous
653/// declaration 'Old'.  Figure out how to resolve this situation,
654/// merging decls or emitting diagnostics as appropriate.
655///
656/// In C++, New and Old must be declarations that are not
657/// overloaded. Use IsOverload to determine whether New and Old are
658/// overloaded, and to select the Old declaration that New should be
659/// merged with.
660///
661/// Returns true if there was an error, false otherwise.
662bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
663  assert(!isa<OverloadedFunctionDecl>(OldD) &&
664         "Cannot merge with an overloaded function declaration");
665
666  // Verify the old decl was also a function.
667  FunctionDecl *Old = 0;
668  if (FunctionTemplateDecl *OldFunctionTemplate
669        = dyn_cast<FunctionTemplateDecl>(OldD))
670    Old = OldFunctionTemplate->getTemplatedDecl();
671  else
672    Old = dyn_cast<FunctionDecl>(OldD);
673  if (!Old) {
674    Diag(New->getLocation(), diag::err_redefinition_different_kind)
675      << New->getDeclName();
676    Diag(OldD->getLocation(), diag::note_previous_definition);
677    return true;
678  }
679
680  // Determine whether the previous declaration was a definition,
681  // implicit declaration, or a declaration.
682  diag::kind PrevDiag;
683  if (Old->isThisDeclarationADefinition())
684    PrevDiag = diag::note_previous_definition;
685  else if (Old->isImplicit())
686    PrevDiag = diag::note_previous_implicit_declaration;
687  else
688    PrevDiag = diag::note_previous_declaration;
689
690  QualType OldQType = Context.getCanonicalType(Old->getType());
691  QualType NewQType = Context.getCanonicalType(New->getType());
692
693  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
694      New->getStorageClass() == FunctionDecl::Static &&
695      Old->getStorageClass() != FunctionDecl::Static) {
696    Diag(New->getLocation(), diag::err_static_non_static)
697      << New;
698    Diag(Old->getLocation(), PrevDiag);
699    return true;
700  }
701
702  if (getLangOptions().CPlusPlus) {
703    // (C++98 13.1p2):
704    //   Certain function declarations cannot be overloaded:
705    //     -- Function declarations that differ only in the return type
706    //        cannot be overloaded.
707    QualType OldReturnType
708      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
709    QualType NewReturnType
710      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
711    if (OldReturnType != NewReturnType) {
712      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
713      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
714      return true;
715    }
716
717    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
718    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
719    if (OldMethod && NewMethod &&
720        NewMethod->getLexicalDeclContext()->isRecord()) {
721      //    -- Member function declarations with the same name and the
722      //       same parameter types cannot be overloaded if any of them
723      //       is a static member function declaration.
724      if (OldMethod->isStatic() || NewMethod->isStatic()) {
725        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
726        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
727        return true;
728      }
729
730      // C++ [class.mem]p1:
731      //   [...] A member shall not be declared twice in the
732      //   member-specification, except that a nested class or member
733      //   class template can be declared and then later defined.
734      unsigned NewDiag;
735      if (isa<CXXConstructorDecl>(OldMethod))
736        NewDiag = diag::err_constructor_redeclared;
737      else if (isa<CXXDestructorDecl>(NewMethod))
738        NewDiag = diag::err_destructor_redeclared;
739      else if (isa<CXXConversionDecl>(NewMethod))
740        NewDiag = diag::err_conv_function_redeclared;
741      else
742        NewDiag = diag::err_member_redeclared;
743
744      Diag(New->getLocation(), NewDiag);
745      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
746    }
747
748    // (C++98 8.3.5p3):
749    //   All declarations for a function shall agree exactly in both the
750    //   return type and the parameter-type-list.
751    if (OldQType == NewQType)
752      return MergeCompatibleFunctionDecls(New, Old);
753
754    // Fall through for conflicting redeclarations and redefinitions.
755  }
756
757  // C: Function types need to be compatible, not identical. This handles
758  // duplicate function decls like "void f(int); void f(enum X);" properly.
759  if (!getLangOptions().CPlusPlus &&
760      Context.typesAreCompatible(OldQType, NewQType)) {
761    const FunctionType *OldFuncType = OldQType->getAsFunctionType();
762    const FunctionType *NewFuncType = NewQType->getAsFunctionType();
763    const FunctionProtoType *OldProto = 0;
764    if (isa<FunctionNoProtoType>(NewFuncType) &&
765        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
766      // The old declaration provided a function prototype, but the
767      // new declaration does not. Merge in the prototype.
768      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
769      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
770                                                 OldProto->arg_type_end());
771      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
772                                         ParamTypes.data(), ParamTypes.size(),
773                                         OldProto->isVariadic(),
774                                         OldProto->getTypeQuals());
775      New->setType(NewQType);
776      New->setHasInheritedPrototype();
777
778      // Synthesize a parameter for each argument type.
779      llvm::SmallVector<ParmVarDecl*, 16> Params;
780      for (FunctionProtoType::arg_type_iterator
781             ParamType = OldProto->arg_type_begin(),
782             ParamEnd = OldProto->arg_type_end();
783           ParamType != ParamEnd; ++ParamType) {
784        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
785                                                 SourceLocation(), 0,
786                                                 *ParamType, VarDecl::None,
787                                                 0);
788        Param->setImplicit();
789        Params.push_back(Param);
790      }
791
792      New->setParams(Context, Params.data(), Params.size());
793    }
794
795    return MergeCompatibleFunctionDecls(New, Old);
796  }
797
798  // GNU C permits a K&R definition to follow a prototype declaration
799  // if the declared types of the parameters in the K&R definition
800  // match the types in the prototype declaration, even when the
801  // promoted types of the parameters from the K&R definition differ
802  // from the types in the prototype. GCC then keeps the types from
803  // the prototype.
804  //
805  // If a variadic prototype is followed by a non-variadic K&R definition,
806  // the K&R definition becomes variadic.  This is sort of an edge case, but
807  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
808  // C99 6.9.1p8.
809  if (!getLangOptions().CPlusPlus &&
810      Old->hasPrototype() && !New->hasPrototype() &&
811      New->getType()->getAsFunctionProtoType() &&
812      Old->getNumParams() == New->getNumParams()) {
813    llvm::SmallVector<QualType, 16> ArgTypes;
814    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
815    const FunctionProtoType *OldProto
816      = Old->getType()->getAsFunctionProtoType();
817    const FunctionProtoType *NewProto
818      = New->getType()->getAsFunctionProtoType();
819
820    // Determine whether this is the GNU C extension.
821    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
822                                               NewProto->getResultType());
823    bool LooseCompatible = !MergedReturn.isNull();
824    for (unsigned Idx = 0, End = Old->getNumParams();
825         LooseCompatible && Idx != End; ++Idx) {
826      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
827      ParmVarDecl *NewParm = New->getParamDecl(Idx);
828      if (Context.typesAreCompatible(OldParm->getType(),
829                                     NewProto->getArgType(Idx))) {
830        ArgTypes.push_back(NewParm->getType());
831      } else if (Context.typesAreCompatible(OldParm->getType(),
832                                            NewParm->getType())) {
833        GNUCompatibleParamWarning Warn
834          = { OldParm, NewParm, NewProto->getArgType(Idx) };
835        Warnings.push_back(Warn);
836        ArgTypes.push_back(NewParm->getType());
837      } else
838        LooseCompatible = false;
839    }
840
841    if (LooseCompatible) {
842      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
843        Diag(Warnings[Warn].NewParm->getLocation(),
844             diag::ext_param_promoted_not_compatible_with_prototype)
845          << Warnings[Warn].PromotedType
846          << Warnings[Warn].OldParm->getType();
847        Diag(Warnings[Warn].OldParm->getLocation(),
848             diag::note_previous_declaration);
849      }
850
851      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
852                                           ArgTypes.size(),
853                                           OldProto->isVariadic(), 0));
854      return MergeCompatibleFunctionDecls(New, Old);
855    }
856
857    // Fall through to diagnose conflicting types.
858  }
859
860  // A function that has already been declared has been redeclared or defined
861  // with a different type- show appropriate diagnostic
862  if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
863    // The user has declared a builtin function with an incompatible
864    // signature.
865    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
866      // The function the user is redeclaring is a library-defined
867      // function like 'malloc' or 'printf'. Warn about the
868      // redeclaration, then pretend that we don't know about this
869      // library built-in.
870      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
871      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
872        << Old << Old->getType();
873      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
874      Old->setInvalidDecl();
875      return false;
876    }
877
878    PrevDiag = diag::note_previous_builtin_declaration;
879  }
880
881  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
882  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
883  return true;
884}
885
886/// \brief Completes the merge of two function declarations that are
887/// known to be compatible.
888///
889/// This routine handles the merging of attributes and other
890/// properties of function declarations form the old declaration to
891/// the new declaration, once we know that New is in fact a
892/// redeclaration of Old.
893///
894/// \returns false
895bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
896  // Merge the attributes
897  MergeAttributes(New, Old, Context);
898
899  // Merge the storage class.
900  if (Old->getStorageClass() != FunctionDecl::Extern)
901    New->setStorageClass(Old->getStorageClass());
902
903  // Merge "inline"
904  if (Old->isInline())
905    New->setInline(true);
906
907  // If this function declaration by itself qualifies as a C99 inline
908  // definition (C99 6.7.4p6), but the previous definition did not,
909  // then the function is not a C99 inline definition.
910  if (New->isC99InlineDefinition() && !Old->isC99InlineDefinition())
911    New->setC99InlineDefinition(false);
912  else if (Old->isC99InlineDefinition() && !New->isC99InlineDefinition()) {
913    // Mark all preceding definitions as not being C99 inline definitions.
914    for (const FunctionDecl *Prev = Old; Prev;
915         Prev = Prev->getPreviousDeclaration())
916      const_cast<FunctionDecl *>(Prev)->setC99InlineDefinition(false);
917  }
918
919  // Merge "pure" flag.
920  if (Old->isPure())
921    New->setPure();
922
923  // Merge the "deleted" flag.
924  if (Old->isDeleted())
925    New->setDeleted();
926
927  if (getLangOptions().CPlusPlus)
928    return MergeCXXFunctionDecl(New, Old);
929
930  return false;
931}
932
933/// MergeVarDecl - We just parsed a variable 'New' which has the same name
934/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
935/// situation, merging decls or emitting diagnostics as appropriate.
936///
937/// Tentative definition rules (C99 6.9.2p2) are checked by
938/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
939/// definitions here, since the initializer hasn't been attached.
940///
941void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
942  // If either decl is invalid, make sure the new one is marked invalid and
943  // don't do any other checking.
944  if (New->isInvalidDecl() || OldD->isInvalidDecl())
945    return New->setInvalidDecl();
946
947  // Verify the old decl was also a variable.
948  VarDecl *Old = dyn_cast<VarDecl>(OldD);
949  if (!Old) {
950    Diag(New->getLocation(), diag::err_redefinition_different_kind)
951      << New->getDeclName();
952    Diag(OldD->getLocation(), diag::note_previous_definition);
953    return New->setInvalidDecl();
954  }
955
956  MergeAttributes(New, Old, Context);
957
958  // Merge the types
959  QualType MergedT;
960  if (getLangOptions().CPlusPlus) {
961    if (Context.hasSameType(New->getType(), Old->getType()))
962      MergedT = New->getType();
963  } else {
964    MergedT = Context.mergeTypes(New->getType(), Old->getType());
965  }
966  if (MergedT.isNull()) {
967    Diag(New->getLocation(), diag::err_redefinition_different_type)
968      << New->getDeclName();
969    Diag(Old->getLocation(), diag::note_previous_definition);
970    return New->setInvalidDecl();
971  }
972  New->setType(MergedT);
973
974  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
975  if (New->getStorageClass() == VarDecl::Static &&
976      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
977    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
978    Diag(Old->getLocation(), diag::note_previous_definition);
979    return New->setInvalidDecl();
980  }
981  // C99 6.2.2p4:
982  //   For an identifier declared with the storage-class specifier
983  //   extern in a scope in which a prior declaration of that
984  //   identifier is visible,23) if the prior declaration specifies
985  //   internal or external linkage, the linkage of the identifier at
986  //   the later declaration is the same as the linkage specified at
987  //   the prior declaration. If no prior declaration is visible, or
988  //   if the prior declaration specifies no linkage, then the
989  //   identifier has external linkage.
990  if (New->hasExternalStorage() && Old->hasLinkage())
991    /* Okay */;
992  else if (New->getStorageClass() != VarDecl::Static &&
993           Old->getStorageClass() == VarDecl::Static) {
994    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
995    Diag(Old->getLocation(), diag::note_previous_definition);
996    return New->setInvalidDecl();
997  }
998
999  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1000
1001  // FIXME: The test for external storage here seems wrong? We still
1002  // need to check for mismatches.
1003  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1004      // Don't complain about out-of-line definitions of static members.
1005      !(Old->getLexicalDeclContext()->isRecord() &&
1006        !New->getLexicalDeclContext()->isRecord())) {
1007    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1008    Diag(Old->getLocation(), diag::note_previous_definition);
1009    return New->setInvalidDecl();
1010  }
1011
1012  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1013    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1014    Diag(Old->getLocation(), diag::note_previous_definition);
1015  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1016    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1017    Diag(Old->getLocation(), diag::note_previous_definition);
1018  }
1019
1020  // Keep a chain of previous declarations.
1021  New->setPreviousDeclaration(Old);
1022}
1023
1024/// CheckFallThrough - Check that we don't fall off the end of a
1025/// Statement that should return a value.
1026///
1027/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1028/// MaybeFallThrough iff we might or might not fall off the end and
1029/// NeverFallThrough iff we never fall off the end of the statement.  We assume
1030/// that functions not marked noreturn will return.
1031Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1032  llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1033
1034  // FIXME: They should never return 0, fix that, delete this code.
1035  if (cfg == 0)
1036    return NeverFallThrough;
1037  // The CFG leaves in dead things, and we don't want to dead code paths to
1038  // confuse us, so we mark all live things first.
1039  std::queue<CFGBlock*> workq;
1040  llvm::BitVector live(cfg->getNumBlockIDs());
1041  // Prep work queue
1042  workq.push(&cfg->getEntry());
1043  // Solve
1044  while (!workq.empty()) {
1045    CFGBlock *item = workq.front();
1046    workq.pop();
1047    live.set(item->getBlockID());
1048    for (CFGBlock::succ_iterator I=item->succ_begin(),
1049           E=item->succ_end();
1050         I != E;
1051         ++I) {
1052      if ((*I) && !live[(*I)->getBlockID()]) {
1053        live.set((*I)->getBlockID());
1054        workq.push(*I);
1055      }
1056    }
1057  }
1058
1059  // Now we know what is live, we check the live precessors of the exit block
1060  // and look for fall through paths, being careful to ignore normal returns,
1061  // and exceptional paths.
1062  bool HasLiveReturn = false;
1063  bool HasFakeEdge = false;
1064  bool HasPlainEdge = false;
1065  for (CFGBlock::succ_iterator I=cfg->getExit().pred_begin(),
1066         E = cfg->getExit().pred_end();
1067       I != E;
1068       ++I) {
1069    CFGBlock& B = **I;
1070    if (!live[B.getBlockID()])
1071      continue;
1072    if (B.size() == 0) {
1073      // A labeled empty statement, or the entry block...
1074      HasPlainEdge = true;
1075      continue;
1076    }
1077    Stmt *S = B[B.size()-1];
1078    if (isa<ReturnStmt>(S)) {
1079      HasLiveReturn = true;
1080      continue;
1081    }
1082    if (isa<ObjCAtThrowStmt>(S)) {
1083      HasFakeEdge = true;
1084      continue;
1085    }
1086    if (isa<CXXThrowExpr>(S)) {
1087      HasFakeEdge = true;
1088      continue;
1089    }
1090    bool NoReturnEdge = false;
1091    if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1092      Expr *CEE = C->getCallee()->IgnoreParenCasts();
1093      if (CEE->getType().getNoReturnAttr()) {
1094        NoReturnEdge = true;
1095        HasFakeEdge = true;
1096      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1097        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1098          if (FD->hasAttr<NoReturnAttr>()) {
1099            NoReturnEdge = true;
1100            HasFakeEdge = true;
1101          }
1102        }
1103      }
1104    }
1105    // FIXME: Add noreturn message sends.
1106    if (NoReturnEdge == false)
1107      HasPlainEdge = true;
1108  }
1109  if (!HasPlainEdge)
1110    return NeverFallThrough;
1111  if (HasFakeEdge || HasLiveReturn)
1112    return MaybeFallThrough;
1113  // This says AlwaysFallThrough for calls to functions that are not marked
1114  // noreturn, that don't return.  If people would like this warning to be more
1115  // accurate, such functions should be marked as noreturn.
1116  return AlwaysFallThrough;
1117}
1118
1119/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1120/// function that should return a value.  Check that we don't fall off the end
1121/// of a noreturn function.  We assume that functions and blocks not marked
1122/// noreturn will return.
1123void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1124  // FIXME: Would be nice if we had a better way to control cascading errors,
1125  // but for now, avoid them.  The problem is that when Parse sees:
1126  //   int foo() { return a; }
1127  // The return is eaten and the Sema code sees just:
1128  //   int foo() { }
1129  // which this code would then warn about.
1130  if (getDiagnostics().hasErrorOccurred())
1131    return;
1132  bool ReturnsVoid = false;
1133  bool HasNoReturn = false;
1134  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1135    if (FD->getResultType()->isVoidType())
1136      ReturnsVoid = true;
1137    if (FD->hasAttr<NoReturnAttr>())
1138      HasNoReturn = true;
1139  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1140    if (MD->getResultType()->isVoidType())
1141      ReturnsVoid = true;
1142    if (MD->hasAttr<NoReturnAttr>())
1143      HasNoReturn = true;
1144  }
1145
1146  // Short circuit for compilation speed.
1147  if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1148       == Diagnostic::Ignored || ReturnsVoid)
1149      && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1150          == Diagnostic::Ignored || !HasNoReturn)
1151      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1152          == Diagnostic::Ignored || !ReturnsVoid))
1153    return;
1154  // FIXME: Funtion try block
1155  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1156    switch (CheckFallThrough(Body)) {
1157    case MaybeFallThrough:
1158      if (HasNoReturn)
1159        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1160      else if (!ReturnsVoid)
1161        Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1162      break;
1163    case AlwaysFallThrough:
1164      if (HasNoReturn)
1165        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1166      else if (!ReturnsVoid)
1167        Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1168      break;
1169    case NeverFallThrough:
1170      if (ReturnsVoid)
1171        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1172      break;
1173    }
1174  }
1175}
1176
1177/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1178/// that should return a value.  Check that we don't fall off the end of a
1179/// noreturn block.  We assume that functions and blocks not marked noreturn
1180/// will return.
1181void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1182  // FIXME: Would be nice if we had a better way to control cascading errors,
1183  // but for now, avoid them.  The problem is that when Parse sees:
1184  //   int foo() { return a; }
1185  // The return is eaten and the Sema code sees just:
1186  //   int foo() { }
1187  // which this code would then warn about.
1188  if (getDiagnostics().hasErrorOccurred())
1189    return;
1190  bool ReturnsVoid = false;
1191  bool HasNoReturn = false;
1192  if (const FunctionType *FT = BlockTy->getPointeeType()->getAsFunctionType()) {
1193    if (FT->getResultType()->isVoidType())
1194      ReturnsVoid = true;
1195    if (FT->getNoReturnAttr())
1196      HasNoReturn = true;
1197  }
1198
1199  // Short circuit for compilation speed.
1200  if (ReturnsVoid
1201      && !HasNoReturn
1202      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1203          == Diagnostic::Ignored || !ReturnsVoid))
1204    return;
1205  // FIXME: Funtion try block
1206  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1207    switch (CheckFallThrough(Body)) {
1208    case MaybeFallThrough:
1209      if (HasNoReturn)
1210        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1211      else if (!ReturnsVoid)
1212        Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1213      break;
1214    case AlwaysFallThrough:
1215      if (HasNoReturn)
1216        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1217      else if (!ReturnsVoid)
1218        Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1219      break;
1220    case NeverFallThrough:
1221      if (ReturnsVoid)
1222        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1223      break;
1224    }
1225  }
1226}
1227
1228/// CheckParmsForFunctionDef - Check that the parameters of the given
1229/// function are appropriate for the definition of a function. This
1230/// takes care of any checks that cannot be performed on the
1231/// declaration itself, e.g., that the types of each of the function
1232/// parameters are complete.
1233bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1234  bool HasInvalidParm = false;
1235  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1236    ParmVarDecl *Param = FD->getParamDecl(p);
1237
1238    // C99 6.7.5.3p4: the parameters in a parameter type list in a
1239    // function declarator that is part of a function definition of
1240    // that function shall not have incomplete type.
1241    //
1242    // This is also C++ [dcl.fct]p6.
1243    if (!Param->isInvalidDecl() &&
1244        RequireCompleteType(Param->getLocation(), Param->getType(),
1245                               diag::err_typecheck_decl_incomplete_type)) {
1246      Param->setInvalidDecl();
1247      HasInvalidParm = true;
1248    }
1249
1250    // C99 6.9.1p5: If the declarator includes a parameter type list, the
1251    // declaration of each parameter shall include an identifier.
1252    if (Param->getIdentifier() == 0 &&
1253        !Param->isImplicit() &&
1254        !getLangOptions().CPlusPlus)
1255      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1256  }
1257
1258  return HasInvalidParm;
1259}
1260
1261/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1262/// no declarator (e.g. "struct foo;") is parsed.
1263Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1264  // FIXME: Error on auto/register at file scope
1265  // FIXME: Error on inline/virtual/explicit
1266  // FIXME: Error on invalid restrict
1267  // FIXME: Warn on useless __thread
1268  // FIXME: Warn on useless const/volatile
1269  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1270  // FIXME: Warn on useless attributes
1271  TagDecl *Tag = 0;
1272  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1273      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1274      DS.getTypeSpecType() == DeclSpec::TST_union ||
1275      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1276    if (!DS.getTypeRep()) // We probably had an error
1277      return DeclPtrTy();
1278
1279    Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
1280  }
1281
1282  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1283    if (!Record->getDeclName() && Record->isDefinition() &&
1284        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1285      if (getLangOptions().CPlusPlus ||
1286          Record->getDeclContext()->isRecord())
1287        return BuildAnonymousStructOrUnion(S, DS, Record);
1288
1289      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1290        << DS.getSourceRange();
1291    }
1292
1293    // Microsoft allows unnamed struct/union fields. Don't complain
1294    // about them.
1295    // FIXME: Should we support Microsoft's extensions in this area?
1296    if (Record->getDeclName() && getLangOptions().Microsoft)
1297      return DeclPtrTy::make(Tag);
1298  }
1299
1300  if (!DS.isMissingDeclaratorOk() &&
1301      DS.getTypeSpecType() != DeclSpec::TST_error) {
1302    // Warn about typedefs of enums without names, since this is an
1303    // extension in both Microsoft an GNU.
1304    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1305        Tag && isa<EnumDecl>(Tag)) {
1306      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1307        << DS.getSourceRange();
1308      return DeclPtrTy::make(Tag);
1309    }
1310
1311    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1312      << DS.getSourceRange();
1313    return DeclPtrTy();
1314  }
1315
1316  return DeclPtrTy::make(Tag);
1317}
1318
1319/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1320/// anonymous struct or union AnonRecord into the owning context Owner
1321/// and scope S. This routine will be invoked just after we realize
1322/// that an unnamed union or struct is actually an anonymous union or
1323/// struct, e.g.,
1324///
1325/// @code
1326/// union {
1327///   int i;
1328///   float f;
1329/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1330///    // f into the surrounding scope.x
1331/// @endcode
1332///
1333/// This routine is recursive, injecting the names of nested anonymous
1334/// structs/unions into the owning context and scope as well.
1335bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1336                                               RecordDecl *AnonRecord) {
1337  bool Invalid = false;
1338  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1339                               FEnd = AnonRecord->field_end();
1340       F != FEnd; ++F) {
1341    if ((*F)->getDeclName()) {
1342      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
1343                                                LookupOrdinaryName, true);
1344      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
1345        // C++ [class.union]p2:
1346        //   The names of the members of an anonymous union shall be
1347        //   distinct from the names of any other entity in the
1348        //   scope in which the anonymous union is declared.
1349        unsigned diagKind
1350          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1351                                 : diag::err_anonymous_struct_member_redecl;
1352        Diag((*F)->getLocation(), diagKind)
1353          << (*F)->getDeclName();
1354        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1355        Invalid = true;
1356      } else {
1357        // C++ [class.union]p2:
1358        //   For the purpose of name lookup, after the anonymous union
1359        //   definition, the members of the anonymous union are
1360        //   considered to have been defined in the scope in which the
1361        //   anonymous union is declared.
1362        Owner->makeDeclVisibleInContext(*F);
1363        S->AddDecl(DeclPtrTy::make(*F));
1364        IdResolver.AddDecl(*F);
1365      }
1366    } else if (const RecordType *InnerRecordType
1367                 = (*F)->getType()->getAs<RecordType>()) {
1368      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1369      if (InnerRecord->isAnonymousStructOrUnion())
1370        Invalid = Invalid ||
1371          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1372    }
1373  }
1374
1375  return Invalid;
1376}
1377
1378/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1379/// anonymous structure or union. Anonymous unions are a C++ feature
1380/// (C++ [class.union]) and a GNU C extension; anonymous structures
1381/// are a GNU C and GNU C++ extension.
1382Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1383                                                  RecordDecl *Record) {
1384  DeclContext *Owner = Record->getDeclContext();
1385
1386  // Diagnose whether this anonymous struct/union is an extension.
1387  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1388    Diag(Record->getLocation(), diag::ext_anonymous_union);
1389  else if (!Record->isUnion())
1390    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1391
1392  // C and C++ require different kinds of checks for anonymous
1393  // structs/unions.
1394  bool Invalid = false;
1395  if (getLangOptions().CPlusPlus) {
1396    const char* PrevSpec = 0;
1397    unsigned DiagID;
1398    // C++ [class.union]p3:
1399    //   Anonymous unions declared in a named namespace or in the
1400    //   global namespace shall be declared static.
1401    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1402        (isa<TranslationUnitDecl>(Owner) ||
1403         (isa<NamespaceDecl>(Owner) &&
1404          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1405      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1406      Invalid = true;
1407
1408      // Recover by adding 'static'.
1409      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1410                             PrevSpec, DiagID);
1411    }
1412    // C++ [class.union]p3:
1413    //   A storage class is not allowed in a declaration of an
1414    //   anonymous union in a class scope.
1415    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1416             isa<RecordDecl>(Owner)) {
1417      Diag(DS.getStorageClassSpecLoc(),
1418           diag::err_anonymous_union_with_storage_spec);
1419      Invalid = true;
1420
1421      // Recover by removing the storage specifier.
1422      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1423                             PrevSpec, DiagID);
1424    }
1425
1426    // C++ [class.union]p2:
1427    //   The member-specification of an anonymous union shall only
1428    //   define non-static data members. [Note: nested types and
1429    //   functions cannot be declared within an anonymous union. ]
1430    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1431                                 MemEnd = Record->decls_end();
1432         Mem != MemEnd; ++Mem) {
1433      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1434        // C++ [class.union]p3:
1435        //   An anonymous union shall not have private or protected
1436        //   members (clause 11).
1437        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1438          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1439            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1440          Invalid = true;
1441        }
1442      } else if ((*Mem)->isImplicit()) {
1443        // Any implicit members are fine.
1444      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1445        // This is a type that showed up in an
1446        // elaborated-type-specifier inside the anonymous struct or
1447        // union, but which actually declares a type outside of the
1448        // anonymous struct or union. It's okay.
1449      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1450        if (!MemRecord->isAnonymousStructOrUnion() &&
1451            MemRecord->getDeclName()) {
1452          // This is a nested type declaration.
1453          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1454            << (int)Record->isUnion();
1455          Invalid = true;
1456        }
1457      } else {
1458        // We have something that isn't a non-static data
1459        // member. Complain about it.
1460        unsigned DK = diag::err_anonymous_record_bad_member;
1461        if (isa<TypeDecl>(*Mem))
1462          DK = diag::err_anonymous_record_with_type;
1463        else if (isa<FunctionDecl>(*Mem))
1464          DK = diag::err_anonymous_record_with_function;
1465        else if (isa<VarDecl>(*Mem))
1466          DK = diag::err_anonymous_record_with_static;
1467        Diag((*Mem)->getLocation(), DK)
1468            << (int)Record->isUnion();
1469          Invalid = true;
1470      }
1471    }
1472  }
1473
1474  if (!Record->isUnion() && !Owner->isRecord()) {
1475    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1476      << (int)getLangOptions().CPlusPlus;
1477    Invalid = true;
1478  }
1479
1480  // Create a declaration for this anonymous struct/union.
1481  NamedDecl *Anon = 0;
1482  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1483    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1484                             /*IdentifierInfo=*/0,
1485                             Context.getTypeDeclType(Record),
1486                             /*BitWidth=*/0, /*Mutable=*/false,
1487                             DS.getSourceRange().getBegin());
1488    Anon->setAccess(AS_public);
1489    if (getLangOptions().CPlusPlus)
1490      FieldCollector->Add(cast<FieldDecl>(Anon));
1491  } else {
1492    VarDecl::StorageClass SC;
1493    switch (DS.getStorageClassSpec()) {
1494    default: assert(0 && "Unknown storage class!");
1495    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1496    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1497    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1498    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1499    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1500    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1501    case DeclSpec::SCS_mutable:
1502      // mutable can only appear on non-static class members, so it's always
1503      // an error here
1504      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1505      Invalid = true;
1506      SC = VarDecl::None;
1507      break;
1508    }
1509
1510    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1511                           /*IdentifierInfo=*/0,
1512                           Context.getTypeDeclType(Record),
1513                           SC, DS.getSourceRange().getBegin());
1514  }
1515  Anon->setImplicit();
1516
1517  // Add the anonymous struct/union object to the current
1518  // context. We'll be referencing this object when we refer to one of
1519  // its members.
1520  Owner->addDecl(Anon);
1521
1522  // Inject the members of the anonymous struct/union into the owning
1523  // context and into the identifier resolver chain for name lookup
1524  // purposes.
1525  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1526    Invalid = true;
1527
1528  // Mark this as an anonymous struct/union type. Note that we do not
1529  // do this until after we have already checked and injected the
1530  // members of this anonymous struct/union type, because otherwise
1531  // the members could be injected twice: once by DeclContext when it
1532  // builds its lookup table, and once by
1533  // InjectAnonymousStructOrUnionMembers.
1534  Record->setAnonymousStructOrUnion(true);
1535
1536  if (Invalid)
1537    Anon->setInvalidDecl();
1538
1539  return DeclPtrTy::make(Anon);
1540}
1541
1542
1543/// GetNameForDeclarator - Determine the full declaration name for the
1544/// given Declarator.
1545DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1546  switch (D.getKind()) {
1547  case Declarator::DK_Abstract:
1548    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1549    return DeclarationName();
1550
1551  case Declarator::DK_Normal:
1552    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1553    return DeclarationName(D.getIdentifier());
1554
1555  case Declarator::DK_Constructor: {
1556    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1557    Ty = Context.getCanonicalType(Ty);
1558    return Context.DeclarationNames.getCXXConstructorName(Ty);
1559  }
1560
1561  case Declarator::DK_Destructor: {
1562    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1563    Ty = Context.getCanonicalType(Ty);
1564    return Context.DeclarationNames.getCXXDestructorName(Ty);
1565  }
1566
1567  case Declarator::DK_Conversion: {
1568    // FIXME: We'd like to keep the non-canonical type for diagnostics!
1569    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1570    Ty = Context.getCanonicalType(Ty);
1571    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1572  }
1573
1574  case Declarator::DK_Operator:
1575    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1576    return Context.DeclarationNames.getCXXOperatorName(
1577                                                D.getOverloadedOperator());
1578  }
1579
1580  assert(false && "Unknown name kind");
1581  return DeclarationName();
1582}
1583
1584/// isNearlyMatchingFunction - Determine whether the C++ functions
1585/// Declaration and Definition are "nearly" matching. This heuristic
1586/// is used to improve diagnostics in the case where an out-of-line
1587/// function definition doesn't match any declaration within
1588/// the class or namespace.
1589static bool isNearlyMatchingFunction(ASTContext &Context,
1590                                     FunctionDecl *Declaration,
1591                                     FunctionDecl *Definition) {
1592  if (Declaration->param_size() != Definition->param_size())
1593    return false;
1594  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1595    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1596    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1597
1598    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1599    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1600    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1601      return false;
1602  }
1603
1604  return true;
1605}
1606
1607Sema::DeclPtrTy
1608Sema::HandleDeclarator(Scope *S, Declarator &D,
1609                       MultiTemplateParamsArg TemplateParamLists,
1610                       bool IsFunctionDefinition) {
1611  DeclarationName Name = GetNameForDeclarator(D);
1612
1613  // All of these full declarators require an identifier.  If it doesn't have
1614  // one, the ParsedFreeStandingDeclSpec action should be used.
1615  if (!Name) {
1616    if (!D.isInvalidType())  // Reject this if we think it is valid.
1617      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1618           diag::err_declarator_need_ident)
1619        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1620    return DeclPtrTy();
1621  }
1622
1623  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1624  // we find one that is.
1625  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1626         (S->getFlags() & Scope::TemplateParamScope) != 0)
1627    S = S->getParent();
1628
1629  DeclContext *DC;
1630  NamedDecl *PrevDecl;
1631  NamedDecl *New;
1632
1633  QualType R = GetTypeForDeclarator(D, S);
1634
1635  // See if this is a redefinition of a variable in the same scope.
1636  if (D.getCXXScopeSpec().isInvalid()) {
1637    DC = CurContext;
1638    PrevDecl = 0;
1639    D.setInvalidType();
1640  } else if (!D.getCXXScopeSpec().isSet()) {
1641    LookupNameKind NameKind = LookupOrdinaryName;
1642
1643    // If the declaration we're planning to build will be a function
1644    // or object with linkage, then look for another declaration with
1645    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1646    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1647      /* Do nothing*/;
1648    else if (R->isFunctionType()) {
1649      if (CurContext->isFunctionOrMethod() ||
1650          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1651        NameKind = LookupRedeclarationWithLinkage;
1652    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1653      NameKind = LookupRedeclarationWithLinkage;
1654    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1655             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1656      NameKind = LookupRedeclarationWithLinkage;
1657
1658    DC = CurContext;
1659    PrevDecl = LookupName(S, Name, NameKind, true,
1660                          NameKind == LookupRedeclarationWithLinkage,
1661                          D.getIdentifierLoc());
1662  } else { // Something like "int foo::x;"
1663    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1664    // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
1665    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1666
1667    // C++ 7.3.1.2p2:
1668    // Members (including explicit specializations of templates) of a named
1669    // namespace can also be defined outside that namespace by explicit
1670    // qualification of the name being defined, provided that the entity being
1671    // defined was already declared in the namespace and the definition appears
1672    // after the point of declaration in a namespace that encloses the
1673    // declarations namespace.
1674    //
1675    // Note that we only check the context at this point. We don't yet
1676    // have enough information to make sure that PrevDecl is actually
1677    // the declaration we want to match. For example, given:
1678    //
1679    //   class X {
1680    //     void f();
1681    //     void f(float);
1682    //   };
1683    //
1684    //   void X::f(int) { } // ill-formed
1685    //
1686    // In this case, PrevDecl will point to the overload set
1687    // containing the two f's declared in X, but neither of them
1688    // matches.
1689
1690    // First check whether we named the global scope.
1691    if (isa<TranslationUnitDecl>(DC)) {
1692      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1693        << Name << D.getCXXScopeSpec().getRange();
1694    } else if (!CurContext->Encloses(DC)) {
1695      // The qualifying scope doesn't enclose the original declaration.
1696      // Emit diagnostic based on current scope.
1697      SourceLocation L = D.getIdentifierLoc();
1698      SourceRange R = D.getCXXScopeSpec().getRange();
1699      if (isa<FunctionDecl>(CurContext))
1700        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1701      else
1702        Diag(L, diag::err_invalid_declarator_scope)
1703          << Name << cast<NamedDecl>(DC) << R;
1704      D.setInvalidType();
1705    }
1706  }
1707
1708  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1709    // Maybe we will complain about the shadowed template parameter.
1710    if (!D.isInvalidType())
1711      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl))
1712        D.setInvalidType();
1713
1714    // Just pretend that we didn't see the previous declaration.
1715    PrevDecl = 0;
1716  }
1717
1718  // In C++, the previous declaration we find might be a tag type
1719  // (class or enum). In this case, the new declaration will hide the
1720  // tag type. Note that this does does not apply if we're declaring a
1721  // typedef (C++ [dcl.typedef]p4).
1722  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1723      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1724    PrevDecl = 0;
1725
1726  bool Redeclaration = false;
1727  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1728    if (TemplateParamLists.size()) {
1729      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
1730      return DeclPtrTy();
1731    }
1732
1733    New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl, Redeclaration);
1734  } else if (R->isFunctionType()) {
1735    New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl,
1736                                  move(TemplateParamLists),
1737                                  IsFunctionDefinition, Redeclaration);
1738  } else {
1739    New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl,
1740                                  move(TemplateParamLists),
1741                                  Redeclaration);
1742  }
1743
1744  if (New == 0)
1745    return DeclPtrTy();
1746
1747  // If this has an identifier and is not an invalid redeclaration,
1748  // add it to the scope stack.
1749  if (Name && !(Redeclaration && New->isInvalidDecl()))
1750    PushOnScopeChains(New, S);
1751
1752  return DeclPtrTy::make(New);
1753}
1754
1755/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1756/// types into constant array types in certain situations which would otherwise
1757/// be errors (for GCC compatibility).
1758static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1759                                                    ASTContext &Context,
1760                                                    bool &SizeIsNegative) {
1761  // This method tries to turn a variable array into a constant
1762  // array even when the size isn't an ICE.  This is necessary
1763  // for compatibility with code that depends on gcc's buggy
1764  // constant expression folding, like struct {char x[(int)(char*)2];}
1765  SizeIsNegative = false;
1766
1767  if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1768    QualType Pointee = PTy->getPointeeType();
1769    QualType FixedType =
1770        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1771    if (FixedType.isNull()) return FixedType;
1772    FixedType = Context.getPointerType(FixedType);
1773    FixedType.setCVRQualifiers(T.getCVRQualifiers());
1774    return FixedType;
1775  }
1776
1777  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1778  if (!VLATy)
1779    return QualType();
1780  // FIXME: We should probably handle this case
1781  if (VLATy->getElementType()->isVariablyModifiedType())
1782    return QualType();
1783
1784  Expr::EvalResult EvalResult;
1785  if (!VLATy->getSizeExpr() ||
1786      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1787      !EvalResult.Val.isInt())
1788    return QualType();
1789
1790  llvm::APSInt &Res = EvalResult.Val.getInt();
1791  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
1792    Expr* ArySizeExpr = VLATy->getSizeExpr();
1793    // FIXME: here we could "steal" (how?) ArySizeExpr from the VLA,
1794    // so as to transfer ownership to the ConstantArrayWithExpr.
1795    // Alternatively, we could "clone" it (how?).
1796    // Since we don't know how to do things above, we just use the
1797    // very same Expr*.
1798    return Context.getConstantArrayWithExprType(VLATy->getElementType(),
1799                                                Res, ArySizeExpr,
1800                                                ArrayType::Normal, 0,
1801                                                VLATy->getBracketsRange());
1802  }
1803
1804  SizeIsNegative = true;
1805  return QualType();
1806}
1807
1808/// \brief Register the given locally-scoped external C declaration so
1809/// that it can be found later for redeclarations
1810void
1811Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1812                                       Scope *S) {
1813  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1814         "Decl is not a locally-scoped decl!");
1815  // Note that we have a locally-scoped external with this name.
1816  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1817
1818  if (!PrevDecl)
1819    return;
1820
1821  // If there was a previous declaration of this variable, it may be
1822  // in our identifier chain. Update the identifier chain with the new
1823  // declaration.
1824  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
1825    // The previous declaration was found on the identifer resolver
1826    // chain, so remove it from its scope.
1827    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
1828      S = S->getParent();
1829
1830    if (S)
1831      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
1832  }
1833}
1834
1835/// \brief Diagnose function specifiers on a declaration of an identifier that
1836/// does not identify a function.
1837void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
1838  // FIXME: We should probably indicate the identifier in question to avoid
1839  // confusion for constructs like "inline int a(), b;"
1840  if (D.getDeclSpec().isInlineSpecified())
1841    Diag(D.getDeclSpec().getInlineSpecLoc(),
1842         diag::err_inline_non_function);
1843
1844  if (D.getDeclSpec().isVirtualSpecified())
1845    Diag(D.getDeclSpec().getVirtualSpecLoc(),
1846         diag::err_virtual_non_function);
1847
1848  if (D.getDeclSpec().isExplicitSpecified())
1849    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1850         diag::err_explicit_non_function);
1851}
1852
1853NamedDecl*
1854Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1855                             QualType R, Decl* PrevDecl, bool &Redeclaration) {
1856  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1857  if (D.getCXXScopeSpec().isSet()) {
1858    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1859      << D.getCXXScopeSpec().getRange();
1860    D.setInvalidType();
1861    // Pretend we didn't see the scope specifier.
1862    DC = 0;
1863  }
1864
1865  if (getLangOptions().CPlusPlus) {
1866    // Check that there are no default arguments (C++ only).
1867    CheckExtraCXXDefaultArguments(D);
1868  }
1869
1870  DiagnoseFunctionSpecifiers(D);
1871
1872  if (D.getDeclSpec().isThreadSpecified())
1873    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1874
1875  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R);
1876  if (!NewTD) return 0;
1877
1878  if (D.isInvalidType())
1879    NewTD->setInvalidDecl();
1880
1881  // Handle attributes prior to checking for duplicates in MergeVarDecl
1882  ProcessDeclAttributes(S, NewTD, D);
1883  // Merge the decl with the existing one if appropriate. If the decl is
1884  // in an outer scope, it isn't the same thing.
1885  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1886    Redeclaration = true;
1887    MergeTypeDefDecl(NewTD, PrevDecl);
1888  }
1889
1890  // C99 6.7.7p2: If a typedef name specifies a variably modified type
1891  // then it shall have block scope.
1892  QualType T = NewTD->getUnderlyingType();
1893  if (T->isVariablyModifiedType()) {
1894    CurFunctionNeedsScopeChecking = true;
1895
1896    if (S->getFnParent() == 0) {
1897      bool SizeIsNegative;
1898      QualType FixedTy =
1899          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1900      if (!FixedTy.isNull()) {
1901        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1902        NewTD->setUnderlyingType(FixedTy);
1903      } else {
1904        if (SizeIsNegative)
1905          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1906        else if (T->isVariableArrayType())
1907          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1908        else
1909          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1910        NewTD->setInvalidDecl();
1911      }
1912    }
1913  }
1914
1915  // If this is the C FILE type, notify the AST context.
1916  if (IdentifierInfo *II = NewTD->getIdentifier())
1917    if (!NewTD->isInvalidDecl() &&
1918        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
1919      if (II->isStr("FILE"))
1920        Context.setFILEDecl(NewTD);
1921      else if (II->isStr("jmp_buf"))
1922        Context.setjmp_bufDecl(NewTD);
1923      else if (II->isStr("sigjmp_buf"))
1924        Context.setsigjmp_bufDecl(NewTD);
1925    }
1926
1927  return NewTD;
1928}
1929
1930/// \brief Determines whether the given declaration is an out-of-scope
1931/// previous declaration.
1932///
1933/// This routine should be invoked when name lookup has found a
1934/// previous declaration (PrevDecl) that is not in the scope where a
1935/// new declaration by the same name is being introduced. If the new
1936/// declaration occurs in a local scope, previous declarations with
1937/// linkage may still be considered previous declarations (C99
1938/// 6.2.2p4-5, C++ [basic.link]p6).
1939///
1940/// \param PrevDecl the previous declaration found by name
1941/// lookup
1942///
1943/// \param DC the context in which the new declaration is being
1944/// declared.
1945///
1946/// \returns true if PrevDecl is an out-of-scope previous declaration
1947/// for a new delcaration with the same name.
1948static bool
1949isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1950                                ASTContext &Context) {
1951  if (!PrevDecl)
1952    return 0;
1953
1954  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1955  // case we need to check each of the overloaded functions.
1956  if (!PrevDecl->hasLinkage())
1957    return false;
1958
1959  if (Context.getLangOptions().CPlusPlus) {
1960    // C++ [basic.link]p6:
1961    //   If there is a visible declaration of an entity with linkage
1962    //   having the same name and type, ignoring entities declared
1963    //   outside the innermost enclosing namespace scope, the block
1964    //   scope declaration declares that same entity and receives the
1965    //   linkage of the previous declaration.
1966    DeclContext *OuterContext = DC->getLookupContext();
1967    if (!OuterContext->isFunctionOrMethod())
1968      // This rule only applies to block-scope declarations.
1969      return false;
1970    else {
1971      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1972      if (PrevOuterContext->isRecord())
1973        // We found a member function: ignore it.
1974        return false;
1975      else {
1976        // Find the innermost enclosing namespace for the new and
1977        // previous declarations.
1978        while (!OuterContext->isFileContext())
1979          OuterContext = OuterContext->getParent();
1980        while (!PrevOuterContext->isFileContext())
1981          PrevOuterContext = PrevOuterContext->getParent();
1982
1983        // The previous declaration is in a different namespace, so it
1984        // isn't the same function.
1985        if (OuterContext->getPrimaryContext() !=
1986            PrevOuterContext->getPrimaryContext())
1987          return false;
1988      }
1989    }
1990  }
1991
1992  return true;
1993}
1994
1995NamedDecl*
1996Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1997                              QualType R,NamedDecl* PrevDecl,
1998                              MultiTemplateParamsArg TemplateParamLists,
1999                              bool &Redeclaration) {
2000  DeclarationName Name = GetNameForDeclarator(D);
2001
2002  // Check that there are no default arguments (C++ only).
2003  if (getLangOptions().CPlusPlus)
2004    CheckExtraCXXDefaultArguments(D);
2005
2006  VarDecl *NewVD;
2007  VarDecl::StorageClass SC;
2008  switch (D.getDeclSpec().getStorageClassSpec()) {
2009  default: assert(0 && "Unknown storage class!");
2010  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
2011  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
2012  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
2013  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
2014  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
2015  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2016  case DeclSpec::SCS_mutable:
2017    // mutable can only appear on non-static class members, so it's always
2018    // an error here
2019    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2020    D.setInvalidType();
2021    SC = VarDecl::None;
2022    break;
2023  }
2024
2025  IdentifierInfo *II = Name.getAsIdentifierInfo();
2026  if (!II) {
2027    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2028      << Name.getAsString();
2029    return 0;
2030  }
2031
2032  DiagnoseFunctionSpecifiers(D);
2033
2034  if (!DC->isRecord() && S->getFnParent() == 0) {
2035    // C99 6.9p2: The storage-class specifiers auto and register shall not
2036    // appear in the declaration specifiers in an external declaration.
2037    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2038
2039      // If this is a register variable with an asm label specified, then this
2040      // is a GNU extension.
2041      if (SC == VarDecl::Register && D.getAsmLabel())
2042        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2043      else
2044        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2045      D.setInvalidType();
2046    }
2047  }
2048  if (DC->isRecord() && !CurContext->isRecord()) {
2049    // This is an out-of-line definition of a static data member.
2050    if (SC == VarDecl::Static) {
2051      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2052           diag::err_static_out_of_line)
2053        << CodeModificationHint::CreateRemoval(
2054                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2055    } else if (SC == VarDecl::None)
2056      SC = VarDecl::Static;
2057  }
2058  if (SC == VarDecl::Static) {
2059    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2060      if (RD->isLocalClass())
2061        Diag(D.getIdentifierLoc(),
2062             diag::err_static_data_member_not_allowed_in_local_class)
2063          << Name << RD->getDeclName();
2064    }
2065  }
2066
2067  // Check that we can declare a template here.
2068  if (TemplateParamLists.size() &&
2069      CheckTemplateDeclScope(S, TemplateParamLists))
2070    return 0;
2071
2072  // Match up the template parameter lists with the scope specifier, then
2073  // determine whether we have a template or a template specialization.
2074  if (TemplateParameterList *TemplateParams
2075      = MatchTemplateParametersToScopeSpecifier(
2076                                  D.getDeclSpec().getSourceRange().getBegin(),
2077                                                D.getCXXScopeSpec(),
2078                        (TemplateParameterList**)TemplateParamLists.get(),
2079                                                 TemplateParamLists.size())) {
2080    if (TemplateParams->size() > 0) {
2081      // There is no such thing as a variable template.
2082      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2083        << II
2084        << SourceRange(TemplateParams->getTemplateLoc(),
2085                       TemplateParams->getRAngleLoc());
2086      return 0;
2087    } else {
2088      // There is an extraneous 'template<>' for this variable. Complain
2089      // about it, but allow the declaration of the variable.
2090      Diag(TemplateParams->getTemplateLoc(),
2091           diag::err_template_variable_noparams)
2092        << II
2093        << SourceRange(TemplateParams->getTemplateLoc(),
2094                       TemplateParams->getRAngleLoc());
2095    }
2096  }
2097
2098  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2099                          II, R, SC,
2100                          // FIXME: Move to DeclGroup...
2101                          D.getDeclSpec().getSourceRange().getBegin());
2102
2103  if (D.isInvalidType())
2104    NewVD->setInvalidDecl();
2105
2106  if (D.getDeclSpec().isThreadSpecified()) {
2107    if (NewVD->hasLocalStorage())
2108      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2109    else if (!Context.Target.isTLSSupported())
2110      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2111    else
2112      NewVD->setThreadSpecified(true);
2113  }
2114
2115  // Set the lexical context. If the declarator has a C++ scope specifier, the
2116  // lexical context will be different from the semantic context.
2117  NewVD->setLexicalDeclContext(CurContext);
2118
2119  // Handle attributes prior to checking for duplicates in MergeVarDecl
2120  ProcessDeclAttributes(S, NewVD, D);
2121
2122  // Handle GNU asm-label extension (encoded as an attribute).
2123  if (Expr *E = (Expr*) D.getAsmLabel()) {
2124    // The parser guarantees this is a string.
2125    StringLiteral *SE = cast<StringLiteral>(E);
2126    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2127                                                        SE->getByteLength())));
2128  }
2129
2130  // If name lookup finds a previous declaration that is not in the
2131  // same scope as the new declaration, this may still be an
2132  // acceptable redeclaration.
2133  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2134      !(NewVD->hasLinkage() &&
2135        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2136    PrevDecl = 0;
2137
2138  // Merge the decl with the existing one if appropriate.
2139  if (PrevDecl) {
2140    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
2141      // The user tried to define a non-static data member
2142      // out-of-line (C++ [dcl.meaning]p1).
2143      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2144        << D.getCXXScopeSpec().getRange();
2145      PrevDecl = 0;
2146      NewVD->setInvalidDecl();
2147    }
2148  } else if (D.getCXXScopeSpec().isSet()) {
2149    // No previous declaration in the qualifying scope.
2150    Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
2151      << Name << D.getCXXScopeSpec().getRange();
2152    NewVD->setInvalidDecl();
2153  }
2154
2155  CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration);
2156
2157  // attributes declared post-definition are currently ignored
2158  if (PrevDecl) {
2159    const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl);
2160    if (PrevVD->getDefinition(Def) && D.hasAttributes()) {
2161      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2162      Diag(Def->getLocation(), diag::note_previous_definition);
2163    }
2164  }
2165
2166  // If this is a locally-scoped extern C variable, update the map of
2167  // such variables.
2168  if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
2169      !NewVD->isInvalidDecl())
2170    RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
2171
2172  return NewVD;
2173}
2174
2175/// \brief Perform semantic checking on a newly-created variable
2176/// declaration.
2177///
2178/// This routine performs all of the type-checking required for a
2179/// variable declaration once it has been built. It is used both to
2180/// check variables after they have been parsed and their declarators
2181/// have been translated into a declaration, and to check variables
2182/// that have been instantiated from a template.
2183///
2184/// Sets NewVD->isInvalidDecl() if an error was encountered.
2185void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
2186                                    bool &Redeclaration) {
2187  // If the decl is already known invalid, don't check it.
2188  if (NewVD->isInvalidDecl())
2189    return;
2190
2191  QualType T = NewVD->getType();
2192
2193  if (T->isObjCInterfaceType()) {
2194    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2195    return NewVD->setInvalidDecl();
2196  }
2197
2198  // The variable can not have an abstract class type.
2199  if (RequireNonAbstractType(NewVD->getLocation(), T,
2200                             diag::err_abstract_type_in_decl,
2201                             AbstractVariableType))
2202    return NewVD->setInvalidDecl();
2203
2204  // Emit an error if an address space was applied to decl with local storage.
2205  // This includes arrays of objects with address space qualifiers, but not
2206  // automatic variables that point to other address spaces.
2207  // ISO/IEC TR 18037 S5.1.2
2208  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2209    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2210    return NewVD->setInvalidDecl();
2211  }
2212
2213  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2214      && !NewVD->hasAttr<BlocksAttr>())
2215    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2216
2217  bool isVM = T->isVariablyModifiedType();
2218  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2219      NewVD->hasAttr<BlocksAttr>())
2220    CurFunctionNeedsScopeChecking = true;
2221
2222  if ((isVM && NewVD->hasLinkage()) ||
2223      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2224    bool SizeIsNegative;
2225    QualType FixedTy =
2226        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2227
2228    if (FixedTy.isNull() && T->isVariableArrayType()) {
2229      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2230      // FIXME: This won't give the correct result for
2231      // int a[10][n];
2232      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2233
2234      if (NewVD->isFileVarDecl())
2235        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2236        << SizeRange;
2237      else if (NewVD->getStorageClass() == VarDecl::Static)
2238        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2239        << SizeRange;
2240      else
2241        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2242        << SizeRange;
2243      return NewVD->setInvalidDecl();
2244    }
2245
2246    if (FixedTy.isNull()) {
2247      if (NewVD->isFileVarDecl())
2248        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2249      else
2250        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2251      return NewVD->setInvalidDecl();
2252    }
2253
2254    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2255    NewVD->setType(FixedTy);
2256  }
2257
2258  if (!PrevDecl && NewVD->isExternC(Context)) {
2259    // Since we did not find anything by this name and we're declaring
2260    // an extern "C" variable, look for a non-visible extern "C"
2261    // declaration with the same name.
2262    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2263      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2264    if (Pos != LocallyScopedExternalDecls.end())
2265      PrevDecl = Pos->second;
2266  }
2267
2268  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2269    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2270      << T;
2271    return NewVD->setInvalidDecl();
2272  }
2273
2274  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2275    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2276    return NewVD->setInvalidDecl();
2277  }
2278
2279  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2280    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2281    return NewVD->setInvalidDecl();
2282  }
2283
2284  if (PrevDecl) {
2285    Redeclaration = true;
2286    MergeVarDecl(NewVD, PrevDecl);
2287  }
2288}
2289
2290NamedDecl*
2291Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2292                              QualType R, NamedDecl* PrevDecl,
2293                              MultiTemplateParamsArg TemplateParamLists,
2294                              bool IsFunctionDefinition, bool &Redeclaration) {
2295  assert(R.getTypePtr()->isFunctionType());
2296
2297  DeclarationName Name = GetNameForDeclarator(D);
2298  FunctionDecl::StorageClass SC = FunctionDecl::None;
2299  switch (D.getDeclSpec().getStorageClassSpec()) {
2300  default: assert(0 && "Unknown storage class!");
2301  case DeclSpec::SCS_auto:
2302  case DeclSpec::SCS_register:
2303  case DeclSpec::SCS_mutable:
2304    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2305         diag::err_typecheck_sclass_func);
2306    D.setInvalidType();
2307    break;
2308  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2309  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2310  case DeclSpec::SCS_static: {
2311    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2312      // C99 6.7.1p5:
2313      //   The declaration of an identifier for a function that has
2314      //   block scope shall have no explicit storage-class specifier
2315      //   other than extern
2316      // See also (C++ [dcl.stc]p4).
2317      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2318           diag::err_static_block_func);
2319      SC = FunctionDecl::None;
2320    } else
2321      SC = FunctionDecl::Static;
2322    break;
2323  }
2324  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2325  }
2326
2327  if (D.getDeclSpec().isThreadSpecified())
2328    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2329
2330  bool isInline = D.getDeclSpec().isInlineSpecified();
2331  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2332  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2333
2334  // Check that the return type is not an abstract class type.
2335  // For record types, this is done by the AbstractClassUsageDiagnoser once
2336  // the class has been completely parsed.
2337  if (!DC->isRecord() &&
2338      RequireNonAbstractType(D.getIdentifierLoc(),
2339                             R->getAsFunctionType()->getResultType(),
2340                             diag::err_abstract_type_in_decl,
2341                             AbstractReturnType))
2342    D.setInvalidType();
2343
2344  // Do not allow returning a objc interface by-value.
2345  if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) {
2346    Diag(D.getIdentifierLoc(),
2347         diag::err_object_cannot_be_passed_returned_by_value) << 0
2348      << R->getAsFunctionType()->getResultType();
2349    D.setInvalidType();
2350  }
2351
2352  // Check that we can declare a template here.
2353  if (TemplateParamLists.size() &&
2354      CheckTemplateDeclScope(S, TemplateParamLists))
2355    return 0;
2356
2357  bool isVirtualOkay = false;
2358  FunctionDecl *NewFD;
2359  if (D.getKind() == Declarator::DK_Constructor) {
2360    // This is a C++ constructor declaration.
2361    assert(DC->isRecord() &&
2362           "Constructors can only be declared in a member context");
2363
2364    R = CheckConstructorDeclarator(D, R, SC);
2365
2366    // Create the new declaration
2367    NewFD = CXXConstructorDecl::Create(Context,
2368                                       cast<CXXRecordDecl>(DC),
2369                                       D.getIdentifierLoc(), Name, R,
2370                                       isExplicit, isInline,
2371                                       /*isImplicitlyDeclared=*/false);
2372  } else if (D.getKind() == Declarator::DK_Destructor) {
2373    // This is a C++ destructor declaration.
2374    if (DC->isRecord()) {
2375      R = CheckDestructorDeclarator(D, SC);
2376
2377      NewFD = CXXDestructorDecl::Create(Context,
2378                                        cast<CXXRecordDecl>(DC),
2379                                        D.getIdentifierLoc(), Name, R,
2380                                        isInline,
2381                                        /*isImplicitlyDeclared=*/false);
2382
2383      isVirtualOkay = true;
2384    } else {
2385      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2386
2387      // Create a FunctionDecl to satisfy the function definition parsing
2388      // code path.
2389      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2390                                   Name, R, SC, isInline,
2391                                   /*hasPrototype=*/true,
2392                                   // FIXME: Move to DeclGroup...
2393                                   D.getDeclSpec().getSourceRange().getBegin());
2394      D.setInvalidType();
2395    }
2396  } else if (D.getKind() == Declarator::DK_Conversion) {
2397    if (!DC->isRecord()) {
2398      Diag(D.getIdentifierLoc(),
2399           diag::err_conv_function_not_member);
2400      return 0;
2401    }
2402
2403    CheckConversionDeclarator(D, R, SC);
2404    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2405                                      D.getIdentifierLoc(), Name, R,
2406                                      isInline, isExplicit);
2407
2408    isVirtualOkay = true;
2409  } else if (DC->isRecord()) {
2410    // If the of the function is the same as the name of the record, then this
2411    // must be an invalid constructor that has a return type.
2412    // (The parser checks for a return type and makes the declarator a
2413    // constructor if it has no return type).
2414    // must have an invalid constructor that has a return type
2415    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2416      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2417        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2418        << SourceRange(D.getIdentifierLoc());
2419      return 0;
2420    }
2421
2422    // This is a C++ method declaration.
2423    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2424                                  D.getIdentifierLoc(), Name, R,
2425                                  (SC == FunctionDecl::Static), isInline);
2426
2427    isVirtualOkay = (SC != FunctionDecl::Static);
2428  } else {
2429    // Determine whether the function was written with a
2430    // prototype. This true when:
2431    //   - we're in C++ (where every function has a prototype),
2432    //   - there is a prototype in the declarator, or
2433    //   - the type R of the function is some kind of typedef or other reference
2434    //     to a type name (which eventually refers to a function type).
2435    bool HasPrototype =
2436       getLangOptions().CPlusPlus ||
2437       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2438       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2439
2440    NewFD = FunctionDecl::Create(Context, DC,
2441                                 D.getIdentifierLoc(),
2442                                 Name, R, SC, isInline, HasPrototype,
2443                                 // FIXME: Move to DeclGroup...
2444                                 D.getDeclSpec().getSourceRange().getBegin());
2445  }
2446
2447  if (D.isInvalidType())
2448    NewFD->setInvalidDecl();
2449
2450  // Set the lexical context. If the declarator has a C++
2451  // scope specifier, the lexical context will be different
2452  // from the semantic context.
2453  NewFD->setLexicalDeclContext(CurContext);
2454
2455  // Match up the template parameter lists with the scope specifier, then
2456  // determine whether we have a template or a template specialization.
2457  FunctionTemplateDecl *FunctionTemplate = 0;
2458  if (TemplateParameterList *TemplateParams
2459        = MatchTemplateParametersToScopeSpecifier(
2460                                  D.getDeclSpec().getSourceRange().getBegin(),
2461                                  D.getCXXScopeSpec(),
2462                           (TemplateParameterList**)TemplateParamLists.get(),
2463                                                  TemplateParamLists.size())) {
2464    if (TemplateParams->size() > 0) {
2465      // This is a function template
2466      FunctionTemplate = FunctionTemplateDecl::Create(Context, CurContext,
2467                                                      NewFD->getLocation(),
2468                                                      Name, TemplateParams,
2469                                                      NewFD);
2470      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2471    } else {
2472      // FIXME: Handle function template specializations
2473    }
2474
2475    // FIXME: Free this memory properly.
2476    TemplateParamLists.release();
2477  }
2478
2479  // C++ [dcl.fct.spec]p5:
2480  //   The virtual specifier shall only be used in declarations of
2481  //   nonstatic class member functions that appear within a
2482  //   member-specification of a class declaration; see 10.3.
2483  //
2484  if (isVirtual && !NewFD->isInvalidDecl()) {
2485    if (!isVirtualOkay) {
2486       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2487           diag::err_virtual_non_function);
2488    } else if (!CurContext->isRecord()) {
2489      // 'virtual' was specified outside of the class.
2490      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2491        << CodeModificationHint::CreateRemoval(
2492                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2493    } else {
2494      // Okay: Add virtual to the method.
2495      cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
2496      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2497      CurClass->setAggregate(false);
2498      CurClass->setPOD(false);
2499      CurClass->setPolymorphic(true);
2500      CurClass->setHasTrivialConstructor(false);
2501      CurClass->setHasTrivialCopyConstructor(false);
2502      CurClass->setHasTrivialCopyAssignment(false);
2503    }
2504  }
2505
2506  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) {
2507    // Look for virtual methods in base classes that this method might override.
2508
2509    BasePaths Paths;
2510    if (LookupInBases(cast<CXXRecordDecl>(DC),
2511                      MemberLookupCriteria(NewMD), Paths)) {
2512      for (BasePaths::decl_iterator I = Paths.found_decls_begin(),
2513           E = Paths.found_decls_end(); I != E; ++I) {
2514        if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2515          if (!CheckOverridingFunctionReturnType(NewMD, OldMD) &&
2516              !CheckOverridingFunctionExceptionSpec(NewMD, OldMD))
2517            NewMD->addOverriddenMethod(OldMD);
2518        }
2519      }
2520    }
2521  }
2522
2523  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2524      !CurContext->isRecord()) {
2525    // C++ [class.static]p1:
2526    //   A data or function member of a class may be declared static
2527    //   in a class definition, in which case it is a static member of
2528    //   the class.
2529
2530    // Complain about the 'static' specifier if it's on an out-of-line
2531    // member function definition.
2532    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2533         diag::err_static_out_of_line)
2534      << CodeModificationHint::CreateRemoval(
2535                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2536  }
2537
2538  // Handle GNU asm-label extension (encoded as an attribute).
2539  if (Expr *E = (Expr*) D.getAsmLabel()) {
2540    // The parser guarantees this is a string.
2541    StringLiteral *SE = cast<StringLiteral>(E);
2542    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2543                                                        SE->getByteLength())));
2544  }
2545
2546  // Copy the parameter declarations from the declarator D to the function
2547  // declaration NewFD, if they are available.  First scavenge them into Params.
2548  llvm::SmallVector<ParmVarDecl*, 16> Params;
2549  if (D.getNumTypeObjects() > 0) {
2550    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2551
2552    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2553    // function that takes no arguments, not a function that takes a
2554    // single void argument.
2555    // We let through "const void" here because Sema::GetTypeForDeclarator
2556    // already checks for that case.
2557    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2558        FTI.ArgInfo[0].Param &&
2559        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2560      // Empty arg list, don't push any params.
2561      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2562
2563      // In C++, the empty parameter-type-list must be spelled "void"; a
2564      // typedef of void is not permitted.
2565      if (getLangOptions().CPlusPlus &&
2566          Param->getType().getUnqualifiedType() != Context.VoidTy)
2567        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2568      // FIXME: Leaks decl?
2569    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2570      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2571        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2572        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2573        Param->setDeclContext(NewFD);
2574        Params.push_back(Param);
2575      }
2576    }
2577
2578  } else if (const FunctionProtoType *FT = R->getAsFunctionProtoType()) {
2579    // When we're declaring a function with a typedef, typeof, etc as in the
2580    // following example, we'll need to synthesize (unnamed)
2581    // parameters for use in the declaration.
2582    //
2583    // @code
2584    // typedef void fn(int);
2585    // fn f;
2586    // @endcode
2587
2588    // Synthesize a parameter for each argument type.
2589    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2590         AE = FT->arg_type_end(); AI != AE; ++AI) {
2591      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2592                                               SourceLocation(), 0,
2593                                               *AI, VarDecl::None, 0);
2594      Param->setImplicit();
2595      Params.push_back(Param);
2596    }
2597  } else {
2598    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2599           "Should not need args for typedef of non-prototype fn");
2600  }
2601  // Finally, we know we have the right number of parameters, install them.
2602  NewFD->setParams(Context, Params.data(), Params.size());
2603
2604  // If name lookup finds a previous declaration that is not in the
2605  // same scope as the new declaration, this may still be an
2606  // acceptable redeclaration.
2607  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2608      !(NewFD->hasLinkage() &&
2609        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2610    PrevDecl = 0;
2611
2612  // Perform semantic checking on the function declaration.
2613  bool OverloadableAttrRequired = false; // FIXME: HACK!
2614  CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration,
2615                           /*FIXME:*/OverloadableAttrRequired);
2616
2617  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
2618    // An out-of-line member function declaration must also be a
2619    // definition (C++ [dcl.meaning]p1).
2620    if (!IsFunctionDefinition) {
2621      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2622        << D.getCXXScopeSpec().getRange();
2623      NewFD->setInvalidDecl();
2624    } else if (!Redeclaration && (!PrevDecl || !isa<UsingDecl>(PrevDecl))) {
2625      // The user tried to provide an out-of-line definition for a
2626      // function that is a member of a class or namespace, but there
2627      // was no such member function declared (C++ [class.mfct]p2,
2628      // C++ [namespace.memdef]p2). For example:
2629      //
2630      // class X {
2631      //   void f() const;
2632      // };
2633      //
2634      // void X::f() { } // ill-formed
2635      //
2636      // Complain about this problem, and attempt to suggest close
2637      // matches (e.g., those that differ only in cv-qualifiers and
2638      // whether the parameter types are references).
2639      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
2640        << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
2641      NewFD->setInvalidDecl();
2642
2643      LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2644                                              true);
2645      assert(!Prev.isAmbiguous() &&
2646             "Cannot have an ambiguity in previous-declaration lookup");
2647      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2648           Func != FuncEnd; ++Func) {
2649        if (isa<FunctionDecl>(*Func) &&
2650            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2651          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
2652      }
2653
2654      PrevDecl = 0;
2655    }
2656  }
2657
2658  // Handle attributes. We need to have merged decls when handling attributes
2659  // (for example to check for conflicts, etc).
2660  // FIXME: This needs to happen before we merge declarations. Then,
2661  // let attribute merging cope with attribute conflicts.
2662  ProcessDeclAttributes(S, NewFD, D);
2663
2664  // attributes declared post-definition are currently ignored
2665  if (PrevDecl) {
2666    const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl);
2667    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
2668      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
2669      Diag(Def->getLocation(), diag::note_previous_definition);
2670    }
2671  }
2672
2673  AddKnownFunctionAttributes(NewFD);
2674
2675  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2676    // If a function name is overloadable in C, then every function
2677    // with that name must be marked "overloadable".
2678    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2679      << Redeclaration << NewFD;
2680    if (PrevDecl)
2681      Diag(PrevDecl->getLocation(),
2682           diag::note_attribute_overloadable_prev_overload);
2683    NewFD->addAttr(::new (Context) OverloadableAttr());
2684  }
2685
2686  // If this is a locally-scoped extern C function, update the
2687  // map of such names.
2688  if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context)
2689      && !NewFD->isInvalidDecl())
2690    RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2691
2692  // Set this FunctionDecl's range up to the right paren.
2693  NewFD->setLocEnd(D.getSourceRange().getEnd());
2694
2695  if (FunctionTemplate && NewFD->isInvalidDecl())
2696    FunctionTemplate->setInvalidDecl();
2697
2698  if (FunctionTemplate)
2699    return FunctionTemplate;
2700
2701  return NewFD;
2702}
2703
2704/// \brief Perform semantic checking of a new function declaration.
2705///
2706/// Performs semantic analysis of the new function declaration
2707/// NewFD. This routine performs all semantic checking that does not
2708/// require the actual declarator involved in the declaration, and is
2709/// used both for the declaration of functions as they are parsed
2710/// (called via ActOnDeclarator) and for the declaration of functions
2711/// that have been instantiated via C++ template instantiation (called
2712/// via InstantiateDecl).
2713///
2714/// This sets NewFD->isInvalidDecl() to true if there was an error.
2715void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
2716                                    bool &Redeclaration,
2717                                    bool &OverloadableAttrRequired) {
2718  // If NewFD is already known erroneous, don't do any of this checking.
2719  if (NewFD->isInvalidDecl())
2720    return;
2721
2722  if (NewFD->getResultType()->isVariablyModifiedType()) {
2723    // Functions returning a variably modified type violate C99 6.7.5.2p2
2724    // because all functions have linkage.
2725    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
2726    return NewFD->setInvalidDecl();
2727  }
2728
2729  if (NewFD->isMain()) CheckMain(NewFD);
2730
2731  // Semantic checking for this function declaration (in isolation).
2732  if (getLangOptions().CPlusPlus) {
2733    // C++-specific checks.
2734    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
2735      CheckConstructor(Constructor);
2736    } else if (isa<CXXDestructorDecl>(NewFD)) {
2737      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
2738      QualType ClassType = Context.getTypeDeclType(Record);
2739      if (!ClassType->isDependentType()) {
2740        ClassType = Context.getCanonicalType(ClassType);
2741        DeclarationName Name
2742          = Context.DeclarationNames.getCXXDestructorName(ClassType);
2743        if (NewFD->getDeclName() != Name) {
2744          Diag(NewFD->getLocation(), diag::err_destructor_name);
2745          return NewFD->setInvalidDecl();
2746        }
2747      }
2748      Record->setUserDeclaredDestructor(true);
2749      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
2750      // user-defined destructor.
2751      Record->setPOD(false);
2752
2753      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
2754      // declared destructor.
2755      // FIXME: C++0x: don't do this for "= default" destructors
2756      Record->setHasTrivialDestructor(false);
2757    } else if (CXXConversionDecl *Conversion
2758               = dyn_cast<CXXConversionDecl>(NewFD))
2759      ActOnConversionDeclarator(Conversion);
2760
2761    // Extra checking for C++ overloaded operators (C++ [over.oper]).
2762    if (NewFD->isOverloadedOperator() &&
2763        CheckOverloadedOperatorDeclaration(NewFD))
2764      return NewFD->setInvalidDecl();
2765  }
2766
2767  // C99 6.7.4p6:
2768  //   [... ] For a function with external linkage, the following
2769  //   restrictions apply: [...] If all of the file scope declarations
2770  //   for a function in a translation unit include the inline
2771  //   function specifier without extern, then the definition in that
2772  //   translation unit is an inline definition. An inline definition
2773  //   does not provide an external definition for the function, and
2774  //   does not forbid an external definition in another translation
2775  //   unit.
2776  //
2777  // Here we determine whether this function, in isolation, would be a
2778  // C99 inline definition. MergeCompatibleFunctionDecls looks at
2779  // previous declarations.
2780  if (NewFD->isInline() && getLangOptions().C99 &&
2781      NewFD->getStorageClass() == FunctionDecl::None &&
2782      NewFD->getDeclContext()->getLookupContext()->isTranslationUnit())
2783    NewFD->setC99InlineDefinition(true);
2784
2785  // Check for a previous declaration of this name.
2786  if (!PrevDecl && NewFD->isExternC(Context)) {
2787    // Since we did not find anything by this name and we're declaring
2788    // an extern "C" function, look for a non-visible extern "C"
2789    // declaration with the same name.
2790    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2791      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
2792    if (Pos != LocallyScopedExternalDecls.end())
2793      PrevDecl = Pos->second;
2794  }
2795
2796  // Merge or overload the declaration with an existing declaration of
2797  // the same name, if appropriate.
2798  if (PrevDecl) {
2799    // Determine whether NewFD is an overload of PrevDecl or
2800    // a declaration that requires merging. If it's an overload,
2801    // there's no more work to do here; we'll just add the new
2802    // function to the scope.
2803    OverloadedFunctionDecl::function_iterator MatchedDecl;
2804
2805    if (!getLangOptions().CPlusPlus &&
2806        AllowOverloadingOfFunction(PrevDecl, Context)) {
2807      OverloadableAttrRequired = true;
2808
2809      // Functions marked "overloadable" must have a prototype (that
2810      // we can't get through declaration merging).
2811      if (!NewFD->getType()->getAsFunctionProtoType()) {
2812        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
2813          << NewFD;
2814        Redeclaration = true;
2815
2816        // Turn this into a variadic function with no parameters.
2817        QualType R = Context.getFunctionType(
2818                       NewFD->getType()->getAsFunctionType()->getResultType(),
2819                       0, 0, true, 0);
2820        NewFD->setType(R);
2821        return NewFD->setInvalidDecl();
2822      }
2823    }
2824
2825    if (PrevDecl &&
2826        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2827         !IsOverload(NewFD, PrevDecl, MatchedDecl)) &&
2828        !isa<UsingDecl>(PrevDecl)) {
2829      Redeclaration = true;
2830      Decl *OldDecl = PrevDecl;
2831
2832      // If PrevDecl was an overloaded function, extract the
2833      // FunctionDecl that matched.
2834      if (isa<OverloadedFunctionDecl>(PrevDecl))
2835        OldDecl = *MatchedDecl;
2836
2837      // NewFD and OldDecl represent declarations that need to be
2838      // merged.
2839      if (MergeFunctionDecl(NewFD, OldDecl))
2840        return NewFD->setInvalidDecl();
2841
2842      if (FunctionTemplateDecl *OldTemplateDecl
2843            = dyn_cast<FunctionTemplateDecl>(OldDecl))
2844        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
2845      else {
2846        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
2847          NewFD->setAccess(OldDecl->getAccess());
2848        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
2849      }
2850    }
2851  }
2852
2853  // In C++, check default arguments now that we have merged decls. Unless
2854  // the lexical context is the class, because in this case this is done
2855  // during delayed parsing anyway.
2856  if (getLangOptions().CPlusPlus && !CurContext->isRecord())
2857    CheckCXXDefaultArguments(NewFD);
2858}
2859
2860void Sema::CheckMain(FunctionDecl* FD) {
2861  // C++ [basic.start.main]p3:  A program that declares main to be inline
2862  //   or static is ill-formed.
2863  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
2864  //   shall not appear in a declaration of main.
2865  // static main is not an error under C99, but we should warn about it.
2866  bool isInline = FD->isInline();
2867  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
2868  if (isInline || isStatic) {
2869    unsigned diagID = diag::warn_unusual_main_decl;
2870    if (isInline || getLangOptions().CPlusPlus)
2871      diagID = diag::err_unusual_main_decl;
2872
2873    int which = isStatic + (isInline << 1) - 1;
2874    Diag(FD->getLocation(), diagID) << which;
2875  }
2876
2877  QualType T = FD->getType();
2878  assert(T->isFunctionType() && "function decl is not of function type");
2879  const FunctionType* FT = T->getAsFunctionType();
2880
2881  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
2882    // TODO: add a replacement fixit to turn the return type into 'int'.
2883    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
2884    FD->setInvalidDecl(true);
2885  }
2886
2887  // Treat protoless main() as nullary.
2888  if (isa<FunctionNoProtoType>(FT)) return;
2889
2890  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
2891  unsigned nparams = FTP->getNumArgs();
2892  assert(FD->getNumParams() == nparams);
2893
2894  if (nparams > 3) {
2895    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
2896    FD->setInvalidDecl(true);
2897    nparams = 3;
2898  }
2899
2900  // FIXME: a lot of the following diagnostics would be improved
2901  // if we had some location information about types.
2902
2903  QualType CharPP =
2904    Context.getPointerType(Context.getPointerType(Context.CharTy));
2905  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
2906
2907  for (unsigned i = 0; i < nparams; ++i) {
2908    QualType AT = FTP->getArgType(i);
2909
2910    bool mismatch = true;
2911
2912    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
2913      mismatch = false;
2914    else if (Expected[i] == CharPP) {
2915      // As an extension, the following forms are okay:
2916      //   char const **
2917      //   char const * const *
2918      //   char * const *
2919
2920      QualifierSet qs;
2921      const PointerType* PT;
2922      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
2923          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
2924          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
2925        qs.removeConst();
2926        mismatch = !qs.empty();
2927      }
2928    }
2929
2930    if (mismatch) {
2931      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
2932      // TODO: suggest replacing given type with expected type
2933      FD->setInvalidDecl(true);
2934    }
2935  }
2936
2937  if (nparams == 1 && !FD->isInvalidDecl()) {
2938    Diag(FD->getLocation(), diag::warn_main_one_arg);
2939  }
2940}
2941
2942bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2943  // FIXME: Need strict checking.  In C89, we need to check for
2944  // any assignment, increment, decrement, function-calls, or
2945  // commas outside of a sizeof.  In C99, it's the same list,
2946  // except that the aforementioned are allowed in unevaluated
2947  // expressions.  Everything else falls under the
2948  // "may accept other forms of constant expressions" exception.
2949  // (We never end up here for C++, so the constant expression
2950  // rules there don't matter.)
2951  if (Init->isConstantInitializer(Context))
2952    return false;
2953  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2954    << Init->getSourceRange();
2955  return true;
2956}
2957
2958void Sema::AddInitializerToDecl(DeclPtrTy dcl, FullExprArg init) {
2959  AddInitializerToDecl(dcl, init.release(), /*DirectInit=*/false);
2960}
2961
2962/// AddInitializerToDecl - Adds the initializer Init to the
2963/// declaration dcl. If DirectInit is true, this is C++ direct
2964/// initialization rather than copy initialization.
2965void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
2966  Decl *RealDecl = dcl.getAs<Decl>();
2967  // If there is no declaration, there was an error parsing it.  Just ignore
2968  // the initializer.
2969  if (RealDecl == 0)
2970    return;
2971
2972  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
2973    // With declarators parsed the way they are, the parser cannot
2974    // distinguish between a normal initializer and a pure-specifier.
2975    // Thus this grotesque test.
2976    IntegerLiteral *IL;
2977    Expr *Init = static_cast<Expr *>(init.get());
2978    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
2979        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
2980      if (Method->isVirtualAsWritten()) {
2981        Method->setPure();
2982
2983        // A class is abstract if at least one function is pure virtual.
2984        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
2985      } else if (!Method->isInvalidDecl()) {
2986        Diag(Method->getLocation(), diag::err_non_virtual_pure)
2987          << Method->getDeclName() << Init->getSourceRange();
2988        Method->setInvalidDecl();
2989      }
2990    } else {
2991      Diag(Method->getLocation(), diag::err_member_function_initialization)
2992        << Method->getDeclName() << Init->getSourceRange();
2993      Method->setInvalidDecl();
2994    }
2995    return;
2996  }
2997
2998  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2999  if (!VDecl) {
3000    if (getLangOptions().CPlusPlus &&
3001        RealDecl->getLexicalDeclContext()->isRecord() &&
3002        isa<NamedDecl>(RealDecl))
3003      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3004        << cast<NamedDecl>(RealDecl)->getDeclName();
3005    else
3006      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3007    RealDecl->setInvalidDecl();
3008    return;
3009  }
3010
3011  if (!VDecl->getType()->isArrayType() &&
3012      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3013                          diag::err_typecheck_decl_incomplete_type)) {
3014    RealDecl->setInvalidDecl();
3015    return;
3016  }
3017
3018  const VarDecl *Def = 0;
3019  if (VDecl->getDefinition(Def)) {
3020    Diag(VDecl->getLocation(), diag::err_redefinition)
3021      << VDecl->getDeclName();
3022    Diag(Def->getLocation(), diag::note_previous_definition);
3023    VDecl->setInvalidDecl();
3024    return;
3025  }
3026
3027  // Take ownership of the expression, now that we're sure we have somewhere
3028  // to put it.
3029  Expr *Init = init.takeAs<Expr>();
3030  assert(Init && "missing initializer");
3031
3032  // Get the decls type and save a reference for later, since
3033  // CheckInitializerTypes may change it.
3034  QualType DclT = VDecl->getType(), SavT = DclT;
3035  if (VDecl->isBlockVarDecl()) {
3036    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3037      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3038      VDecl->setInvalidDecl();
3039    } else if (!VDecl->isInvalidDecl()) {
3040      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3041                                VDecl->getDeclName(), DirectInit))
3042        VDecl->setInvalidDecl();
3043
3044      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3045      // Don't check invalid declarations to avoid emitting useless diagnostics.
3046      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3047        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3048          CheckForConstantInitializer(Init, DclT);
3049      }
3050    }
3051  } else if (VDecl->isStaticDataMember() &&
3052             VDecl->getLexicalDeclContext()->isRecord()) {
3053    // This is an in-class initialization for a static data member, e.g.,
3054    //
3055    // struct S {
3056    //   static const int value = 17;
3057    // };
3058
3059    // Attach the initializer
3060    VDecl->setInit(Context, Init);
3061
3062    // C++ [class.mem]p4:
3063    //   A member-declarator can contain a constant-initializer only
3064    //   if it declares a static member (9.4) of const integral or
3065    //   const enumeration type, see 9.4.2.
3066    QualType T = VDecl->getType();
3067    if (!T->isDependentType() &&
3068        (!Context.getCanonicalType(T).isConstQualified() ||
3069         !T->isIntegralType())) {
3070      Diag(VDecl->getLocation(), diag::err_member_initialization)
3071        << VDecl->getDeclName() << Init->getSourceRange();
3072      VDecl->setInvalidDecl();
3073    } else {
3074      // C++ [class.static.data]p4:
3075      //   If a static data member is of const integral or const
3076      //   enumeration type, its declaration in the class definition
3077      //   can specify a constant-initializer which shall be an
3078      //   integral constant expression (5.19).
3079      if (!Init->isTypeDependent() &&
3080          !Init->getType()->isIntegralType()) {
3081        // We have a non-dependent, non-integral or enumeration type.
3082        Diag(Init->getSourceRange().getBegin(),
3083             diag::err_in_class_initializer_non_integral_type)
3084          << Init->getType() << Init->getSourceRange();
3085        VDecl->setInvalidDecl();
3086      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3087        // Check whether the expression is a constant expression.
3088        llvm::APSInt Value;
3089        SourceLocation Loc;
3090        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3091          Diag(Loc, diag::err_in_class_initializer_non_constant)
3092            << Init->getSourceRange();
3093          VDecl->setInvalidDecl();
3094        } else if (!VDecl->getType()->isDependentType())
3095          ImpCastExprToType(Init, VDecl->getType());
3096      }
3097    }
3098  } else if (VDecl->isFileVarDecl()) {
3099    if (VDecl->getStorageClass() == VarDecl::Extern)
3100      Diag(VDecl->getLocation(), diag::warn_extern_init);
3101    if (!VDecl->isInvalidDecl())
3102      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3103                                VDecl->getDeclName(), DirectInit))
3104        VDecl->setInvalidDecl();
3105
3106    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3107    // Don't check invalid declarations to avoid emitting useless diagnostics.
3108    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3109      // C99 6.7.8p4. All file scoped initializers need to be constant.
3110      CheckForConstantInitializer(Init, DclT);
3111    }
3112  }
3113  // If the type changed, it means we had an incomplete type that was
3114  // completed by the initializer. For example:
3115  //   int ary[] = { 1, 3, 5 };
3116  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3117  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3118    VDecl->setType(DclT);
3119    Init->setType(DclT);
3120  }
3121
3122  // Attach the initializer to the decl.
3123  VDecl->setInit(Context, Init);
3124
3125  // If the previous declaration of VDecl was a tentative definition,
3126  // remove it from the set of tentative definitions.
3127  if (VDecl->getPreviousDeclaration() &&
3128      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3129    llvm::DenseMap<DeclarationName, VarDecl *>::iterator Pos
3130      = TentativeDefinitions.find(VDecl->getDeclName());
3131    assert(Pos != TentativeDefinitions.end() &&
3132           "Unrecorded tentative definition?");
3133    TentativeDefinitions.erase(Pos);
3134  }
3135
3136  return;
3137}
3138
3139void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3140                                  bool TypeContainsUndeducedAuto) {
3141  Decl *RealDecl = dcl.getAs<Decl>();
3142
3143  // If there is no declaration, there was an error parsing it. Just ignore it.
3144  if (RealDecl == 0)
3145    return;
3146
3147  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3148    QualType Type = Var->getType();
3149
3150    // Record tentative definitions.
3151    if (Var->isTentativeDefinition(Context))
3152      TentativeDefinitions[Var->getDeclName()] = Var;
3153
3154    // C++ [dcl.init.ref]p3:
3155    //   The initializer can be omitted for a reference only in a
3156    //   parameter declaration (8.3.5), in the declaration of a
3157    //   function return type, in the declaration of a class member
3158    //   within its class declaration (9.2), and where the extern
3159    //   specifier is explicitly used.
3160    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3161      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3162        << Var->getDeclName()
3163        << SourceRange(Var->getLocation(), Var->getLocation());
3164      Var->setInvalidDecl();
3165      return;
3166    }
3167
3168    // C++0x [dcl.spec.auto]p3
3169    if (TypeContainsUndeducedAuto) {
3170      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3171        << Var->getDeclName() << Type;
3172      Var->setInvalidDecl();
3173      return;
3174    }
3175
3176    // C++ [dcl.init]p9:
3177    //
3178    //   If no initializer is specified for an object, and the object
3179    //   is of (possibly cv-qualified) non-POD class type (or array
3180    //   thereof), the object shall be default-initialized; if the
3181    //   object is of const-qualified type, the underlying class type
3182    //   shall have a user-declared default constructor.
3183    if (getLangOptions().CPlusPlus) {
3184      QualType InitType = Type;
3185      if (const ArrayType *Array = Context.getAsArrayType(Type))
3186        InitType = Array->getElementType();
3187      if ((!Var->hasExternalStorage() && !Var->isExternC(Context)) &&
3188          InitType->isRecordType() && !InitType->isDependentType()) {
3189        CXXRecordDecl *RD =
3190          cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
3191        CXXConstructorDecl *Constructor = 0;
3192        if (!RequireCompleteType(Var->getLocation(), InitType,
3193                                    diag::err_invalid_incomplete_type_use))
3194          Constructor
3195            = PerformInitializationByConstructor(InitType, 0, 0,
3196                                                 Var->getLocation(),
3197                                               SourceRange(Var->getLocation(),
3198                                                           Var->getLocation()),
3199                                                 Var->getDeclName(),
3200                                                 IK_Default);
3201        if (!Constructor)
3202          Var->setInvalidDecl();
3203        else {
3204          if (!RD->hasTrivialConstructor())
3205            InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0);
3206          FinalizeVarWithDestructor(Var, InitType);
3207        }
3208      }
3209    }
3210
3211#if 0
3212    // FIXME: Temporarily disabled because we are not properly parsing
3213    // linkage specifications on declarations, e.g.,
3214    //
3215    //   extern "C" const CGPoint CGPointerZero;
3216    //
3217    // C++ [dcl.init]p9:
3218    //
3219    //     If no initializer is specified for an object, and the
3220    //     object is of (possibly cv-qualified) non-POD class type (or
3221    //     array thereof), the object shall be default-initialized; if
3222    //     the object is of const-qualified type, the underlying class
3223    //     type shall have a user-declared default
3224    //     constructor. Otherwise, if no initializer is specified for
3225    //     an object, the object and its subobjects, if any, have an
3226    //     indeterminate initial value; if the object or any of its
3227    //     subobjects are of const-qualified type, the program is
3228    //     ill-formed.
3229    //
3230    // This isn't technically an error in C, so we don't diagnose it.
3231    //
3232    // FIXME: Actually perform the POD/user-defined default
3233    // constructor check.
3234    if (getLangOptions().CPlusPlus &&
3235        Context.getCanonicalType(Type).isConstQualified() &&
3236        !Var->hasExternalStorage())
3237      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3238        << Var->getName()
3239        << SourceRange(Var->getLocation(), Var->getLocation());
3240#endif
3241  }
3242}
3243
3244Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3245                                                   DeclPtrTy *Group,
3246                                                   unsigned NumDecls) {
3247  llvm::SmallVector<Decl*, 8> Decls;
3248
3249  if (DS.isTypeSpecOwned())
3250    Decls.push_back((Decl*)DS.getTypeRep());
3251
3252  for (unsigned i = 0; i != NumDecls; ++i)
3253    if (Decl *D = Group[i].getAs<Decl>())
3254      Decls.push_back(D);
3255
3256  // Perform semantic analysis that depends on having fully processed both
3257  // the declarator and initializer.
3258  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3259    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3260    if (!IDecl)
3261      continue;
3262    QualType T = IDecl->getType();
3263
3264    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3265    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3266    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3267      if (!IDecl->isInvalidDecl() &&
3268          RequireCompleteType(IDecl->getLocation(), T,
3269                              diag::err_typecheck_decl_incomplete_type))
3270        IDecl->setInvalidDecl();
3271    }
3272    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3273    // object that has file scope without an initializer, and without a
3274    // storage-class specifier or with the storage-class specifier "static",
3275    // constitutes a tentative definition. Note: A tentative definition with
3276    // external linkage is valid (C99 6.2.2p5).
3277    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3278      if (const IncompleteArrayType *ArrayT
3279          = Context.getAsIncompleteArrayType(T)) {
3280        if (RequireCompleteType(IDecl->getLocation(),
3281                                ArrayT->getElementType(),
3282                                diag::err_illegal_decl_array_incomplete_type))
3283          IDecl->setInvalidDecl();
3284      }
3285      else if (IDecl->getStorageClass() == VarDecl::Static) {
3286        // C99 6.9.2p3: If the declaration of an identifier for an object is
3287        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3288        // declared type shall not be an incomplete type.
3289        // NOTE: code such as the following
3290        //     static struct s;
3291        //     struct s { int a; };
3292        // is accepted by gcc. Hence here we issue a warning instead of
3293        // an error and we do not invalidate the static declaration.
3294        // NOTE: to avoid multiple warnings, only check the first declaration.
3295        if (IDecl->getPreviousDeclaration() == 0)
3296          RequireCompleteType(IDecl->getLocation(), T,
3297                              diag::ext_typecheck_decl_incomplete_type);
3298      }
3299    }
3300  }
3301  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3302                                                   Decls.data(), Decls.size()));
3303}
3304
3305
3306/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3307/// to introduce parameters into function prototype scope.
3308Sema::DeclPtrTy
3309Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3310  const DeclSpec &DS = D.getDeclSpec();
3311
3312  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3313  VarDecl::StorageClass StorageClass = VarDecl::None;
3314  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3315    StorageClass = VarDecl::Register;
3316  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3317    Diag(DS.getStorageClassSpecLoc(),
3318         diag::err_invalid_storage_class_in_func_decl);
3319    D.getMutableDeclSpec().ClearStorageClassSpecs();
3320  }
3321
3322  if (D.getDeclSpec().isThreadSpecified())
3323    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3324
3325  DiagnoseFunctionSpecifiers(D);
3326
3327  // Check that there are no default arguments inside the type of this
3328  // parameter (C++ only).
3329  if (getLangOptions().CPlusPlus)
3330    CheckExtraCXXDefaultArguments(D);
3331
3332  TagDecl *OwnedDecl = 0;
3333  QualType parmDeclType = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedDecl);
3334
3335  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3336    // C++ [dcl.fct]p6:
3337    //   Types shall not be defined in return or parameter types.
3338    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3339      << Context.getTypeDeclType(OwnedDecl);
3340  }
3341
3342  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3343  // Can this happen for params?  We already checked that they don't conflict
3344  // among each other.  Here they can only shadow globals, which is ok.
3345  IdentifierInfo *II = D.getIdentifier();
3346  if (II) {
3347    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
3348      if (PrevDecl->isTemplateParameter()) {
3349        // Maybe we will complain about the shadowed template parameter.
3350        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3351        // Just pretend that we didn't see the previous declaration.
3352        PrevDecl = 0;
3353      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3354        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3355
3356        // Recover by removing the name
3357        II = 0;
3358        D.SetIdentifier(0, D.getIdentifierLoc());
3359      }
3360    }
3361  }
3362
3363  // Parameters can not be abstract class types.
3364  // For record types, this is done by the AbstractClassUsageDiagnoser once
3365  // the class has been completely parsed.
3366  if (!CurContext->isRecord() &&
3367      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3368                             diag::err_abstract_type_in_decl,
3369                             AbstractParamType))
3370    D.setInvalidType(true);
3371
3372  QualType T = adjustParameterType(parmDeclType);
3373
3374  ParmVarDecl *New;
3375  if (T == parmDeclType) // parameter type did not need adjustment
3376    New = ParmVarDecl::Create(Context, CurContext,
3377                              D.getIdentifierLoc(), II,
3378                              parmDeclType, StorageClass,
3379                              0);
3380  else // keep track of both the adjusted and unadjusted types
3381    New = OriginalParmVarDecl::Create(Context, CurContext,
3382                                      D.getIdentifierLoc(), II, T,
3383                                      parmDeclType, StorageClass, 0);
3384
3385  if (D.isInvalidType())
3386    New->setInvalidDecl();
3387
3388  // Parameter declarators cannot be interface types. All ObjC objects are
3389  // passed by reference.
3390  if (T->isObjCInterfaceType()) {
3391    Diag(D.getIdentifierLoc(),
3392         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3393    New->setInvalidDecl();
3394  }
3395
3396  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3397  if (D.getCXXScopeSpec().isSet()) {
3398    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3399      << D.getCXXScopeSpec().getRange();
3400    New->setInvalidDecl();
3401  }
3402
3403  // Add the parameter declaration into this scope.
3404  S->AddDecl(DeclPtrTy::make(New));
3405  if (II)
3406    IdResolver.AddDecl(New);
3407
3408  ProcessDeclAttributes(S, New, D);
3409
3410  if (New->hasAttr<BlocksAttr>()) {
3411    Diag(New->getLocation(), diag::err_block_on_nonlocal);
3412  }
3413  return DeclPtrTy::make(New);
3414}
3415
3416void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3417                                           SourceLocation LocAfterDecls) {
3418  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3419         "Not a function declarator!");
3420  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3421
3422  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3423  // for a K&R function.
3424  if (!FTI.hasPrototype) {
3425    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3426      --i;
3427      if (FTI.ArgInfo[i].Param == 0) {
3428        std::string Code = "  int ";
3429        Code += FTI.ArgInfo[i].Ident->getName();
3430        Code += ";\n";
3431        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3432          << FTI.ArgInfo[i].Ident
3433          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code);
3434
3435        // Implicitly declare the argument as type 'int' for lack of a better
3436        // type.
3437        DeclSpec DS;
3438        const char* PrevSpec; // unused
3439        unsigned DiagID; // unused
3440        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3441                           PrevSpec, DiagID);
3442        Declarator ParamD(DS, Declarator::KNRTypeListContext);
3443        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3444        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3445      }
3446    }
3447  }
3448}
3449
3450Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3451                                              Declarator &D) {
3452  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3453  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3454         "Not a function declarator!");
3455  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3456
3457  if (FTI.hasPrototype) {
3458    // FIXME: Diagnose arguments without names in C.
3459  }
3460
3461  Scope *ParentScope = FnBodyScope->getParent();
3462
3463  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3464                                  MultiTemplateParamsArg(*this),
3465                                  /*IsFunctionDefinition=*/true);
3466  return ActOnStartOfFunctionDef(FnBodyScope, DP);
3467}
3468
3469Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
3470  if (!D)
3471    return D;
3472  FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>());
3473
3474  CurFunctionNeedsScopeChecking = false;
3475
3476  // See if this is a redefinition.
3477  const FunctionDecl *Definition;
3478  if (FD->getBody(Definition)) {
3479    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
3480    Diag(Definition->getLocation(), diag::note_previous_definition);
3481  }
3482
3483  // Builtin functions cannot be defined.
3484  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3485    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3486      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
3487      FD->setInvalidDecl();
3488    }
3489  }
3490
3491  // The return type of a function definition must be complete
3492  // (C99 6.9.1p3, C++ [dcl.fct]p6).
3493  QualType ResultType = FD->getResultType();
3494  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
3495      !FD->isInvalidDecl() &&
3496      RequireCompleteType(FD->getLocation(), ResultType,
3497                          diag::err_func_def_incomplete_result))
3498    FD->setInvalidDecl();
3499
3500  // GNU warning -Wmissing-prototypes:
3501  //   Warn if a global function is defined without a previous
3502  //   prototype declaration. This warning is issued even if the
3503  //   definition itself provides a prototype. The aim is to detect
3504  //   global functions that fail to be declared in header files.
3505  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
3506      !FD->isMain()) {
3507    bool MissingPrototype = true;
3508    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
3509         Prev; Prev = Prev->getPreviousDeclaration()) {
3510      // Ignore any declarations that occur in function or method
3511      // scope, because they aren't visible from the header.
3512      if (Prev->getDeclContext()->isFunctionOrMethod())
3513        continue;
3514
3515      MissingPrototype = !Prev->getType()->isFunctionProtoType();
3516      break;
3517    }
3518
3519    if (MissingPrototype)
3520      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
3521  }
3522
3523  if (FnBodyScope)
3524    PushDeclContext(FnBodyScope, FD);
3525
3526  // Check the validity of our function parameters
3527  CheckParmsForFunctionDef(FD);
3528
3529  // Introduce our parameters into the function scope
3530  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
3531    ParmVarDecl *Param = FD->getParamDecl(p);
3532    Param->setOwningFunction(FD);
3533
3534    // If this has an identifier, add it to the scope stack.
3535    if (Param->getIdentifier() && FnBodyScope)
3536      PushOnScopeChains(Param, FnBodyScope);
3537  }
3538
3539  // Checking attributes of current function definition
3540  // dllimport attribute.
3541  if (FD->getAttr<DLLImportAttr>() &&
3542      (!FD->getAttr<DLLExportAttr>())) {
3543    // dllimport attribute cannot be applied to definition.
3544    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
3545      Diag(FD->getLocation(),
3546           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
3547        << "dllimport";
3548      FD->setInvalidDecl();
3549      return DeclPtrTy::make(FD);
3550    } else {
3551      // If a symbol previously declared dllimport is later defined, the
3552      // attribute is ignored in subsequent references, and a warning is
3553      // emitted.
3554      Diag(FD->getLocation(),
3555           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3556        << FD->getNameAsCString() << "dllimport";
3557    }
3558  }
3559  return DeclPtrTy::make(FD);
3560}
3561
3562Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
3563  return ActOnFinishFunctionBody(D, move(BodyArg), false);
3564}
3565
3566Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
3567                                              bool IsInstantiation) {
3568  Decl *dcl = D.getAs<Decl>();
3569  Stmt *Body = BodyArg.takeAs<Stmt>();
3570  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
3571    FD->setBody(Body);
3572    if (FD->isMain())
3573      // C and C++ allow for main to automagically return 0.
3574      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
3575      FD->setHasImplicitReturnZero(true);
3576    else
3577      CheckFallThroughForFunctionDef(FD, Body);
3578
3579    if (!FD->isInvalidDecl())
3580      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
3581
3582    // C++ [basic.def.odr]p2:
3583    //   [...] A virtual member function is used if it is not pure. [...]
3584    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
3585      if (Method->isVirtual() && !Method->isPure())
3586        MarkDeclarationReferenced(Method->getLocation(), Method);
3587
3588    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3589  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3590    assert(MD == getCurMethodDecl() && "Method parsing confused");
3591    MD->setBody(Body);
3592    CheckFallThroughForFunctionDef(MD, Body);
3593    MD->setEndLoc(Body->getLocEnd());
3594
3595    if (!MD->isInvalidDecl())
3596      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
3597  } else {
3598    Body->Destroy(Context);
3599    return DeclPtrTy();
3600  }
3601  if (!IsInstantiation)
3602    PopDeclContext();
3603
3604  // Verify and clean out per-function state.
3605
3606  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
3607
3608  // Check goto/label use.
3609  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3610       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
3611    LabelStmt *L = I->second;
3612
3613    // Verify that we have no forward references left.  If so, there was a goto
3614    // or address of a label taken, but no definition of it.  Label fwd
3615    // definitions are indicated with a null substmt.
3616    if (L->getSubStmt() != 0)
3617      continue;
3618
3619    // Emit error.
3620    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
3621
3622    // At this point, we have gotos that use the bogus label.  Stitch it into
3623    // the function body so that they aren't leaked and that the AST is well
3624    // formed.
3625    if (Body == 0) {
3626      // The whole function wasn't parsed correctly, just delete this.
3627      L->Destroy(Context);
3628      continue;
3629    }
3630
3631    // Otherwise, the body is valid: we want to stitch the label decl into the
3632    // function somewhere so that it is properly owned and so that the goto
3633    // has a valid target.  Do this by creating a new compound stmt with the
3634    // label in it.
3635
3636    // Give the label a sub-statement.
3637    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3638
3639    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
3640                               cast<CXXTryStmt>(Body)->getTryBlock() :
3641                               cast<CompoundStmt>(Body);
3642    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
3643    Elements.push_back(L);
3644    Compound->setStmts(Context, &Elements[0], Elements.size());
3645  }
3646  FunctionLabelMap.clear();
3647
3648  if (!Body) return D;
3649
3650  // Verify that that gotos and switch cases don't jump into scopes illegally.
3651  if (CurFunctionNeedsScopeChecking)
3652    DiagnoseInvalidJumps(Body);
3653
3654  // C++ constructors that have function-try-blocks can't have return
3655  // statements in the handlers of that block. (C++ [except.handle]p14)
3656  // Verify this.
3657  if (isa<CXXConstructorDecl>(dcl) && isa<CXXTryStmt>(Body))
3658    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
3659
3660  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
3661    Destructor->computeBaseOrMembersToDestroy(Context);
3662  return D;
3663}
3664
3665/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3666/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
3667NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3668                                          IdentifierInfo &II, Scope *S) {
3669  // Before we produce a declaration for an implicitly defined
3670  // function, see whether there was a locally-scoped declaration of
3671  // this name as a function or variable. If so, use that
3672  // (non-visible) declaration, and complain about it.
3673  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3674    = LocallyScopedExternalDecls.find(&II);
3675  if (Pos != LocallyScopedExternalDecls.end()) {
3676    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
3677    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
3678    return Pos->second;
3679  }
3680
3681  // Extension in C99.  Legal in C90, but warn about it.
3682  if (getLangOptions().C99)
3683    Diag(Loc, diag::ext_implicit_function_decl) << &II;
3684  else
3685    Diag(Loc, diag::warn_implicit_function_decl) << &II;
3686
3687  // FIXME: handle stuff like:
3688  // void foo() { extern float X(); }
3689  // void bar() { X(); }  <-- implicit decl for X in another scope.
3690
3691  // Set a Declarator for the implicit definition: int foo();
3692  const char *Dummy;
3693  DeclSpec DS;
3694  unsigned DiagID;
3695  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
3696  Error = Error; // Silence warning.
3697  assert(!Error && "Error setting up implicit decl!");
3698  Declarator D(DS, Declarator::BlockContext);
3699  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
3700                                             0, 0, false, SourceLocation(),
3701                                             false, 0,0,0, Loc, D),
3702                SourceLocation());
3703  D.SetIdentifier(&II, Loc);
3704
3705  // Insert this function into translation-unit scope.
3706
3707  DeclContext *PrevDC = CurContext;
3708  CurContext = Context.getTranslationUnitDecl();
3709
3710  FunctionDecl *FD =
3711 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
3712  FD->setImplicit();
3713
3714  CurContext = PrevDC;
3715
3716  AddKnownFunctionAttributes(FD);
3717
3718  return FD;
3719}
3720
3721/// \brief Adds any function attributes that we know a priori based on
3722/// the declaration of this function.
3723///
3724/// These attributes can apply both to implicitly-declared builtins
3725/// (like __builtin___printf_chk) or to library-declared functions
3726/// like NSLog or printf.
3727void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3728  if (FD->isInvalidDecl())
3729    return;
3730
3731  // If this is a built-in function, map its builtin attributes to
3732  // actual attributes.
3733  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3734    // Handle printf-formatting attributes.
3735    unsigned FormatIdx;
3736    bool HasVAListArg;
3737    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3738      if (!FD->getAttr<FormatAttr>())
3739        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
3740                                             HasVAListArg ? 0 : FormatIdx + 2));
3741    }
3742
3743    // Mark const if we don't care about errno and that is the only
3744    // thing preventing the function from being const. This allows
3745    // IRgen to use LLVM intrinsics for such functions.
3746    if (!getLangOptions().MathErrno &&
3747        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3748      if (!FD->getAttr<ConstAttr>())
3749        FD->addAttr(::new (Context) ConstAttr());
3750    }
3751
3752    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
3753      FD->addAttr(::new (Context) NoReturnAttr());
3754  }
3755
3756  IdentifierInfo *Name = FD->getIdentifier();
3757  if (!Name)
3758    return;
3759  if ((!getLangOptions().CPlusPlus &&
3760       FD->getDeclContext()->isTranslationUnit()) ||
3761      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3762       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3763       LinkageSpecDecl::lang_c)) {
3764    // Okay: this could be a libc/libm/Objective-C function we know
3765    // about.
3766  } else
3767    return;
3768
3769  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
3770    // FIXME: NSLog and NSLogv should be target specific
3771    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3772      // FIXME: We known better than our headers.
3773      const_cast<FormatAttr *>(Format)->setType("printf");
3774    } else
3775      FD->addAttr(::new (Context) FormatAttr("printf", 1,
3776                                             Name->isStr("NSLogv") ? 0 : 2));
3777  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
3778    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
3779    // target-specific builtins, perhaps?
3780    if (!FD->getAttr<FormatAttr>())
3781      FD->addAttr(::new (Context) FormatAttr("printf", 2,
3782                                             Name->isStr("vasprintf") ? 0 : 3));
3783  }
3784}
3785
3786TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) {
3787  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
3788  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3789
3790  // Scope manipulation handled by caller.
3791  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3792                                           D.getIdentifierLoc(),
3793                                           D.getIdentifier(),
3794                                           T);
3795
3796  if (TagType *TT = dyn_cast<TagType>(T)) {
3797    TagDecl *TD = TT->getDecl();
3798
3799    // If the TagDecl that the TypedefDecl points to is an anonymous decl
3800    // keep track of the TypedefDecl.
3801    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
3802      TD->setTypedefForAnonDecl(NewTD);
3803  }
3804
3805  if (D.isInvalidType())
3806    NewTD->setInvalidDecl();
3807  return NewTD;
3808}
3809
3810
3811/// \brief Determine whether a tag with a given kind is acceptable
3812/// as a redeclaration of the given tag declaration.
3813///
3814/// \returns true if the new tag kind is acceptable, false otherwise.
3815bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
3816                                        TagDecl::TagKind NewTag,
3817                                        SourceLocation NewTagLoc,
3818                                        const IdentifierInfo &Name) {
3819  // C++ [dcl.type.elab]p3:
3820  //   The class-key or enum keyword present in the
3821  //   elaborated-type-specifier shall agree in kind with the
3822  //   declaration to which the name in theelaborated-type-specifier
3823  //   refers. This rule also applies to the form of
3824  //   elaborated-type-specifier that declares a class-name or
3825  //   friend class since it can be construed as referring to the
3826  //   definition of the class. Thus, in any
3827  //   elaborated-type-specifier, the enum keyword shall be used to
3828  //   refer to an enumeration (7.2), the union class-keyshall be
3829  //   used to refer to a union (clause 9), and either the class or
3830  //   struct class-key shall be used to refer to a class (clause 9)
3831  //   declared using the class or struct class-key.
3832  TagDecl::TagKind OldTag = Previous->getTagKind();
3833  if (OldTag == NewTag)
3834    return true;
3835
3836  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
3837      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
3838    // Warn about the struct/class tag mismatch.
3839    bool isTemplate = false;
3840    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
3841      isTemplate = Record->getDescribedClassTemplate();
3842
3843    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
3844      << (NewTag == TagDecl::TK_class)
3845      << isTemplate << &Name
3846      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
3847                              OldTag == TagDecl::TK_class? "class" : "struct");
3848    Diag(Previous->getLocation(), diag::note_previous_use);
3849    return true;
3850  }
3851  return false;
3852}
3853
3854/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
3855/// former case, Name will be non-null.  In the later case, Name will be null.
3856/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
3857/// reference/declaration/definition of a tag.
3858Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3859                               SourceLocation KWLoc, const CXXScopeSpec &SS,
3860                               IdentifierInfo *Name, SourceLocation NameLoc,
3861                               AttributeList *Attr, AccessSpecifier AS,
3862                               MultiTemplateParamsArg TemplateParameterLists,
3863                               bool &OwnedDecl) {
3864  // If this is not a definition, it must have a name.
3865  assert((Name != 0 || TUK == TUK_Definition) &&
3866         "Nameless record must be a definition!");
3867
3868  OwnedDecl = false;
3869  TagDecl::TagKind Kind;
3870  switch (TagSpec) {
3871  default: assert(0 && "Unknown tag type!");
3872  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3873  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3874  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3875  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
3876  }
3877
3878  if (TUK != TUK_Reference) {
3879    if (TemplateParameterList *TemplateParams
3880          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
3881                        (TemplateParameterList**)TemplateParameterLists.get(),
3882                                              TemplateParameterLists.size())) {
3883      if (TemplateParams->size() > 0) {
3884        // This is a declaration or definition of a class template (which may
3885        // be a member of another template).
3886        OwnedDecl = false;
3887        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
3888                                               SS, Name, NameLoc, Attr,
3889                                               move(TemplateParameterLists),
3890                                               AS);
3891        return Result.get();
3892      } else {
3893        // FIXME: diagnose the extraneous 'template<>', once we recover
3894        // slightly better in ParseTemplate.cpp from bogus template
3895        // parameters.
3896      }
3897    }
3898  }
3899
3900  DeclContext *SearchDC = CurContext;
3901  DeclContext *DC = CurContext;
3902  NamedDecl *PrevDecl = 0;
3903
3904  bool Invalid = false;
3905
3906  if (Name && SS.isNotEmpty()) {
3907    // We have a nested-name tag ('struct foo::bar').
3908
3909    // Check for invalid 'foo::'.
3910    if (SS.isInvalid()) {
3911      Name = 0;
3912      goto CreateNewDecl;
3913    }
3914
3915    if (RequireCompleteDeclContext(SS))
3916      return DeclPtrTy::make((Decl *)0);
3917
3918    DC = computeDeclContext(SS, true);
3919    SearchDC = DC;
3920    // Look-up name inside 'foo::'.
3921    PrevDecl
3922      = dyn_cast_or_null<TagDecl>(
3923               LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
3924
3925    // A tag 'foo::bar' must already exist.
3926    if (PrevDecl == 0) {
3927      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
3928      Name = 0;
3929      Invalid = true;
3930      goto CreateNewDecl;
3931    }
3932  } else if (Name) {
3933    // If this is a named struct, check to see if there was a previous forward
3934    // declaration or definition.
3935    // FIXME: We're looking into outer scopes here, even when we
3936    // shouldn't be. Doing so can result in ambiguities that we
3937    // shouldn't be diagnosing.
3938    LookupResult R = LookupName(S, Name, LookupTagName,
3939                                /*RedeclarationOnly=*/(TUK != TUK_Reference));
3940    if (R.isAmbiguous()) {
3941      DiagnoseAmbiguousLookup(R, Name, NameLoc);
3942      // FIXME: This is not best way to recover from case like:
3943      //
3944      // struct S s;
3945      //
3946      // causes needless "incomplete type" error later.
3947      Name = 0;
3948      PrevDecl = 0;
3949      Invalid = true;
3950    }
3951    else
3952      PrevDecl = R;
3953
3954    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
3955      // FIXME: This makes sure that we ignore the contexts associated
3956      // with C structs, unions, and enums when looking for a matching
3957      // tag declaration or definition. See the similar lookup tweak
3958      // in Sema::LookupName; is there a better way to deal with this?
3959      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3960        SearchDC = SearchDC->getParent();
3961    }
3962  }
3963
3964  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3965    // Maybe we will complain about the shadowed template parameter.
3966    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3967    // Just pretend that we didn't see the previous declaration.
3968    PrevDecl = 0;
3969  }
3970
3971  if (PrevDecl) {
3972    // Check whether the previous declaration is usable.
3973    (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
3974
3975    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
3976      // If this is a use of a previous tag, or if the tag is already declared
3977      // in the same scope (so that the definition/declaration completes or
3978      // rementions the tag), reuse the decl.
3979      if (TUK == TUK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
3980        // Make sure that this wasn't declared as an enum and now used as a
3981        // struct or something similar.
3982        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
3983          bool SafeToContinue
3984            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
3985               Kind != TagDecl::TK_enum);
3986          if (SafeToContinue)
3987            Diag(KWLoc, diag::err_use_with_wrong_tag)
3988              << Name
3989              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
3990                                                  PrevTagDecl->getKindName());
3991          else
3992            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
3993          Diag(PrevDecl->getLocation(), diag::note_previous_use);
3994
3995          if (SafeToContinue)
3996            Kind = PrevTagDecl->getTagKind();
3997          else {
3998            // Recover by making this an anonymous redefinition.
3999            Name = 0;
4000            PrevDecl = 0;
4001            Invalid = true;
4002          }
4003        }
4004
4005        if (!Invalid) {
4006          // If this is a use, just return the declaration we found.
4007
4008          // FIXME: In the future, return a variant or some other clue
4009          // for the consumer of this Decl to know it doesn't own it.
4010          // For our current ASTs this shouldn't be a problem, but will
4011          // need to be changed with DeclGroups.
4012          if (TUK == TUK_Reference)
4013            return DeclPtrTy::make(PrevDecl);
4014
4015          // Diagnose attempts to redefine a tag.
4016          if (TUK == TUK_Definition) {
4017            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4018              Diag(NameLoc, diag::err_redefinition) << Name;
4019              Diag(Def->getLocation(), diag::note_previous_definition);
4020              // If this is a redefinition, recover by making this
4021              // struct be anonymous, which will make any later
4022              // references get the previous definition.
4023              Name = 0;
4024              PrevDecl = 0;
4025              Invalid = true;
4026            } else {
4027              // If the type is currently being defined, complain
4028              // about a nested redefinition.
4029              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4030              if (Tag->isBeingDefined()) {
4031                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4032                Diag(PrevTagDecl->getLocation(),
4033                     diag::note_previous_definition);
4034                Name = 0;
4035                PrevDecl = 0;
4036                Invalid = true;
4037              }
4038            }
4039
4040            // Okay, this is definition of a previously declared or referenced
4041            // tag PrevDecl. We're going to create a new Decl for it.
4042          }
4043        }
4044        // If we get here we have (another) forward declaration or we
4045        // have a definition.  Just create a new decl.
4046      } else {
4047        // If we get here, this is a definition of a new tag type in a nested
4048        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4049        // new decl/type.  We set PrevDecl to NULL so that the entities
4050        // have distinct types.
4051        PrevDecl = 0;
4052      }
4053      // If we get here, we're going to create a new Decl. If PrevDecl
4054      // is non-NULL, it's a definition of the tag declared by
4055      // PrevDecl. If it's NULL, we have a new definition.
4056    } else {
4057      // PrevDecl is a namespace, template, or anything else
4058      // that lives in the IDNS_Tag identifier namespace.
4059      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4060        // The tag name clashes with a namespace name, issue an error and
4061        // recover by making this tag be anonymous.
4062        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4063        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4064        Name = 0;
4065        PrevDecl = 0;
4066        Invalid = true;
4067      } else {
4068        // The existing declaration isn't relevant to us; we're in a
4069        // new scope, so clear out the previous declaration.
4070        PrevDecl = 0;
4071      }
4072    }
4073  } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
4074             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
4075    // C++ [basic.scope.pdecl]p5:
4076    //   -- for an elaborated-type-specifier of the form
4077    //
4078    //          class-key identifier
4079    //
4080    //      if the elaborated-type-specifier is used in the
4081    //      decl-specifier-seq or parameter-declaration-clause of a
4082    //      function defined in namespace scope, the identifier is
4083    //      declared as a class-name in the namespace that contains
4084    //      the declaration; otherwise, except as a friend
4085    //      declaration, the identifier is declared in the smallest
4086    //      non-class, non-function-prototype scope that contains the
4087    //      declaration.
4088    //
4089    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4090    // C structs and unions.
4091    //
4092    // GNU C also supports this behavior as part of its incomplete
4093    // enum types extension, while GNU C++ does not.
4094    //
4095    // Find the context where we'll be declaring the tag.
4096    // FIXME: We would like to maintain the current DeclContext as the
4097    // lexical context,
4098    while (SearchDC->isRecord())
4099      SearchDC = SearchDC->getParent();
4100
4101    // Find the scope where we'll be declaring the tag.
4102    while (S->isClassScope() ||
4103           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4104           ((S->getFlags() & Scope::DeclScope) == 0) ||
4105           (S->getEntity() &&
4106            ((DeclContext *)S->getEntity())->isTransparentContext()))
4107      S = S->getParent();
4108  }
4109
4110CreateNewDecl:
4111
4112  // If there is an identifier, use the location of the identifier as the
4113  // location of the decl, otherwise use the location of the struct/union
4114  // keyword.
4115  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4116
4117  // Otherwise, create a new declaration. If there is a previous
4118  // declaration of the same entity, the two will be linked via
4119  // PrevDecl.
4120  TagDecl *New;
4121
4122  if (Kind == TagDecl::TK_enum) {
4123    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4124    // enum X { A, B, C } D;    D should chain to X.
4125    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4126                           cast_or_null<EnumDecl>(PrevDecl));
4127    // If this is an undefined enum, warn.
4128    if (TUK != TUK_Definition && !Invalid)  {
4129      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4130                                              : diag::ext_forward_ref_enum;
4131      Diag(Loc, DK);
4132    }
4133  } else {
4134    // struct/union/class
4135
4136    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4137    // struct X { int A; } D;    D should chain to X.
4138    if (getLangOptions().CPlusPlus)
4139      // FIXME: Look for a way to use RecordDecl for simple structs.
4140      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4141                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4142    else
4143      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4144                               cast_or_null<RecordDecl>(PrevDecl));
4145  }
4146
4147  if (Kind != TagDecl::TK_enum) {
4148    // Handle #pragma pack: if the #pragma pack stack has non-default
4149    // alignment, make up a packed attribute for this decl. These
4150    // attributes are checked when the ASTContext lays out the
4151    // structure.
4152    //
4153    // It is important for implementing the correct semantics that this
4154    // happen here (in act on tag decl). The #pragma pack stack is
4155    // maintained as a result of parser callbacks which can occur at
4156    // many points during the parsing of a struct declaration (because
4157    // the #pragma tokens are effectively skipped over during the
4158    // parsing of the struct).
4159    if (unsigned Alignment = getPragmaPackAlignment())
4160      New->addAttr(::new (Context) PackedAttr(Alignment * 8));
4161  }
4162
4163  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4164    // C++ [dcl.typedef]p3:
4165    //   [...] Similarly, in a given scope, a class or enumeration
4166    //   shall not be declared with the same name as a typedef-name
4167    //   that is declared in that scope and refers to a type other
4168    //   than the class or enumeration itself.
4169    LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
4170    TypedefDecl *PrevTypedef = 0;
4171    if (Lookup.getKind() == LookupResult::Found)
4172      PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
4173
4174    if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
4175        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4176          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4177      Diag(Loc, diag::err_tag_definition_of_typedef)
4178        << Context.getTypeDeclType(New)
4179        << PrevTypedef->getUnderlyingType();
4180      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4181      Invalid = true;
4182    }
4183  }
4184
4185  if (Invalid)
4186    New->setInvalidDecl();
4187
4188  if (Attr)
4189    ProcessDeclAttributeList(S, New, Attr);
4190
4191  // If we're declaring or defining a tag in function prototype scope
4192  // in C, note that this type can only be used within the function.
4193  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4194    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4195
4196  // Set the lexical context. If the tag has a C++ scope specifier, the
4197  // lexical context will be different from the semantic context.
4198  New->setLexicalDeclContext(CurContext);
4199
4200  // Set the access specifier.
4201  if (!Invalid)
4202    SetMemberAccessSpecifier(New, PrevDecl, AS);
4203
4204  if (TUK == TUK_Definition)
4205    New->startDefinition();
4206
4207  // If this has an identifier, add it to the scope stack.
4208  if (Name) {
4209    S = getNonFieldDeclScope(S);
4210    PushOnScopeChains(New, S);
4211  } else {
4212    CurContext->addDecl(New);
4213  }
4214
4215  // If this is the C FILE type, notify the AST context.
4216  if (IdentifierInfo *II = New->getIdentifier())
4217    if (!New->isInvalidDecl() &&
4218        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4219        II->isStr("FILE"))
4220      Context.setFILEDecl(New);
4221
4222  OwnedDecl = true;
4223  return DeclPtrTy::make(New);
4224}
4225
4226void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4227  AdjustDeclIfTemplate(TagD);
4228  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4229
4230  // Enter the tag context.
4231  PushDeclContext(S, Tag);
4232
4233  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4234    FieldCollector->StartClass();
4235
4236    if (Record->getIdentifier()) {
4237      // C++ [class]p2:
4238      //   [...] The class-name is also inserted into the scope of the
4239      //   class itself; this is known as the injected-class-name. For
4240      //   purposes of access checking, the injected-class-name is treated
4241      //   as if it were a public member name.
4242      CXXRecordDecl *InjectedClassName
4243        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4244                                CurContext, Record->getLocation(),
4245                                Record->getIdentifier(),
4246                                Record->getTagKeywordLoc(),
4247                                Record);
4248      InjectedClassName->setImplicit();
4249      InjectedClassName->setAccess(AS_public);
4250      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4251        InjectedClassName->setDescribedClassTemplate(Template);
4252      PushOnScopeChains(InjectedClassName, S);
4253      assert(InjectedClassName->isInjectedClassName() &&
4254             "Broken injected-class-name");
4255    }
4256  }
4257}
4258
4259void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4260                                    SourceLocation RBraceLoc) {
4261  AdjustDeclIfTemplate(TagD);
4262  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4263  Tag->setRBraceLoc(RBraceLoc);
4264
4265  if (isa<CXXRecordDecl>(Tag))
4266    FieldCollector->FinishClass();
4267
4268  // Exit this scope of this tag's definition.
4269  PopDeclContext();
4270
4271  // Notify the consumer that we've defined a tag.
4272  Consumer.HandleTagDeclDefinition(Tag);
4273}
4274
4275// Note that FieldName may be null for anonymous bitfields.
4276bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4277                          QualType FieldTy, const Expr *BitWidth) {
4278
4279  // C99 6.7.2.1p4 - verify the field type.
4280  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4281  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4282    // Handle incomplete types with specific error.
4283    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4284      return true;
4285    if (FieldName)
4286      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4287        << FieldName << FieldTy << BitWidth->getSourceRange();
4288    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4289      << FieldTy << BitWidth->getSourceRange();
4290  }
4291
4292  // If the bit-width is type- or value-dependent, don't try to check
4293  // it now.
4294  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4295    return false;
4296
4297  llvm::APSInt Value;
4298  if (VerifyIntegerConstantExpression(BitWidth, &Value))
4299    return true;
4300
4301  // Zero-width bitfield is ok for anonymous field.
4302  if (Value == 0 && FieldName)
4303    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
4304
4305  if (Value.isSigned() && Value.isNegative()) {
4306    if (FieldName)
4307      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
4308               << FieldName << Value.toString(10);
4309    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4310      << Value.toString(10);
4311  }
4312
4313  if (!FieldTy->isDependentType()) {
4314    uint64_t TypeSize = Context.getTypeSize(FieldTy);
4315    if (Value.getZExtValue() > TypeSize) {
4316      if (FieldName)
4317        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4318          << FieldName << (unsigned)TypeSize;
4319      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4320        << (unsigned)TypeSize;
4321    }
4322  }
4323
4324  return false;
4325}
4326
4327/// ActOnField - Each field of a struct/union/class is passed into this in order
4328/// to create a FieldDecl object for it.
4329Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
4330                                 SourceLocation DeclStart,
4331                                 Declarator &D, ExprTy *BitfieldWidth) {
4332  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4333                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4334                               AS_public);
4335  return DeclPtrTy::make(Res);
4336}
4337
4338/// HandleField - Analyze a field of a C struct or a C++ data member.
4339///
4340FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4341                             SourceLocation DeclStart,
4342                             Declarator &D, Expr *BitWidth,
4343                             AccessSpecifier AS) {
4344  IdentifierInfo *II = D.getIdentifier();
4345  SourceLocation Loc = DeclStart;
4346  if (II) Loc = D.getIdentifierLoc();
4347
4348  QualType T = GetTypeForDeclarator(D, S);
4349  if (getLangOptions().CPlusPlus)
4350    CheckExtraCXXDefaultArguments(D);
4351
4352  DiagnoseFunctionSpecifiers(D);
4353
4354  if (D.getDeclSpec().isThreadSpecified())
4355    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4356
4357  NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
4358
4359  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4360    // Maybe we will complain about the shadowed template parameter.
4361    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4362    // Just pretend that we didn't see the previous declaration.
4363    PrevDecl = 0;
4364  }
4365
4366  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
4367    PrevDecl = 0;
4368
4369  bool Mutable
4370    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
4371  SourceLocation TSSL = D.getSourceRange().getBegin();
4372  FieldDecl *NewFD
4373    = CheckFieldDecl(II, T, Record, Loc, Mutable, BitWidth, TSSL,
4374                     AS, PrevDecl, &D);
4375  if (NewFD->isInvalidDecl() && PrevDecl) {
4376    // Don't introduce NewFD into scope; there's already something
4377    // with the same name in the same scope.
4378  } else if (II) {
4379    PushOnScopeChains(NewFD, S);
4380  } else
4381    Record->addDecl(NewFD);
4382
4383  return NewFD;
4384}
4385
4386/// \brief Build a new FieldDecl and check its well-formedness.
4387///
4388/// This routine builds a new FieldDecl given the fields name, type,
4389/// record, etc. \p PrevDecl should refer to any previous declaration
4390/// with the same name and in the same scope as the field to be
4391/// created.
4392///
4393/// \returns a new FieldDecl.
4394///
4395/// \todo The Declarator argument is a hack. It will be removed once
4396FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
4397                                RecordDecl *Record, SourceLocation Loc,
4398                                bool Mutable, Expr *BitWidth,
4399                                SourceLocation TSSL,
4400                                AccessSpecifier AS, NamedDecl *PrevDecl,
4401                                Declarator *D) {
4402  IdentifierInfo *II = Name.getAsIdentifierInfo();
4403  bool InvalidDecl = false;
4404  if (D) InvalidDecl = D->isInvalidType();
4405
4406  // If we receive a broken type, recover by assuming 'int' and
4407  // marking this declaration as invalid.
4408  if (T.isNull()) {
4409    InvalidDecl = true;
4410    T = Context.IntTy;
4411  }
4412
4413  // C99 6.7.2.1p8: A member of a structure or union may have any type other
4414  // than a variably modified type.
4415  if (T->isVariablyModifiedType()) {
4416    bool SizeIsNegative;
4417    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
4418                                                           SizeIsNegative);
4419    if (!FixedTy.isNull()) {
4420      Diag(Loc, diag::warn_illegal_constant_array_size);
4421      T = FixedTy;
4422    } else {
4423      if (SizeIsNegative)
4424        Diag(Loc, diag::err_typecheck_negative_array_size);
4425      else
4426        Diag(Loc, diag::err_typecheck_field_variable_size);
4427      InvalidDecl = true;
4428    }
4429  }
4430
4431  // Fields can not have abstract class types
4432  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
4433                             AbstractFieldType))
4434    InvalidDecl = true;
4435
4436  // If this is declared as a bit-field, check the bit-field.
4437  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) {
4438    InvalidDecl = true;
4439    DeleteExpr(BitWidth);
4440    BitWidth = 0;
4441  }
4442
4443  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth,
4444                                       Mutable, TSSL);
4445  if (InvalidDecl)
4446    NewFD->setInvalidDecl();
4447
4448  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
4449    Diag(Loc, diag::err_duplicate_member) << II;
4450    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4451    NewFD->setInvalidDecl();
4452  }
4453
4454  if (getLangOptions().CPlusPlus) {
4455    QualType EltTy = Context.getBaseElementType(T);
4456
4457    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
4458      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
4459
4460      if (!RDecl->hasTrivialConstructor())
4461        cast<CXXRecordDecl>(Record)->setHasTrivialConstructor(false);
4462      if (!RDecl->hasTrivialCopyConstructor())
4463        cast<CXXRecordDecl>(Record)->setHasTrivialCopyConstructor(false);
4464      if (!RDecl->hasTrivialCopyAssignment())
4465        cast<CXXRecordDecl>(Record)->setHasTrivialCopyAssignment(false);
4466      if (!RDecl->hasTrivialDestructor())
4467        cast<CXXRecordDecl>(Record)->setHasTrivialDestructor(false);
4468
4469      // C++ 9.5p1: An object of a class with a non-trivial
4470      // constructor, a non-trivial copy constructor, a non-trivial
4471      // destructor, or a non-trivial copy assignment operator
4472      // cannot be a member of a union, nor can an array of such
4473      // objects.
4474      // TODO: C++0x alters this restriction significantly.
4475      if (Record->isUnion()) {
4476        // We check for copy constructors before constructors
4477        // because otherwise we'll never get complaints about
4478        // copy constructors.
4479
4480        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
4481
4482        CXXSpecialMember member;
4483        if (!RDecl->hasTrivialCopyConstructor())
4484          member = CXXCopyConstructor;
4485        else if (!RDecl->hasTrivialConstructor())
4486          member = CXXDefaultConstructor;
4487        else if (!RDecl->hasTrivialCopyAssignment())
4488          member = CXXCopyAssignment;
4489        else if (!RDecl->hasTrivialDestructor())
4490          member = CXXDestructor;
4491        else
4492          member = invalid;
4493
4494        if (member != invalid) {
4495          Diag(Loc, diag::err_illegal_union_member) << Name << member;
4496          DiagnoseNontrivial(RT, member);
4497          NewFD->setInvalidDecl();
4498        }
4499      }
4500    }
4501  }
4502
4503  if (getLangOptions().CPlusPlus && !T->isPODType())
4504    cast<CXXRecordDecl>(Record)->setPOD(false);
4505
4506  // FIXME: We need to pass in the attributes given an AST
4507  // representation, not a parser representation.
4508  if (D)
4509    // FIXME: What to pass instead of TUScope?
4510    ProcessDeclAttributes(TUScope, NewFD, *D);
4511
4512  if (T.isObjCGCWeak())
4513    Diag(Loc, diag::warn_attribute_weak_on_field);
4514
4515  NewFD->setAccess(AS);
4516
4517  // C++ [dcl.init.aggr]p1:
4518  //   An aggregate is an array or a class (clause 9) with [...] no
4519  //   private or protected non-static data members (clause 11).
4520  // A POD must be an aggregate.
4521  if (getLangOptions().CPlusPlus &&
4522      (AS == AS_private || AS == AS_protected)) {
4523    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
4524    CXXRecord->setAggregate(false);
4525    CXXRecord->setPOD(false);
4526  }
4527
4528  return NewFD;
4529}
4530
4531/// DiagnoseNontrivial - Given that a class has a non-trivial
4532/// special member, figure out why.
4533void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
4534  QualType QT(T, 0U);
4535  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
4536
4537  // Check whether the member was user-declared.
4538  switch (member) {
4539  case CXXDefaultConstructor:
4540    if (RD->hasUserDeclaredConstructor()) {
4541      typedef CXXRecordDecl::ctor_iterator ctor_iter;
4542      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce; ++ci)
4543        if (!ci->isImplicitlyDefined(Context)) {
4544          SourceLocation CtorLoc = ci->getLocation();
4545          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4546          return;
4547        }
4548
4549      assert(0 && "found no user-declared constructors");
4550      return;
4551    }
4552    break;
4553
4554  case CXXCopyConstructor:
4555    if (RD->hasUserDeclaredCopyConstructor()) {
4556      SourceLocation CtorLoc =
4557        RD->getCopyConstructor(Context, 0)->getLocation();
4558      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4559      return;
4560    }
4561    break;
4562
4563  case CXXCopyAssignment:
4564    if (RD->hasUserDeclaredCopyAssignment()) {
4565      // FIXME: this should use the location of the copy
4566      // assignment, not the type.
4567      SourceLocation TyLoc = RD->getSourceRange().getBegin();
4568      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
4569      return;
4570    }
4571    break;
4572
4573  case CXXDestructor:
4574    if (RD->hasUserDeclaredDestructor()) {
4575      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
4576      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
4577      return;
4578    }
4579    break;
4580  }
4581
4582  typedef CXXRecordDecl::base_class_iterator base_iter;
4583
4584  // Virtual bases and members inhibit trivial copying/construction,
4585  // but not trivial destruction.
4586  if (member != CXXDestructor) {
4587    // Check for virtual bases.  vbases includes indirect virtual bases,
4588    // so we just iterate through the direct bases.
4589    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
4590      if (bi->isVirtual()) {
4591        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
4592        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
4593        return;
4594      }
4595
4596    // Check for virtual methods.
4597    typedef CXXRecordDecl::method_iterator meth_iter;
4598    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
4599         ++mi) {
4600      if (mi->isVirtual()) {
4601        SourceLocation MLoc = mi->getSourceRange().getBegin();
4602        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
4603        return;
4604      }
4605    }
4606  }
4607
4608  bool (CXXRecordDecl::*hasTrivial)() const;
4609  switch (member) {
4610  case CXXDefaultConstructor:
4611    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
4612  case CXXCopyConstructor:
4613    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
4614  case CXXCopyAssignment:
4615    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
4616  case CXXDestructor:
4617    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
4618  default:
4619    assert(0 && "unexpected special member"); return;
4620  }
4621
4622  // Check for nontrivial bases (and recurse).
4623  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
4624    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
4625    assert(BaseRT);
4626    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
4627    if (!(BaseRecTy->*hasTrivial)()) {
4628      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
4629      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
4630      DiagnoseNontrivial(BaseRT, member);
4631      return;
4632    }
4633  }
4634
4635  // Check for nontrivial members (and recurse).
4636  typedef RecordDecl::field_iterator field_iter;
4637  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
4638       ++fi) {
4639    QualType EltTy = Context.getBaseElementType((*fi)->getType());
4640    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
4641      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
4642
4643      if (!(EltRD->*hasTrivial)()) {
4644        SourceLocation FLoc = (*fi)->getLocation();
4645        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
4646        DiagnoseNontrivial(EltRT, member);
4647        return;
4648      }
4649    }
4650  }
4651
4652  assert(0 && "found no explanation for non-trivial member");
4653}
4654
4655/// TranslateIvarVisibility - Translate visibility from a token ID to an
4656///  AST enum value.
4657static ObjCIvarDecl::AccessControl
4658TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
4659  switch (ivarVisibility) {
4660  default: assert(0 && "Unknown visitibility kind");
4661  case tok::objc_private: return ObjCIvarDecl::Private;
4662  case tok::objc_public: return ObjCIvarDecl::Public;
4663  case tok::objc_protected: return ObjCIvarDecl::Protected;
4664  case tok::objc_package: return ObjCIvarDecl::Package;
4665  }
4666}
4667
4668/// ActOnIvar - Each ivar field of an objective-c class is passed into this
4669/// in order to create an IvarDecl object for it.
4670Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
4671                                SourceLocation DeclStart,
4672                                DeclPtrTy IntfDecl,
4673                                Declarator &D, ExprTy *BitfieldWidth,
4674                                tok::ObjCKeywordKind Visibility) {
4675
4676  IdentifierInfo *II = D.getIdentifier();
4677  Expr *BitWidth = (Expr*)BitfieldWidth;
4678  SourceLocation Loc = DeclStart;
4679  if (II) Loc = D.getIdentifierLoc();
4680
4681  // FIXME: Unnamed fields can be handled in various different ways, for
4682  // example, unnamed unions inject all members into the struct namespace!
4683
4684  QualType T = GetTypeForDeclarator(D, S);
4685
4686  if (BitWidth) {
4687    // 6.7.2.1p3, 6.7.2.1p4
4688    if (VerifyBitField(Loc, II, T, BitWidth)) {
4689      D.setInvalidType();
4690      DeleteExpr(BitWidth);
4691      BitWidth = 0;
4692    }
4693  } else {
4694    // Not a bitfield.
4695
4696    // validate II.
4697
4698  }
4699
4700  // C99 6.7.2.1p8: A member of a structure or union may have any type other
4701  // than a variably modified type.
4702  if (T->isVariablyModifiedType()) {
4703    Diag(Loc, diag::err_typecheck_ivar_variable_size);
4704    D.setInvalidType();
4705  }
4706
4707  // Get the visibility (access control) for this ivar.
4708  ObjCIvarDecl::AccessControl ac =
4709    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
4710                                        : ObjCIvarDecl::None;
4711  // Must set ivar's DeclContext to its enclosing interface.
4712  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
4713  DeclContext *EnclosingContext;
4714  if (ObjCImplementationDecl *IMPDecl =
4715      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
4716    // Case of ivar declared in an implementation. Context is that of its class.
4717    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
4718    assert(IDecl && "No class- ActOnIvar");
4719    EnclosingContext = cast_or_null<DeclContext>(IDecl);
4720  }
4721  else
4722    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
4723  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
4724
4725  // Construct the decl.
4726  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
4727                                             EnclosingContext, Loc, II, T,ac,
4728                                             (Expr *)BitfieldWidth);
4729
4730  if (II) {
4731    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
4732    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
4733        && !isa<TagDecl>(PrevDecl)) {
4734      Diag(Loc, diag::err_duplicate_member) << II;
4735      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4736      NewID->setInvalidDecl();
4737    }
4738  }
4739
4740  // Process attributes attached to the ivar.
4741  ProcessDeclAttributes(S, NewID, D);
4742
4743  if (D.isInvalidType())
4744    NewID->setInvalidDecl();
4745
4746  if (II) {
4747    // FIXME: When interfaces are DeclContexts, we'll need to add
4748    // these to the interface.
4749    S->AddDecl(DeclPtrTy::make(NewID));
4750    IdResolver.AddDecl(NewID);
4751  }
4752
4753  return DeclPtrTy::make(NewID);
4754}
4755
4756void Sema::ActOnFields(Scope* S,
4757                       SourceLocation RecLoc, DeclPtrTy RecDecl,
4758                       DeclPtrTy *Fields, unsigned NumFields,
4759                       SourceLocation LBrac, SourceLocation RBrac,
4760                       AttributeList *Attr) {
4761  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
4762  assert(EnclosingDecl && "missing record or interface decl");
4763
4764  // If the decl this is being inserted into is invalid, then it may be a
4765  // redeclaration or some other bogus case.  Don't try to add fields to it.
4766  if (EnclosingDecl->isInvalidDecl()) {
4767    // FIXME: Deallocate fields?
4768    return;
4769  }
4770
4771
4772  // Verify that all the fields are okay.
4773  unsigned NumNamedMembers = 0;
4774  llvm::SmallVector<FieldDecl*, 32> RecFields;
4775
4776  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
4777  for (unsigned i = 0; i != NumFields; ++i) {
4778    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
4779
4780    // Get the type for the field.
4781    Type *FDTy = FD->getType().getTypePtr();
4782
4783    if (!FD->isAnonymousStructOrUnion()) {
4784      // Remember all fields written by the user.
4785      RecFields.push_back(FD);
4786    }
4787
4788    // If the field is already invalid for some reason, don't emit more
4789    // diagnostics about it.
4790    if (FD->isInvalidDecl())
4791      continue;
4792
4793    // C99 6.7.2.1p2:
4794    //   A structure or union shall not contain a member with
4795    //   incomplete or function type (hence, a structure shall not
4796    //   contain an instance of itself, but may contain a pointer to
4797    //   an instance of itself), except that the last member of a
4798    //   structure with more than one named member may have incomplete
4799    //   array type; such a structure (and any union containing,
4800    //   possibly recursively, a member that is such a structure)
4801    //   shall not be a member of a structure or an element of an
4802    //   array.
4803    if (FDTy->isFunctionType()) {
4804      // Field declared as a function.
4805      Diag(FD->getLocation(), diag::err_field_declared_as_function)
4806        << FD->getDeclName();
4807      FD->setInvalidDecl();
4808      EnclosingDecl->setInvalidDecl();
4809      continue;
4810    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
4811               Record && Record->isStruct()) {
4812      // Flexible array member.
4813      if (NumNamedMembers < 1) {
4814        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
4815          << FD->getDeclName();
4816        FD->setInvalidDecl();
4817        EnclosingDecl->setInvalidDecl();
4818        continue;
4819      }
4820      // Okay, we have a legal flexible array member at the end of the struct.
4821      if (Record)
4822        Record->setHasFlexibleArrayMember(true);
4823    } else if (!FDTy->isDependentType() &&
4824               RequireCompleteType(FD->getLocation(), FD->getType(),
4825                                   diag::err_field_incomplete)) {
4826      // Incomplete type
4827      FD->setInvalidDecl();
4828      EnclosingDecl->setInvalidDecl();
4829      continue;
4830    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
4831      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
4832        // If this is a member of a union, then entire union becomes "flexible".
4833        if (Record && Record->isUnion()) {
4834          Record->setHasFlexibleArrayMember(true);
4835        } else {
4836          // If this is a struct/class and this is not the last element, reject
4837          // it.  Note that GCC supports variable sized arrays in the middle of
4838          // structures.
4839          if (i != NumFields-1)
4840            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
4841              << FD->getDeclName() << FD->getType();
4842          else {
4843            // We support flexible arrays at the end of structs in
4844            // other structs as an extension.
4845            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
4846              << FD->getDeclName();
4847            if (Record)
4848              Record->setHasFlexibleArrayMember(true);
4849          }
4850        }
4851      }
4852      if (Record && FDTTy->getDecl()->hasObjectMember())
4853        Record->setHasObjectMember(true);
4854    } else if (FDTy->isObjCInterfaceType()) {
4855      /// A field cannot be an Objective-c object
4856      Diag(FD->getLocation(), diag::err_statically_allocated_object);
4857      FD->setInvalidDecl();
4858      EnclosingDecl->setInvalidDecl();
4859      continue;
4860    }
4861    else if (getLangOptions().ObjC1 &&
4862             getLangOptions().getGCMode() != LangOptions::NonGC &&
4863             Record &&
4864             (FD->getType()->isObjCObjectPointerType() ||
4865              FD->getType().isObjCGCStrong()))
4866      Record->setHasObjectMember(true);
4867    // Keep track of the number of named members.
4868    if (FD->getIdentifier())
4869      ++NumNamedMembers;
4870  }
4871
4872  // Okay, we successfully defined 'Record'.
4873  if (Record) {
4874    Record->completeDefinition(Context);
4875  } else {
4876    ObjCIvarDecl **ClsFields =
4877      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
4878    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
4879      ID->setIVarList(ClsFields, RecFields.size(), Context);
4880      ID->setLocEnd(RBrac);
4881      // Add ivar's to class's DeclContext.
4882      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
4883        ClsFields[i]->setLexicalDeclContext(ID);
4884        ID->addDecl(ClsFields[i]);
4885      }
4886      // Must enforce the rule that ivars in the base classes may not be
4887      // duplicates.
4888      if (ID->getSuperClass()) {
4889        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
4890             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
4891          ObjCIvarDecl* Ivar = (*IVI);
4892
4893          if (IdentifierInfo *II = Ivar->getIdentifier()) {
4894            ObjCIvarDecl* prevIvar =
4895              ID->getSuperClass()->lookupInstanceVariable(II);
4896            if (prevIvar) {
4897              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
4898              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
4899            }
4900          }
4901        }
4902      }
4903    } else if (ObjCImplementationDecl *IMPDecl =
4904                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
4905      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
4906      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
4907        // Ivar declared in @implementation never belongs to the implementation.
4908        // Only it is in implementation's lexical context.
4909        ClsFields[I]->setLexicalDeclContext(IMPDecl);
4910      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
4911    }
4912  }
4913
4914  if (Attr)
4915    ProcessDeclAttributeList(S, Record, Attr);
4916}
4917
4918EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
4919                                          EnumConstantDecl *LastEnumConst,
4920                                          SourceLocation IdLoc,
4921                                          IdentifierInfo *Id,
4922                                          ExprArg val) {
4923  Expr *Val = (Expr *)val.get();
4924
4925  llvm::APSInt EnumVal(32);
4926  QualType EltTy;
4927  if (Val && !Val->isTypeDependent()) {
4928    // Make sure to promote the operand type to int.
4929    UsualUnaryConversions(Val);
4930    if (Val != val.get()) {
4931      val.release();
4932      val = Val;
4933    }
4934
4935    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
4936    SourceLocation ExpLoc;
4937    if (!Val->isValueDependent() &&
4938        VerifyIntegerConstantExpression(Val, &EnumVal)) {
4939      Val = 0;
4940    } else {
4941      EltTy = Val->getType();
4942    }
4943  }
4944
4945  if (!Val) {
4946    if (LastEnumConst) {
4947      // Assign the last value + 1.
4948      EnumVal = LastEnumConst->getInitVal();
4949      ++EnumVal;
4950
4951      // Check for overflow on increment.
4952      if (EnumVal < LastEnumConst->getInitVal())
4953        Diag(IdLoc, diag::warn_enum_value_overflow);
4954
4955      EltTy = LastEnumConst->getType();
4956    } else {
4957      // First value, set to zero.
4958      EltTy = Context.IntTy;
4959      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
4960    }
4961  }
4962
4963  val.release();
4964  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
4965                                  Val, EnumVal);
4966}
4967
4968
4969Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
4970                                        DeclPtrTy lastEnumConst,
4971                                        SourceLocation IdLoc,
4972                                        IdentifierInfo *Id,
4973                                        SourceLocation EqualLoc, ExprTy *val) {
4974  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
4975  EnumConstantDecl *LastEnumConst =
4976    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
4977  Expr *Val = static_cast<Expr*>(val);
4978
4979  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4980  // we find one that is.
4981  S = getNonFieldDeclScope(S);
4982
4983  // Verify that there isn't already something declared with this name in this
4984  // scope.
4985  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
4986  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4987    // Maybe we will complain about the shadowed template parameter.
4988    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
4989    // Just pretend that we didn't see the previous declaration.
4990    PrevDecl = 0;
4991  }
4992
4993  if (PrevDecl) {
4994    // When in C++, we may get a TagDecl with the same name; in this case the
4995    // enum constant will 'hide' the tag.
4996    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
4997           "Received TagDecl when not in C++!");
4998    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
4999      if (isa<EnumConstantDecl>(PrevDecl))
5000        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5001      else
5002        Diag(IdLoc, diag::err_redefinition) << Id;
5003      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5004      if (Val) Val->Destroy(Context);
5005      return DeclPtrTy();
5006    }
5007  }
5008
5009  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5010                                            IdLoc, Id, Owned(Val));
5011
5012  // Register this decl in the current scope stack.
5013  if (New)
5014    PushOnScopeChains(New, S);
5015
5016  return DeclPtrTy::make(New);
5017}
5018
5019void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5020                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5021                         DeclPtrTy *Elements, unsigned NumElements) {
5022  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5023  QualType EnumType = Context.getTypeDeclType(Enum);
5024
5025  // TODO: If the result value doesn't fit in an int, it must be a long or long
5026  // long value.  ISO C does not support this, but GCC does as an extension,
5027  // emit a warning.
5028  unsigned IntWidth = Context.Target.getIntWidth();
5029
5030  // Verify that all the values are okay, compute the size of the values, and
5031  // reverse the list.
5032  unsigned NumNegativeBits = 0;
5033  unsigned NumPositiveBits = 0;
5034
5035  // Keep track of whether all elements have type int.
5036  bool AllElementsInt = true;
5037
5038  for (unsigned i = 0; i != NumElements; ++i) {
5039    EnumConstantDecl *ECD =
5040      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5041    if (!ECD) continue;  // Already issued a diagnostic.
5042
5043    // If the enum value doesn't fit in an int, emit an extension warning.
5044    const llvm::APSInt &InitVal = ECD->getInitVal();
5045    assert(InitVal.getBitWidth() >= IntWidth &&
5046           "Should have promoted value to int");
5047    if (InitVal.getBitWidth() > IntWidth) {
5048      llvm::APSInt V(InitVal);
5049      V.trunc(IntWidth);
5050      V.extend(InitVal.getBitWidth());
5051      if (V != InitVal)
5052        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5053          << InitVal.toString(10);
5054    }
5055
5056    // Keep track of the size of positive and negative values.
5057    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5058      NumPositiveBits = std::max(NumPositiveBits,
5059                                 (unsigned)InitVal.getActiveBits());
5060    else
5061      NumNegativeBits = std::max(NumNegativeBits,
5062                                 (unsigned)InitVal.getMinSignedBits());
5063
5064    // Keep track of whether every enum element has type int (very commmon).
5065    if (AllElementsInt)
5066      AllElementsInt = ECD->getType() == Context.IntTy;
5067  }
5068
5069  // Figure out the type that should be used for this enum.
5070  // FIXME: Support attribute(packed) on enums and -fshort-enums.
5071  QualType BestType;
5072  unsigned BestWidth;
5073
5074  if (NumNegativeBits) {
5075    // If there is a negative value, figure out the smallest integer type (of
5076    // int/long/longlong) that fits.
5077    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5078      BestType = Context.IntTy;
5079      BestWidth = IntWidth;
5080    } else {
5081      BestWidth = Context.Target.getLongWidth();
5082
5083      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
5084        BestType = Context.LongTy;
5085      else {
5086        BestWidth = Context.Target.getLongLongWidth();
5087
5088        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5089          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5090        BestType = Context.LongLongTy;
5091      }
5092    }
5093  } else {
5094    // If there is no negative value, figure out which of uint, ulong, ulonglong
5095    // fits.
5096    if (NumPositiveBits <= IntWidth) {
5097      BestType = Context.UnsignedIntTy;
5098      BestWidth = IntWidth;
5099    } else if (NumPositiveBits <=
5100               (BestWidth = Context.Target.getLongWidth())) {
5101      BestType = Context.UnsignedLongTy;
5102    } else {
5103      BestWidth = Context.Target.getLongLongWidth();
5104      assert(NumPositiveBits <= BestWidth &&
5105             "How could an initializer get larger than ULL?");
5106      BestType = Context.UnsignedLongLongTy;
5107    }
5108  }
5109
5110  // Loop over all of the enumerator constants, changing their types to match
5111  // the type of the enum if needed.
5112  for (unsigned i = 0; i != NumElements; ++i) {
5113    EnumConstantDecl *ECD =
5114      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5115    if (!ECD) continue;  // Already issued a diagnostic.
5116
5117    // Standard C says the enumerators have int type, but we allow, as an
5118    // extension, the enumerators to be larger than int size.  If each
5119    // enumerator value fits in an int, type it as an int, otherwise type it the
5120    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5121    // that X has type 'int', not 'unsigned'.
5122    if (ECD->getType() == Context.IntTy) {
5123      // Make sure the init value is signed.
5124      llvm::APSInt IV = ECD->getInitVal();
5125      IV.setIsSigned(true);
5126      ECD->setInitVal(IV);
5127
5128      if (getLangOptions().CPlusPlus)
5129        // C++ [dcl.enum]p4: Following the closing brace of an
5130        // enum-specifier, each enumerator has the type of its
5131        // enumeration.
5132        ECD->setType(EnumType);
5133      continue;  // Already int type.
5134    }
5135
5136    // Determine whether the value fits into an int.
5137    llvm::APSInt InitVal = ECD->getInitVal();
5138    bool FitsInInt;
5139    if (InitVal.isUnsigned() || !InitVal.isNegative())
5140      FitsInInt = InitVal.getActiveBits() < IntWidth;
5141    else
5142      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5143
5144    // If it fits into an integer type, force it.  Otherwise force it to match
5145    // the enum decl type.
5146    QualType NewTy;
5147    unsigned NewWidth;
5148    bool NewSign;
5149    if (FitsInInt) {
5150      NewTy = Context.IntTy;
5151      NewWidth = IntWidth;
5152      NewSign = true;
5153    } else if (ECD->getType() == BestType) {
5154      // Already the right type!
5155      if (getLangOptions().CPlusPlus)
5156        // C++ [dcl.enum]p4: Following the closing brace of an
5157        // enum-specifier, each enumerator has the type of its
5158        // enumeration.
5159        ECD->setType(EnumType);
5160      continue;
5161    } else {
5162      NewTy = BestType;
5163      NewWidth = BestWidth;
5164      NewSign = BestType->isSignedIntegerType();
5165    }
5166
5167    // Adjust the APSInt value.
5168    InitVal.extOrTrunc(NewWidth);
5169    InitVal.setIsSigned(NewSign);
5170    ECD->setInitVal(InitVal);
5171
5172    // Adjust the Expr initializer and type.
5173    if (ECD->getInitExpr())
5174      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5175                                                      CastExpr::CK_Unknown,
5176                                                      ECD->getInitExpr(),
5177                                                      /*isLvalue=*/false));
5178    if (getLangOptions().CPlusPlus)
5179      // C++ [dcl.enum]p4: Following the closing brace of an
5180      // enum-specifier, each enumerator has the type of its
5181      // enumeration.
5182      ECD->setType(EnumType);
5183    else
5184      ECD->setType(NewTy);
5185  }
5186
5187  Enum->completeDefinition(Context, BestType);
5188}
5189
5190Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5191                                            ExprArg expr) {
5192  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
5193
5194  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5195                                                   Loc, AsmString);
5196  CurContext->addDecl(New);
5197  return DeclPtrTy::make(New);
5198}
5199
5200void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5201                             SourceLocation PragmaLoc,
5202                             SourceLocation NameLoc) {
5203  Decl *PrevDecl = LookupName(TUScope, Name, LookupOrdinaryName);
5204
5205  if (PrevDecl) {
5206    PrevDecl->addAttr(::new (Context) WeakAttr());
5207  } else {
5208    (void)WeakUndeclaredIdentifiers.insert(
5209      std::pair<IdentifierInfo*,WeakInfo>
5210        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
5211  }
5212}
5213
5214void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5215                                IdentifierInfo* AliasName,
5216                                SourceLocation PragmaLoc,
5217                                SourceLocation NameLoc,
5218                                SourceLocation AliasNameLoc) {
5219  Decl *PrevDecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
5220  WeakInfo W = WeakInfo(Name, NameLoc);
5221
5222  if (PrevDecl) {
5223    if (!PrevDecl->hasAttr<AliasAttr>())
5224      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
5225        DeclApplyPragmaWeak(TUScope, ND, W);
5226  } else {
5227    (void)WeakUndeclaredIdentifiers.insert(
5228      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
5229  }
5230}
5231