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