SemaDecl.cpp revision 369a3bd9979cf529eed529aa037de713c213e47d
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  for (Path.Decls = BaseRecord->lookup(Data->Method->getDeclName());
2594       Path.Decls.first != Path.Decls.second;
2595       ++Path.Decls.first) {
2596    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2597      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2598        return true;
2599    }
2600  }
2601
2602  return false;
2603}
2604
2605/// AddOverriddenMethods - See if a method overrides any in the base classes,
2606/// and if so, check that it's a valid override and remember it.
2607void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2608  // Look for virtual methods in base classes that this method might override.
2609  CXXBasePaths Paths;
2610  FindOverriddenMethodData Data;
2611  Data.Method = MD;
2612  Data.S = this;
2613  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2614    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2615         E = Paths.found_decls_end(); I != E; ++I) {
2616      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2617        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2618            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2619            !CheckOverridingFunctionAttributes(MD, OldMD))
2620          MD->addOverriddenMethod(OldMD);
2621      }
2622    }
2623  }
2624}
2625
2626NamedDecl*
2627Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2628                              QualType R, DeclaratorInfo *DInfo,
2629                              LookupResult &Previous,
2630                              MultiTemplateParamsArg TemplateParamLists,
2631                              bool IsFunctionDefinition, bool &Redeclaration) {
2632  assert(R.getTypePtr()->isFunctionType());
2633
2634  DeclarationName Name = GetNameForDeclarator(D);
2635  FunctionDecl::StorageClass SC = FunctionDecl::None;
2636  switch (D.getDeclSpec().getStorageClassSpec()) {
2637  default: assert(0 && "Unknown storage class!");
2638  case DeclSpec::SCS_auto:
2639  case DeclSpec::SCS_register:
2640  case DeclSpec::SCS_mutable:
2641    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2642         diag::err_typecheck_sclass_func);
2643    D.setInvalidType();
2644    break;
2645  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2646  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2647  case DeclSpec::SCS_static: {
2648    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2649      // C99 6.7.1p5:
2650      //   The declaration of an identifier for a function that has
2651      //   block scope shall have no explicit storage-class specifier
2652      //   other than extern
2653      // See also (C++ [dcl.stc]p4).
2654      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2655           diag::err_static_block_func);
2656      SC = FunctionDecl::None;
2657    } else
2658      SC = FunctionDecl::Static;
2659    break;
2660  }
2661  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2662  }
2663
2664  if (D.getDeclSpec().isThreadSpecified())
2665    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2666
2667  bool isFriend = D.getDeclSpec().isFriendSpecified();
2668  bool isInline = D.getDeclSpec().isInlineSpecified();
2669  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2670  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2671
2672  // Check that the return type is not an abstract class type.
2673  // For record types, this is done by the AbstractClassUsageDiagnoser once
2674  // the class has been completely parsed.
2675  if (!DC->isRecord() &&
2676      RequireNonAbstractType(D.getIdentifierLoc(),
2677                             R->getAs<FunctionType>()->getResultType(),
2678                             diag::err_abstract_type_in_decl,
2679                             AbstractReturnType))
2680    D.setInvalidType();
2681
2682  // Do not allow returning a objc interface by-value.
2683  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2684    Diag(D.getIdentifierLoc(),
2685         diag::err_object_cannot_be_passed_returned_by_value) << 0
2686      << R->getAs<FunctionType>()->getResultType();
2687    D.setInvalidType();
2688  }
2689
2690  bool isVirtualOkay = false;
2691  FunctionDecl *NewFD;
2692
2693  if (isFriend) {
2694    // C++ [class.friend]p5
2695    //   A function can be defined in a friend declaration of a
2696    //   class . . . . Such a function is implicitly inline.
2697    isInline |= IsFunctionDefinition;
2698  }
2699
2700  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2701    // This is a C++ constructor declaration.
2702    assert(DC->isRecord() &&
2703           "Constructors can only be declared in a member context");
2704
2705    R = CheckConstructorDeclarator(D, R, SC);
2706
2707    // Create the new declaration
2708    NewFD = CXXConstructorDecl::Create(Context,
2709                                       cast<CXXRecordDecl>(DC),
2710                                       D.getIdentifierLoc(), Name, R, DInfo,
2711                                       isExplicit, isInline,
2712                                       /*isImplicitlyDeclared=*/false);
2713  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2714    // This is a C++ destructor declaration.
2715    if (DC->isRecord()) {
2716      R = CheckDestructorDeclarator(D, SC);
2717
2718      NewFD = CXXDestructorDecl::Create(Context,
2719                                        cast<CXXRecordDecl>(DC),
2720                                        D.getIdentifierLoc(), Name, R,
2721                                        isInline,
2722                                        /*isImplicitlyDeclared=*/false);
2723
2724      isVirtualOkay = true;
2725    } else {
2726      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2727
2728      // Create a FunctionDecl to satisfy the function definition parsing
2729      // code path.
2730      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2731                                   Name, R, DInfo, SC, isInline,
2732                                   /*hasPrototype=*/true);
2733      D.setInvalidType();
2734    }
2735  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2736    if (!DC->isRecord()) {
2737      Diag(D.getIdentifierLoc(),
2738           diag::err_conv_function_not_member);
2739      return 0;
2740    }
2741
2742    CheckConversionDeclarator(D, R, SC);
2743    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2744                                      D.getIdentifierLoc(), Name, R, DInfo,
2745                                      isInline, isExplicit);
2746
2747    isVirtualOkay = true;
2748  } else if (DC->isRecord()) {
2749    // If the of the function is the same as the name of the record, then this
2750    // must be an invalid constructor that has a return type.
2751    // (The parser checks for a return type and makes the declarator a
2752    // constructor if it has no return type).
2753    // must have an invalid constructor that has a return type
2754    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2755      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2756        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2757        << SourceRange(D.getIdentifierLoc());
2758      return 0;
2759    }
2760
2761    bool isStatic = SC == FunctionDecl::Static;
2762
2763    // [class.free]p1:
2764    // Any allocation function for a class T is a static member
2765    // (even if not explicitly declared static).
2766    if (Name.getCXXOverloadedOperator() == OO_New ||
2767        Name.getCXXOverloadedOperator() == OO_Array_New)
2768      isStatic = true;
2769
2770    // [class.free]p6 Any deallocation function for a class X is a static member
2771    // (even if not explicitly declared static).
2772    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2773        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2774      isStatic = true;
2775
2776    // This is a C++ method declaration.
2777    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2778                                  D.getIdentifierLoc(), Name, R, DInfo,
2779                                  isStatic, isInline);
2780
2781    isVirtualOkay = !isStatic;
2782  } else {
2783    // Determine whether the function was written with a
2784    // prototype. This true when:
2785    //   - we're in C++ (where every function has a prototype),
2786    //   - there is a prototype in the declarator, or
2787    //   - the type R of the function is some kind of typedef or other reference
2788    //     to a type name (which eventually refers to a function type).
2789    bool HasPrototype =
2790       getLangOptions().CPlusPlus ||
2791       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2792       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2793
2794    NewFD = FunctionDecl::Create(Context, DC,
2795                                 D.getIdentifierLoc(),
2796                                 Name, R, DInfo, SC, isInline, HasPrototype);
2797  }
2798
2799  if (D.isInvalidType())
2800    NewFD->setInvalidDecl();
2801
2802  // Set the lexical context. If the declarator has a C++
2803  // scope specifier, or is the object of a friend declaration, the
2804  // lexical context will be different from the semantic context.
2805  NewFD->setLexicalDeclContext(CurContext);
2806
2807  // Match up the template parameter lists with the scope specifier, then
2808  // determine whether we have a template or a template specialization.
2809  FunctionTemplateDecl *FunctionTemplate = 0;
2810  bool isExplicitSpecialization = false;
2811  bool isFunctionTemplateSpecialization = false;
2812  if (TemplateParameterList *TemplateParams
2813        = MatchTemplateParametersToScopeSpecifier(
2814                                  D.getDeclSpec().getSourceRange().getBegin(),
2815                                  D.getCXXScopeSpec(),
2816                           (TemplateParameterList**)TemplateParamLists.get(),
2817                                                  TemplateParamLists.size(),
2818                                                  isExplicitSpecialization)) {
2819    if (TemplateParams->size() > 0) {
2820      // This is a function template
2821
2822      // Check that we can declare a template here.
2823      if (CheckTemplateDeclScope(S, TemplateParams))
2824        return 0;
2825
2826      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2827                                                      NewFD->getLocation(),
2828                                                      Name, TemplateParams,
2829                                                      NewFD);
2830      FunctionTemplate->setLexicalDeclContext(CurContext);
2831      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2832    } else {
2833      // This is a function template specialization.
2834      isFunctionTemplateSpecialization = true;
2835    }
2836
2837    // FIXME: Free this memory properly.
2838    TemplateParamLists.release();
2839  }
2840
2841  // C++ [dcl.fct.spec]p5:
2842  //   The virtual specifier shall only be used in declarations of
2843  //   nonstatic class member functions that appear within a
2844  //   member-specification of a class declaration; see 10.3.
2845  //
2846  if (isVirtual && !NewFD->isInvalidDecl()) {
2847    if (!isVirtualOkay) {
2848       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2849           diag::err_virtual_non_function);
2850    } else if (!CurContext->isRecord()) {
2851      // 'virtual' was specified outside of the class.
2852      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2853        << CodeModificationHint::CreateRemoval(
2854                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2855    } else {
2856      // Okay: Add virtual to the method.
2857      cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
2858      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2859      CurClass->setAggregate(false);
2860      CurClass->setPOD(false);
2861      CurClass->setEmpty(false);
2862      CurClass->setPolymorphic(true);
2863      CurClass->setHasTrivialConstructor(false);
2864      CurClass->setHasTrivialCopyConstructor(false);
2865      CurClass->setHasTrivialCopyAssignment(false);
2866    }
2867  }
2868
2869  // Filter out previous declarations that don't match the scope.
2870  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2871
2872  if (isFriend) {
2873    // DC is the namespace in which the function is being declared.
2874    assert((DC->isFileContext() || !Previous.empty()) &&
2875           "previously-undeclared friend function being created "
2876           "in a non-namespace context");
2877
2878    if (FunctionTemplate) {
2879      FunctionTemplate->setObjectOfFriendDecl(
2880                                   /* PreviouslyDeclared= */ !Previous.empty());
2881      FunctionTemplate->setAccess(AS_public);
2882    }
2883    else
2884      NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2885
2886    NewFD->setAccess(AS_public);
2887  }
2888
2889  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
2890    AddOverriddenMethods(cast<CXXRecordDecl>(DC), NewMD);
2891
2892  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2893      !CurContext->isRecord()) {
2894    // C++ [class.static]p1:
2895    //   A data or function member of a class may be declared static
2896    //   in a class definition, in which case it is a static member of
2897    //   the class.
2898
2899    // Complain about the 'static' specifier if it's on an out-of-line
2900    // member function definition.
2901    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2902         diag::err_static_out_of_line)
2903      << CodeModificationHint::CreateRemoval(
2904                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2905  }
2906
2907  // Handle GNU asm-label extension (encoded as an attribute).
2908  if (Expr *E = (Expr*) D.getAsmLabel()) {
2909    // The parser guarantees this is a string.
2910    StringLiteral *SE = cast<StringLiteral>(E);
2911    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2912                                                        SE->getByteLength())));
2913  }
2914
2915  // Copy the parameter declarations from the declarator D to the function
2916  // declaration NewFD, if they are available.  First scavenge them into Params.
2917  llvm::SmallVector<ParmVarDecl*, 16> Params;
2918  if (D.getNumTypeObjects() > 0) {
2919    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2920
2921    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2922    // function that takes no arguments, not a function that takes a
2923    // single void argument.
2924    // We let through "const void" here because Sema::GetTypeForDeclarator
2925    // already checks for that case.
2926    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2927        FTI.ArgInfo[0].Param &&
2928        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2929      // Empty arg list, don't push any params.
2930      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2931
2932      // In C++, the empty parameter-type-list must be spelled "void"; a
2933      // typedef of void is not permitted.
2934      if (getLangOptions().CPlusPlus &&
2935          Param->getType().getUnqualifiedType() != Context.VoidTy)
2936        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2937      // FIXME: Leaks decl?
2938    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2939      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2940        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2941        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2942        Param->setDeclContext(NewFD);
2943        Params.push_back(Param);
2944      }
2945    }
2946
2947  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2948    // When we're declaring a function with a typedef, typeof, etc as in the
2949    // following example, we'll need to synthesize (unnamed)
2950    // parameters for use in the declaration.
2951    //
2952    // @code
2953    // typedef void fn(int);
2954    // fn f;
2955    // @endcode
2956
2957    // Synthesize a parameter for each argument type.
2958    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2959         AE = FT->arg_type_end(); AI != AE; ++AI) {
2960      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2961                                               SourceLocation(), 0,
2962                                               *AI, /*DInfo=*/0,
2963                                               VarDecl::None, 0);
2964      Param->setImplicit();
2965      Params.push_back(Param);
2966    }
2967  } else {
2968    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2969           "Should not need args for typedef of non-prototype fn");
2970  }
2971  // Finally, we know we have the right number of parameters, install them.
2972  NewFD->setParams(Context, Params.data(), Params.size());
2973
2974  // If the declarator is a template-id, translate the parser's template
2975  // argument list into our AST format.
2976  bool HasExplicitTemplateArgs = false;
2977  TemplateArgumentListInfo TemplateArgs;
2978  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2979    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2980    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
2981    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
2982    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2983                                       TemplateId->getTemplateArgs(),
2984                                       TemplateId->NumArgs);
2985    translateTemplateArguments(TemplateArgsPtr,
2986                               TemplateArgs);
2987    TemplateArgsPtr.release();
2988
2989    HasExplicitTemplateArgs = true;
2990
2991    if (FunctionTemplate) {
2992      // FIXME: Diagnose function template with explicit template
2993      // arguments.
2994      HasExplicitTemplateArgs = false;
2995    } else if (!isFunctionTemplateSpecialization &&
2996               !D.getDeclSpec().isFriendSpecified()) {
2997      // We have encountered something that the user meant to be a
2998      // specialization (because it has explicitly-specified template
2999      // arguments) but that was not introduced with a "template<>" (or had
3000      // too few of them).
3001      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3002        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3003        << CodeModificationHint::CreateInsertion(
3004                                   D.getDeclSpec().getSourceRange().getBegin(),
3005                                                 "template<> ");
3006      isFunctionTemplateSpecialization = true;
3007    }
3008  }
3009
3010  if (isFunctionTemplateSpecialization) {
3011      if (CheckFunctionTemplateSpecialization(NewFD,
3012                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3013                                              Previous))
3014        NewFD->setInvalidDecl();
3015  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3016             CheckMemberSpecialization(NewFD, Previous))
3017    NewFD->setInvalidDecl();
3018
3019  // Perform semantic checking on the function declaration.
3020  bool OverloadableAttrRequired = false; // FIXME: HACK!
3021  CheckFunctionDeclaration(NewFD, Previous, isExplicitSpecialization,
3022                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3023
3024  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3025          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3026         "previous declaration set still overloaded");
3027
3028  // If we have a function template, check the template parameter
3029  // list. This will check and merge default template arguments.
3030  if (FunctionTemplate) {
3031    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3032    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3033                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3034             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3035                                                : TPC_FunctionTemplate);
3036  }
3037
3038  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3039    // An out-of-line member function declaration must also be a
3040    // definition (C++ [dcl.meaning]p1).
3041    // Note that this is not the case for explicit specializations of
3042    // function templates or member functions of class templates, per
3043    // C++ [temp.expl.spec]p2.
3044    if (!IsFunctionDefinition && !isFriend &&
3045        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3046      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3047        << D.getCXXScopeSpec().getRange();
3048      NewFD->setInvalidDecl();
3049    } else if (!Redeclaration) {
3050      // The user tried to provide an out-of-line definition for a
3051      // function that is a member of a class or namespace, but there
3052      // was no such member function declared (C++ [class.mfct]p2,
3053      // C++ [namespace.memdef]p2). For example:
3054      //
3055      // class X {
3056      //   void f() const;
3057      // };
3058      //
3059      // void X::f() { } // ill-formed
3060      //
3061      // Complain about this problem, and attempt to suggest close
3062      // matches (e.g., those that differ only in cv-qualifiers and
3063      // whether the parameter types are references).
3064      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3065        << Name << DC << D.getCXXScopeSpec().getRange();
3066      NewFD->setInvalidDecl();
3067
3068      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3069                        ForRedeclaration);
3070      LookupQualifiedName(Prev, DC);
3071      assert(!Prev.isAmbiguous() &&
3072             "Cannot have an ambiguity in previous-declaration lookup");
3073      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3074           Func != FuncEnd; ++Func) {
3075        if (isa<FunctionDecl>(*Func) &&
3076            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3077          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3078      }
3079    }
3080  }
3081
3082  // Handle attributes. We need to have merged decls when handling attributes
3083  // (for example to check for conflicts, etc).
3084  // FIXME: This needs to happen before we merge declarations. Then,
3085  // let attribute merging cope with attribute conflicts.
3086  ProcessDeclAttributes(S, NewFD, D);
3087
3088  // attributes declared post-definition are currently ignored
3089  if (Redeclaration && Previous.isSingleResult()) {
3090    const FunctionDecl *Def;
3091    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3092    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3093      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3094      Diag(Def->getLocation(), diag::note_previous_definition);
3095    }
3096  }
3097
3098  AddKnownFunctionAttributes(NewFD);
3099
3100  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3101    // If a function name is overloadable in C, then every function
3102    // with that name must be marked "overloadable".
3103    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3104      << Redeclaration << NewFD;
3105    if (!Previous.empty())
3106      Diag(Previous.getRepresentativeDecl()->getLocation(),
3107           diag::note_attribute_overloadable_prev_overload);
3108    NewFD->addAttr(::new (Context) OverloadableAttr());
3109  }
3110
3111  // If this is a locally-scoped extern C function, update the
3112  // map of such names.
3113  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3114      && !NewFD->isInvalidDecl())
3115    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3116
3117  // Set this FunctionDecl's range up to the right paren.
3118  NewFD->setLocEnd(D.getSourceRange().getEnd());
3119
3120  if (FunctionTemplate && NewFD->isInvalidDecl())
3121    FunctionTemplate->setInvalidDecl();
3122
3123  if (FunctionTemplate)
3124    return FunctionTemplate;
3125
3126  return NewFD;
3127}
3128
3129/// \brief Perform semantic checking of a new function declaration.
3130///
3131/// Performs semantic analysis of the new function declaration
3132/// NewFD. This routine performs all semantic checking that does not
3133/// require the actual declarator involved in the declaration, and is
3134/// used both for the declaration of functions as they are parsed
3135/// (called via ActOnDeclarator) and for the declaration of functions
3136/// that have been instantiated via C++ template instantiation (called
3137/// via InstantiateDecl).
3138///
3139/// \param IsExplicitSpecialiation whether this new function declaration is
3140/// an explicit specialization of the previous declaration.
3141///
3142/// This sets NewFD->isInvalidDecl() to true if there was an error.
3143void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD,
3144                                    LookupResult &Previous,
3145                                    bool IsExplicitSpecialization,
3146                                    bool &Redeclaration,
3147                                    bool &OverloadableAttrRequired) {
3148  // If NewFD is already known erroneous, don't do any of this checking.
3149  if (NewFD->isInvalidDecl())
3150    return;
3151
3152  if (NewFD->getResultType()->isVariablyModifiedType()) {
3153    // Functions returning a variably modified type violate C99 6.7.5.2p2
3154    // because all functions have linkage.
3155    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3156    return NewFD->setInvalidDecl();
3157  }
3158
3159  if (NewFD->isMain())
3160    CheckMain(NewFD);
3161
3162  // Check for a previous declaration of this name.
3163  if (Previous.empty() && NewFD->isExternC()) {
3164    // Since we did not find anything by this name and we're declaring
3165    // an extern "C" function, look for a non-visible extern "C"
3166    // declaration with the same name.
3167    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3168      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3169    if (Pos != LocallyScopedExternalDecls.end())
3170      Previous.addDecl(Pos->second);
3171  }
3172
3173  // Merge or overload the declaration with an existing declaration of
3174  // the same name, if appropriate.
3175  if (!Previous.empty()) {
3176    // Determine whether NewFD is an overload of PrevDecl or
3177    // a declaration that requires merging. If it's an overload,
3178    // there's no more work to do here; we'll just add the new
3179    // function to the scope.
3180
3181    if (!getLangOptions().CPlusPlus &&
3182        AllowOverloadingOfFunction(Previous, Context)) {
3183      OverloadableAttrRequired = true;
3184
3185      // Functions marked "overloadable" must have a prototype (that
3186      // we can't get through declaration merging).
3187      if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3188        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
3189          << NewFD;
3190        Redeclaration = true;
3191
3192        // Turn this into a variadic function with no parameters.
3193        QualType R = Context.getFunctionType(
3194                       NewFD->getType()->getAs<FunctionType>()->getResultType(),
3195                       0, 0, true, 0);
3196        NewFD->setType(R);
3197        return NewFD->setInvalidDecl();
3198      }
3199    }
3200
3201    NamedDecl *OldDecl = 0;
3202    if (!Previous.empty()) {
3203      if (!AllowOverloadingOfFunction(Previous, Context)) {
3204        Redeclaration = true;
3205        OldDecl = Previous.getFoundDecl();
3206      } else if (!IsOverload(NewFD, Previous, OldDecl)) {
3207        if (!isUsingDecl(OldDecl))
3208          Redeclaration = true;
3209      }
3210    }
3211
3212    if (Redeclaration) {
3213      // NewFD and OldDecl represent declarations that need to be
3214      // merged.
3215      if (MergeFunctionDecl(NewFD, OldDecl))
3216        return NewFD->setInvalidDecl();
3217
3218      Previous.clear();
3219      Previous.addDecl(OldDecl);
3220
3221      if (FunctionTemplateDecl *OldTemplateDecl
3222                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3223        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3224        FunctionTemplateDecl *NewTemplateDecl
3225          = NewFD->getDescribedFunctionTemplate();
3226        assert(NewTemplateDecl && "Template/non-template mismatch");
3227        if (CXXMethodDecl *Method
3228              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3229          Method->setAccess(OldTemplateDecl->getAccess());
3230          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3231        }
3232
3233        // If this is an explicit specialization of a member that is a function
3234        // template, mark it as a member specialization.
3235        if (IsExplicitSpecialization &&
3236            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3237          NewTemplateDecl->setMemberSpecialization();
3238          assert(OldTemplateDecl->isMemberSpecialization());
3239        }
3240      } else {
3241        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3242          NewFD->setAccess(OldDecl->getAccess());
3243        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3244      }
3245    }
3246  }
3247
3248  // Semantic checking for this function declaration (in isolation).
3249  if (getLangOptions().CPlusPlus) {
3250    // C++-specific checks.
3251    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3252      CheckConstructor(Constructor);
3253    } else if (CXXDestructorDecl *Destructor =
3254                dyn_cast<CXXDestructorDecl>(NewFD)) {
3255      CXXRecordDecl *Record = Destructor->getParent();
3256      QualType ClassType = Context.getTypeDeclType(Record);
3257
3258      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3259      // type is dependent? Both gcc and edg can handle that.
3260      if (!ClassType->isDependentType()) {
3261        DeclarationName Name
3262          = Context.DeclarationNames.getCXXDestructorName(
3263                                        Context.getCanonicalType(ClassType));
3264        if (NewFD->getDeclName() != Name) {
3265          Diag(NewFD->getLocation(), diag::err_destructor_name);
3266          return NewFD->setInvalidDecl();
3267        }
3268
3269        CheckDestructor(Destructor);
3270      }
3271
3272      Record->setUserDeclaredDestructor(true);
3273      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3274      // user-defined destructor.
3275      Record->setPOD(false);
3276
3277      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3278      // declared destructor.
3279      // FIXME: C++0x: don't do this for "= default" destructors
3280      Record->setHasTrivialDestructor(false);
3281    } else if (CXXConversionDecl *Conversion
3282               = dyn_cast<CXXConversionDecl>(NewFD))
3283      ActOnConversionDeclarator(Conversion);
3284
3285    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3286    if (NewFD->isOverloadedOperator() &&
3287        CheckOverloadedOperatorDeclaration(NewFD))
3288      return NewFD->setInvalidDecl();
3289
3290    // In C++, check default arguments now that we have merged decls. Unless
3291    // the lexical context is the class, because in this case this is done
3292    // during delayed parsing anyway.
3293    if (!CurContext->isRecord())
3294      CheckCXXDefaultArguments(NewFD);
3295  }
3296}
3297
3298void Sema::CheckMain(FunctionDecl* FD) {
3299  // C++ [basic.start.main]p3:  A program that declares main to be inline
3300  //   or static is ill-formed.
3301  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3302  //   shall not appear in a declaration of main.
3303  // static main is not an error under C99, but we should warn about it.
3304  bool isInline = FD->isInlineSpecified();
3305  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3306  if (isInline || isStatic) {
3307    unsigned diagID = diag::warn_unusual_main_decl;
3308    if (isInline || getLangOptions().CPlusPlus)
3309      diagID = diag::err_unusual_main_decl;
3310
3311    int which = isStatic + (isInline << 1) - 1;
3312    Diag(FD->getLocation(), diagID) << which;
3313  }
3314
3315  QualType T = FD->getType();
3316  assert(T->isFunctionType() && "function decl is not of function type");
3317  const FunctionType* FT = T->getAs<FunctionType>();
3318
3319  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3320    // TODO: add a replacement fixit to turn the return type into 'int'.
3321    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3322    FD->setInvalidDecl(true);
3323  }
3324
3325  // Treat protoless main() as nullary.
3326  if (isa<FunctionNoProtoType>(FT)) return;
3327
3328  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3329  unsigned nparams = FTP->getNumArgs();
3330  assert(FD->getNumParams() == nparams);
3331
3332  if (nparams > 3) {
3333    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3334    FD->setInvalidDecl(true);
3335    nparams = 3;
3336  }
3337
3338  // FIXME: a lot of the following diagnostics would be improved
3339  // if we had some location information about types.
3340
3341  QualType CharPP =
3342    Context.getPointerType(Context.getPointerType(Context.CharTy));
3343  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
3344
3345  for (unsigned i = 0; i < nparams; ++i) {
3346    QualType AT = FTP->getArgType(i);
3347
3348    bool mismatch = true;
3349
3350    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3351      mismatch = false;
3352    else if (Expected[i] == CharPP) {
3353      // As an extension, the following forms are okay:
3354      //   char const **
3355      //   char const * const *
3356      //   char * const *
3357
3358      QualifierCollector qs;
3359      const PointerType* PT;
3360      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3361          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3362          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3363        qs.removeConst();
3364        mismatch = !qs.empty();
3365      }
3366    }
3367
3368    if (mismatch) {
3369      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3370      // TODO: suggest replacing given type with expected type
3371      FD->setInvalidDecl(true);
3372    }
3373  }
3374
3375  if (nparams == 1 && !FD->isInvalidDecl()) {
3376    Diag(FD->getLocation(), diag::warn_main_one_arg);
3377  }
3378}
3379
3380bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3381  // FIXME: Need strict checking.  In C89, we need to check for
3382  // any assignment, increment, decrement, function-calls, or
3383  // commas outside of a sizeof.  In C99, it's the same list,
3384  // except that the aforementioned are allowed in unevaluated
3385  // expressions.  Everything else falls under the
3386  // "may accept other forms of constant expressions" exception.
3387  // (We never end up here for C++, so the constant expression
3388  // rules there don't matter.)
3389  if (Init->isConstantInitializer(Context))
3390    return false;
3391  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3392    << Init->getSourceRange();
3393  return true;
3394}
3395
3396void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3397  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3398}
3399
3400/// AddInitializerToDecl - Adds the initializer Init to the
3401/// declaration dcl. If DirectInit is true, this is C++ direct
3402/// initialization rather than copy initialization.
3403void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3404  Decl *RealDecl = dcl.getAs<Decl>();
3405  // If there is no declaration, there was an error parsing it.  Just ignore
3406  // the initializer.
3407  if (RealDecl == 0)
3408    return;
3409
3410  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3411    // With declarators parsed the way they are, the parser cannot
3412    // distinguish between a normal initializer and a pure-specifier.
3413    // Thus this grotesque test.
3414    IntegerLiteral *IL;
3415    Expr *Init = static_cast<Expr *>(init.get());
3416    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3417        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
3418      if (Method->isVirtualAsWritten()) {
3419        Method->setPure();
3420
3421        // A class is abstract if at least one function is pure virtual.
3422        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
3423      } else if (!Method->isInvalidDecl()) {
3424        Diag(Method->getLocation(), diag::err_non_virtual_pure)
3425          << Method->getDeclName() << Init->getSourceRange();
3426        Method->setInvalidDecl();
3427      }
3428    } else {
3429      Diag(Method->getLocation(), diag::err_member_function_initialization)
3430        << Method->getDeclName() << Init->getSourceRange();
3431      Method->setInvalidDecl();
3432    }
3433    return;
3434  }
3435
3436  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3437  if (!VDecl) {
3438    if (getLangOptions().CPlusPlus &&
3439        RealDecl->getLexicalDeclContext()->isRecord() &&
3440        isa<NamedDecl>(RealDecl))
3441      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3442        << cast<NamedDecl>(RealDecl)->getDeclName();
3443    else
3444      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3445    RealDecl->setInvalidDecl();
3446    return;
3447  }
3448
3449  // A definition must end up with a complete type, which means it must be
3450  // complete with the restriction that an array type might be completed by the
3451  // initializer; note that later code assumes this restriction.
3452  QualType BaseDeclType = VDecl->getType();
3453  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3454    BaseDeclType = Array->getElementType();
3455  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3456                          diag::err_typecheck_decl_incomplete_type)) {
3457    RealDecl->setInvalidDecl();
3458    return;
3459  }
3460
3461  const VarDecl *Def = 0;
3462  if (VDecl->getDefinition(Def)) {
3463    Diag(VDecl->getLocation(), diag::err_redefinition)
3464      << VDecl->getDeclName();
3465    Diag(Def->getLocation(), diag::note_previous_definition);
3466    VDecl->setInvalidDecl();
3467    return;
3468  }
3469
3470  // Take ownership of the expression, now that we're sure we have somewhere
3471  // to put it.
3472  Expr *Init = init.takeAs<Expr>();
3473  assert(Init && "missing initializer");
3474
3475  // Get the decls type and save a reference for later, since
3476  // CheckInitializerTypes may change it.
3477  QualType DclT = VDecl->getType(), SavT = DclT;
3478  if (VDecl->isBlockVarDecl()) {
3479    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3480      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3481      VDecl->setInvalidDecl();
3482    } else if (!VDecl->isInvalidDecl()) {
3483      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3484                                VDecl->getDeclName(), DirectInit))
3485        VDecl->setInvalidDecl();
3486
3487      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3488      // Don't check invalid declarations to avoid emitting useless diagnostics.
3489      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3490        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3491          CheckForConstantInitializer(Init, DclT);
3492      }
3493    }
3494  } else if (VDecl->isStaticDataMember() &&
3495             VDecl->getLexicalDeclContext()->isRecord()) {
3496    // This is an in-class initialization for a static data member, e.g.,
3497    //
3498    // struct S {
3499    //   static const int value = 17;
3500    // };
3501
3502    // Attach the initializer
3503    VDecl->setInit(Context, Init);
3504
3505    // C++ [class.mem]p4:
3506    //   A member-declarator can contain a constant-initializer only
3507    //   if it declares a static member (9.4) of const integral or
3508    //   const enumeration type, see 9.4.2.
3509    QualType T = VDecl->getType();
3510    if (!T->isDependentType() &&
3511        (!Context.getCanonicalType(T).isConstQualified() ||
3512         !T->isIntegralType())) {
3513      Diag(VDecl->getLocation(), diag::err_member_initialization)
3514        << VDecl->getDeclName() << Init->getSourceRange();
3515      VDecl->setInvalidDecl();
3516    } else {
3517      // C++ [class.static.data]p4:
3518      //   If a static data member is of const integral or const
3519      //   enumeration type, its declaration in the class definition
3520      //   can specify a constant-initializer which shall be an
3521      //   integral constant expression (5.19).
3522      if (!Init->isTypeDependent() &&
3523          !Init->getType()->isIntegralType()) {
3524        // We have a non-dependent, non-integral or enumeration type.
3525        Diag(Init->getSourceRange().getBegin(),
3526             diag::err_in_class_initializer_non_integral_type)
3527          << Init->getType() << Init->getSourceRange();
3528        VDecl->setInvalidDecl();
3529      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3530        // Check whether the expression is a constant expression.
3531        llvm::APSInt Value;
3532        SourceLocation Loc;
3533        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3534          Diag(Loc, diag::err_in_class_initializer_non_constant)
3535            << Init->getSourceRange();
3536          VDecl->setInvalidDecl();
3537        } else if (!VDecl->getType()->isDependentType())
3538          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3539      }
3540    }
3541  } else if (VDecl->isFileVarDecl()) {
3542    if (VDecl->getStorageClass() == VarDecl::Extern)
3543      Diag(VDecl->getLocation(), diag::warn_extern_init);
3544    if (!VDecl->isInvalidDecl())
3545      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3546                                VDecl->getDeclName(), DirectInit))
3547        VDecl->setInvalidDecl();
3548
3549    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3550    // Don't check invalid declarations to avoid emitting useless diagnostics.
3551    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3552      // C99 6.7.8p4. All file scoped initializers need to be constant.
3553      CheckForConstantInitializer(Init, DclT);
3554    }
3555  }
3556  // If the type changed, it means we had an incomplete type that was
3557  // completed by the initializer. For example:
3558  //   int ary[] = { 1, 3, 5 };
3559  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3560  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3561    VDecl->setType(DclT);
3562    Init->setType(DclT);
3563  }
3564
3565  Init = MaybeCreateCXXExprWithTemporaries(Init,
3566                                           /*ShouldDestroyTemporaries=*/true);
3567  // Attach the initializer to the decl.
3568  VDecl->setInit(Context, Init);
3569
3570  // If the previous declaration of VDecl was a tentative definition,
3571  // remove it from the set of tentative definitions.
3572  if (VDecl->getPreviousDeclaration() &&
3573      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3574    bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3575    assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
3576  }
3577
3578  return;
3579}
3580
3581void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3582                                  bool TypeContainsUndeducedAuto) {
3583  Decl *RealDecl = dcl.getAs<Decl>();
3584
3585  // If there is no declaration, there was an error parsing it. Just ignore it.
3586  if (RealDecl == 0)
3587    return;
3588
3589  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3590    QualType Type = Var->getType();
3591
3592    // Record tentative definitions.
3593    if (Var->isTentativeDefinition(Context)) {
3594      std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
3595        InsertPair =
3596           TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
3597
3598      // Keep the latest definition in the map.  If we see 'int i; int i;' we
3599      // want the second one in the map.
3600      InsertPair.first->second = Var;
3601
3602      // However, for the list, we don't care about the order, just make sure
3603      // that there are no dupes for a given declaration name.
3604      if (InsertPair.second)
3605        TentativeDefinitionList.push_back(Var->getDeclName());
3606    }
3607
3608    // C++ [dcl.init.ref]p3:
3609    //   The initializer can be omitted for a reference only in a
3610    //   parameter declaration (8.3.5), in the declaration of a
3611    //   function return type, in the declaration of a class member
3612    //   within its class declaration (9.2), and where the extern
3613    //   specifier is explicitly used.
3614    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3615      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3616        << Var->getDeclName()
3617        << SourceRange(Var->getLocation(), Var->getLocation());
3618      Var->setInvalidDecl();
3619      return;
3620    }
3621
3622    // C++0x [dcl.spec.auto]p3
3623    if (TypeContainsUndeducedAuto) {
3624      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3625        << Var->getDeclName() << Type;
3626      Var->setInvalidDecl();
3627      return;
3628    }
3629
3630    // An array without size is an incomplete type, and there are no special
3631    // rules in C++ to make such a definition acceptable.
3632    if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3633        !Var->hasExternalStorage()) {
3634      Diag(Var->getLocation(),
3635           diag::err_typecheck_incomplete_array_needs_initializer);
3636      Var->setInvalidDecl();
3637      return;
3638    }
3639
3640    // C++ [temp.expl.spec]p15:
3641    //   An explicit specialization of a static data member of a template is a
3642    //   definition if the declaration includes an initializer; otherwise, it
3643    //   is a declaration.
3644    if (Var->isStaticDataMember() &&
3645        Var->getInstantiatedFromStaticDataMember() &&
3646        Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3647      return;
3648
3649    // C++ [dcl.init]p9:
3650    //   If no initializer is specified for an object, and the object
3651    //   is of (possibly cv-qualified) non-POD class type (or array
3652    //   thereof), the object shall be default-initialized; if the
3653    //   object is of const-qualified type, the underlying class type
3654    //   shall have a user-declared default constructor.
3655    //
3656    // FIXME: Diagnose the "user-declared default constructor" bit.
3657    if (getLangOptions().CPlusPlus) {
3658      QualType InitType = Type;
3659      if (const ArrayType *Array = Context.getAsArrayType(Type))
3660        InitType = Context.getBaseElementType(Array);
3661      if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
3662          InitType->isRecordType() && !InitType->isDependentType()) {
3663        if (!RequireCompleteType(Var->getLocation(), InitType,
3664                                 diag::err_invalid_incomplete_type_use)) {
3665          ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3666
3667          CXXConstructorDecl *Constructor
3668            = PerformInitializationByConstructor(InitType,
3669                                                 MultiExprArg(*this, 0, 0),
3670                                                 Var->getLocation(),
3671                                               SourceRange(Var->getLocation(),
3672                                                           Var->getLocation()),
3673                                                 Var->getDeclName(),
3674                                                 IK_Default,
3675                                                 ConstructorArgs);
3676
3677          // FIXME: Location info for the variable initialization?
3678          if (!Constructor)
3679            Var->setInvalidDecl();
3680          else {
3681            // FIXME: Cope with initialization of arrays
3682            if (!Constructor->isTrivial() &&
3683                InitializeVarWithConstructor(Var, Constructor,
3684                                             move_arg(ConstructorArgs)))
3685              Var->setInvalidDecl();
3686
3687            FinalizeVarWithDestructor(Var, InitType);
3688          }
3689        } else {
3690          Var->setInvalidDecl();
3691        }
3692      }
3693    }
3694
3695#if 0
3696    // FIXME: Temporarily disabled because we are not properly parsing
3697    // linkage specifications on declarations, e.g.,
3698    //
3699    //   extern "C" const CGPoint CGPointerZero;
3700    //
3701    // C++ [dcl.init]p9:
3702    //
3703    //     If no initializer is specified for an object, and the
3704    //     object is of (possibly cv-qualified) non-POD class type (or
3705    //     array thereof), the object shall be default-initialized; if
3706    //     the object is of const-qualified type, the underlying class
3707    //     type shall have a user-declared default
3708    //     constructor. Otherwise, if no initializer is specified for
3709    //     an object, the object and its subobjects, if any, have an
3710    //     indeterminate initial value; if the object or any of its
3711    //     subobjects are of const-qualified type, the program is
3712    //     ill-formed.
3713    //
3714    // This isn't technically an error in C, so we don't diagnose it.
3715    //
3716    // FIXME: Actually perform the POD/user-defined default
3717    // constructor check.
3718    if (getLangOptions().CPlusPlus &&
3719        Context.getCanonicalType(Type).isConstQualified() &&
3720        !Var->hasExternalStorage())
3721      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3722        << Var->getName()
3723        << SourceRange(Var->getLocation(), Var->getLocation());
3724#endif
3725  }
3726}
3727
3728Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3729                                                   DeclPtrTy *Group,
3730                                                   unsigned NumDecls) {
3731  llvm::SmallVector<Decl*, 8> Decls;
3732
3733  if (DS.isTypeSpecOwned())
3734    Decls.push_back((Decl*)DS.getTypeRep());
3735
3736  for (unsigned i = 0; i != NumDecls; ++i)
3737    if (Decl *D = Group[i].getAs<Decl>())
3738      Decls.push_back(D);
3739
3740  // Perform semantic analysis that depends on having fully processed both
3741  // the declarator and initializer.
3742  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3743    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3744    if (!IDecl)
3745      continue;
3746    QualType T = IDecl->getType();
3747
3748    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3749    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3750    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3751      if (T->isDependentType()) {
3752        // If T is dependent, we should not require a complete type.
3753        // (RequireCompleteType shouldn't be called with dependent types.)
3754        // But we still can at least check if we've got an array of unspecified
3755        // size without an initializer.
3756        if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3757            !IDecl->getInit()) {
3758          Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3759            << T;
3760          IDecl->setInvalidDecl();
3761        }
3762      } else if (!IDecl->isInvalidDecl()) {
3763        // If T is an incomplete array type with an initializer list that is
3764        // dependent on something, its size has not been fixed. We could attempt
3765        // to fix the size for such arrays, but we would still have to check
3766        // here for initializers containing a C++0x vararg expansion, e.g.
3767        // template <typename... Args> void f(Args... args) {
3768        //   int vals[] = { args };
3769        // }
3770        const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
3771        Expr *Init = IDecl->getInit();
3772        if (IAT && Init &&
3773            (Init->isTypeDependent() || Init->isValueDependent())) {
3774          // Check that the member type of the array is complete, at least.
3775          if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3776                                  diag::err_typecheck_decl_incomplete_type))
3777            IDecl->setInvalidDecl();
3778        } else if (RequireCompleteType(IDecl->getLocation(), T,
3779                                      diag::err_typecheck_decl_incomplete_type))
3780          IDecl->setInvalidDecl();
3781      }
3782    }
3783    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3784    // object that has file scope without an initializer, and without a
3785    // storage-class specifier or with the storage-class specifier "static",
3786    // constitutes a tentative definition. Note: A tentative definition with
3787    // external linkage is valid (C99 6.2.2p5).
3788    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3789      if (const IncompleteArrayType *ArrayT
3790          = Context.getAsIncompleteArrayType(T)) {
3791        if (RequireCompleteType(IDecl->getLocation(),
3792                                ArrayT->getElementType(),
3793                                diag::err_illegal_decl_array_incomplete_type))
3794          IDecl->setInvalidDecl();
3795      } else if (IDecl->getStorageClass() == VarDecl::Static) {
3796        // C99 6.9.2p3: If the declaration of an identifier for an object is
3797        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3798        // declared type shall not be an incomplete type.
3799        // NOTE: code such as the following
3800        //     static struct s;
3801        //     struct s { int a; };
3802        // is accepted by gcc. Hence here we issue a warning instead of
3803        // an error and we do not invalidate the static declaration.
3804        // NOTE: to avoid multiple warnings, only check the first declaration.
3805        if (IDecl->getPreviousDeclaration() == 0)
3806          RequireCompleteType(IDecl->getLocation(), T,
3807                              diag::ext_typecheck_decl_incomplete_type);
3808      }
3809    }
3810  }
3811  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3812                                                   Decls.data(), Decls.size()));
3813}
3814
3815
3816/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3817/// to introduce parameters into function prototype scope.
3818Sema::DeclPtrTy
3819Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3820  const DeclSpec &DS = D.getDeclSpec();
3821
3822  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3823  VarDecl::StorageClass StorageClass = VarDecl::None;
3824  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3825    StorageClass = VarDecl::Register;
3826  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3827    Diag(DS.getStorageClassSpecLoc(),
3828         diag::err_invalid_storage_class_in_func_decl);
3829    D.getMutableDeclSpec().ClearStorageClassSpecs();
3830  }
3831
3832  if (D.getDeclSpec().isThreadSpecified())
3833    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3834
3835  DiagnoseFunctionSpecifiers(D);
3836
3837  // Check that there are no default arguments inside the type of this
3838  // parameter (C++ only).
3839  if (getLangOptions().CPlusPlus)
3840    CheckExtraCXXDefaultArguments(D);
3841
3842  DeclaratorInfo *DInfo = 0;
3843  TagDecl *OwnedDecl = 0;
3844  QualType parmDeclType = GetTypeForDeclarator(D, S, &DInfo, &OwnedDecl);
3845
3846  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3847    // C++ [dcl.fct]p6:
3848    //   Types shall not be defined in return or parameter types.
3849    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3850      << Context.getTypeDeclType(OwnedDecl);
3851  }
3852
3853  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3854  // Can this happen for params?  We already checked that they don't conflict
3855  // among each other.  Here they can only shadow globals, which is ok.
3856  IdentifierInfo *II = D.getIdentifier();
3857  if (II) {
3858    if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3859      if (PrevDecl->isTemplateParameter()) {
3860        // Maybe we will complain about the shadowed template parameter.
3861        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3862        // Just pretend that we didn't see the previous declaration.
3863        PrevDecl = 0;
3864      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3865        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3866
3867        // Recover by removing the name
3868        II = 0;
3869        D.SetIdentifier(0, D.getIdentifierLoc());
3870      }
3871    }
3872  }
3873
3874  // Parameters can not be abstract class types.
3875  // For record types, this is done by the AbstractClassUsageDiagnoser once
3876  // the class has been completely parsed.
3877  if (!CurContext->isRecord() &&
3878      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3879                             diag::err_abstract_type_in_decl,
3880                             AbstractParamType))
3881    D.setInvalidType(true);
3882
3883  QualType T = adjustParameterType(parmDeclType);
3884
3885  ParmVarDecl *New
3886    = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
3887                          T, DInfo, StorageClass, 0);
3888
3889  if (D.isInvalidType())
3890    New->setInvalidDecl();
3891
3892  // Parameter declarators cannot be interface types. All ObjC objects are
3893  // passed by reference.
3894  if (T->isObjCInterfaceType()) {
3895    Diag(D.getIdentifierLoc(),
3896         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3897    New->setInvalidDecl();
3898  }
3899
3900  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3901  if (D.getCXXScopeSpec().isSet()) {
3902    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3903      << D.getCXXScopeSpec().getRange();
3904    New->setInvalidDecl();
3905  }
3906
3907  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3908  // duration shall not be qualified by an address-space qualifier."
3909  // Since all parameters have automatic store duration, they can not have
3910  // an address space.
3911  if (T.getAddressSpace() != 0) {
3912    Diag(D.getIdentifierLoc(),
3913         diag::err_arg_with_address_space);
3914    New->setInvalidDecl();
3915  }
3916
3917
3918  // Add the parameter declaration into this scope.
3919  S->AddDecl(DeclPtrTy::make(New));
3920  if (II)
3921    IdResolver.AddDecl(New);
3922
3923  ProcessDeclAttributes(S, New, D);
3924
3925  if (New->hasAttr<BlocksAttr>()) {
3926    Diag(New->getLocation(), diag::err_block_on_nonlocal);
3927  }
3928  return DeclPtrTy::make(New);
3929}
3930
3931void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3932                                           SourceLocation LocAfterDecls) {
3933  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3934         "Not a function declarator!");
3935  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3936
3937  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3938  // for a K&R function.
3939  if (!FTI.hasPrototype) {
3940    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3941      --i;
3942      if (FTI.ArgInfo[i].Param == 0) {
3943        llvm::SmallString<256> Code;
3944        llvm::raw_svector_ostream(Code) << "  int "
3945                                        << FTI.ArgInfo[i].Ident->getName()
3946                                        << ";\n";
3947        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3948          << FTI.ArgInfo[i].Ident
3949          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
3950
3951        // Implicitly declare the argument as type 'int' for lack of a better
3952        // type.
3953        DeclSpec DS;
3954        const char* PrevSpec; // unused
3955        unsigned DiagID; // unused
3956        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3957                           PrevSpec, DiagID);
3958        Declarator ParamD(DS, Declarator::KNRTypeListContext);
3959        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3960        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3961      }
3962    }
3963  }
3964}
3965
3966Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3967                                              Declarator &D) {
3968  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3969  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3970         "Not a function declarator!");
3971  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3972
3973  if (FTI.hasPrototype) {
3974    // FIXME: Diagnose arguments without names in C.
3975  }
3976
3977  Scope *ParentScope = FnBodyScope->getParent();
3978
3979  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3980                                  MultiTemplateParamsArg(*this),
3981                                  /*IsFunctionDefinition=*/true);
3982  return ActOnStartOfFunctionDef(FnBodyScope, DP);
3983}
3984
3985Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
3986  // Clear the last template instantiation error context.
3987  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
3988
3989  if (!D)
3990    return D;
3991  FunctionDecl *FD = 0;
3992
3993  if (FunctionTemplateDecl *FunTmpl
3994        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
3995    FD = FunTmpl->getTemplatedDecl();
3996  else
3997    FD = cast<FunctionDecl>(D.getAs<Decl>());
3998
3999  CurFunctionNeedsScopeChecking = false;
4000
4001  // See if this is a redefinition.
4002  const FunctionDecl *Definition;
4003  if (FD->getBody(Definition)) {
4004    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4005    Diag(Definition->getLocation(), diag::note_previous_definition);
4006  }
4007
4008  // Builtin functions cannot be defined.
4009  if (unsigned BuiltinID = FD->getBuiltinID()) {
4010    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4011      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4012      FD->setInvalidDecl();
4013    }
4014  }
4015
4016  // The return type of a function definition must be complete
4017  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4018  QualType ResultType = FD->getResultType();
4019  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4020      !FD->isInvalidDecl() &&
4021      RequireCompleteType(FD->getLocation(), ResultType,
4022                          diag::err_func_def_incomplete_result))
4023    FD->setInvalidDecl();
4024
4025  // GNU warning -Wmissing-prototypes:
4026  //   Warn if a global function is defined without a previous
4027  //   prototype declaration. This warning is issued even if the
4028  //   definition itself provides a prototype. The aim is to detect
4029  //   global functions that fail to be declared in header files.
4030  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
4031      !FD->isMain()) {
4032    bool MissingPrototype = true;
4033    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4034         Prev; Prev = Prev->getPreviousDeclaration()) {
4035      // Ignore any declarations that occur in function or method
4036      // scope, because they aren't visible from the header.
4037      if (Prev->getDeclContext()->isFunctionOrMethod())
4038        continue;
4039
4040      MissingPrototype = !Prev->getType()->isFunctionProtoType();
4041      break;
4042    }
4043
4044    if (MissingPrototype)
4045      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4046  }
4047
4048  if (FnBodyScope)
4049    PushDeclContext(FnBodyScope, FD);
4050
4051  // Check the validity of our function parameters
4052  CheckParmsForFunctionDef(FD);
4053
4054  // Introduce our parameters into the function scope
4055  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4056    ParmVarDecl *Param = FD->getParamDecl(p);
4057    Param->setOwningFunction(FD);
4058
4059    // If this has an identifier, add it to the scope stack.
4060    if (Param->getIdentifier() && FnBodyScope)
4061      PushOnScopeChains(Param, FnBodyScope);
4062  }
4063
4064  // Checking attributes of current function definition
4065  // dllimport attribute.
4066  if (FD->getAttr<DLLImportAttr>() &&
4067      (!FD->getAttr<DLLExportAttr>())) {
4068    // dllimport attribute cannot be applied to definition.
4069    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4070      Diag(FD->getLocation(),
4071           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4072        << "dllimport";
4073      FD->setInvalidDecl();
4074      return DeclPtrTy::make(FD);
4075    } else {
4076      // If a symbol previously declared dllimport is later defined, the
4077      // attribute is ignored in subsequent references, and a warning is
4078      // emitted.
4079      Diag(FD->getLocation(),
4080           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4081        << FD->getNameAsCString() << "dllimport";
4082    }
4083  }
4084  return DeclPtrTy::make(FD);
4085}
4086
4087Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4088  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4089}
4090
4091Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4092                                              bool IsInstantiation) {
4093  Decl *dcl = D.getAs<Decl>();
4094  Stmt *Body = BodyArg.takeAs<Stmt>();
4095
4096  FunctionDecl *FD = 0;
4097  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4098  if (FunTmpl)
4099    FD = FunTmpl->getTemplatedDecl();
4100  else
4101    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4102
4103  if (FD) {
4104    FD->setBody(Body);
4105    if (FD->isMain())
4106      // C and C++ allow for main to automagically return 0.
4107      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4108      FD->setHasImplicitReturnZero(true);
4109    else
4110      CheckFallThroughForFunctionDef(FD, Body);
4111
4112    if (!FD->isInvalidDecl())
4113      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4114
4115    // C++ [basic.def.odr]p2:
4116    //   [...] A virtual member function is used if it is not pure. [...]
4117    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4118      if (Method->isVirtual() && !Method->isPure())
4119        MarkDeclarationReferenced(Method->getLocation(), Method);
4120
4121    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4122  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4123    assert(MD == getCurMethodDecl() && "Method parsing confused");
4124    MD->setBody(Body);
4125    CheckFallThroughForFunctionDef(MD, Body);
4126    MD->setEndLoc(Body->getLocEnd());
4127
4128    if (!MD->isInvalidDecl())
4129      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4130  } else {
4131    Body->Destroy(Context);
4132    return DeclPtrTy();
4133  }
4134  if (!IsInstantiation)
4135    PopDeclContext();
4136
4137  // Verify and clean out per-function state.
4138
4139  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4140
4141  // Check goto/label use.
4142  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4143       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4144    LabelStmt *L = I->second;
4145
4146    // Verify that we have no forward references left.  If so, there was a goto
4147    // or address of a label taken, but no definition of it.  Label fwd
4148    // definitions are indicated with a null substmt.
4149    if (L->getSubStmt() != 0)
4150      continue;
4151
4152    // Emit error.
4153    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4154
4155    // At this point, we have gotos that use the bogus label.  Stitch it into
4156    // the function body so that they aren't leaked and that the AST is well
4157    // formed.
4158    if (Body == 0) {
4159      // The whole function wasn't parsed correctly, just delete this.
4160      L->Destroy(Context);
4161      continue;
4162    }
4163
4164    // Otherwise, the body is valid: we want to stitch the label decl into the
4165    // function somewhere so that it is properly owned and so that the goto
4166    // has a valid target.  Do this by creating a new compound stmt with the
4167    // label in it.
4168
4169    // Give the label a sub-statement.
4170    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4171
4172    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4173                               cast<CXXTryStmt>(Body)->getTryBlock() :
4174                               cast<CompoundStmt>(Body);
4175    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4176    Elements.push_back(L);
4177    Compound->setStmts(Context, &Elements[0], Elements.size());
4178  }
4179  FunctionLabelMap.clear();
4180
4181  if (!Body) return D;
4182
4183  // Verify that that gotos and switch cases don't jump into scopes illegally.
4184  if (CurFunctionNeedsScopeChecking)
4185    DiagnoseInvalidJumps(Body);
4186
4187  // C++ constructors that have function-try-blocks can't have return
4188  // statements in the handlers of that block. (C++ [except.handle]p14)
4189  // Verify this.
4190  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4191    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4192
4193  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4194    MarkBaseAndMemberDestructorsReferenced(Destructor);
4195
4196  // If any errors have occurred, clear out any temporaries that may have
4197  // been leftover. This ensures that these temporaries won't be picked up for
4198  // deletion in some later function.
4199  if (PP.getDiagnostics().hasErrorOccurred())
4200    ExprTemporaries.clear();
4201
4202  assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4203  return D;
4204}
4205
4206/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4207/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4208NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4209                                          IdentifierInfo &II, Scope *S) {
4210  // Before we produce a declaration for an implicitly defined
4211  // function, see whether there was a locally-scoped declaration of
4212  // this name as a function or variable. If so, use that
4213  // (non-visible) declaration, and complain about it.
4214  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4215    = LocallyScopedExternalDecls.find(&II);
4216  if (Pos != LocallyScopedExternalDecls.end()) {
4217    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4218    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4219    return Pos->second;
4220  }
4221
4222  // Extension in C99.  Legal in C90, but warn about it.
4223  if (II.getName().startswith("__builtin_"))
4224    Diag(Loc, diag::warn_builtin_unknown) << &II;
4225  else if (getLangOptions().C99)
4226    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4227  else
4228    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4229
4230  // Set a Declarator for the implicit definition: int foo();
4231  const char *Dummy;
4232  DeclSpec DS;
4233  unsigned DiagID;
4234  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4235  Error = Error; // Silence warning.
4236  assert(!Error && "Error setting up implicit decl!");
4237  Declarator D(DS, Declarator::BlockContext);
4238  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4239                                             0, 0, false, SourceLocation(),
4240                                             false, 0,0,0, Loc, Loc, D),
4241                SourceLocation());
4242  D.SetIdentifier(&II, Loc);
4243
4244  // Insert this function into translation-unit scope.
4245
4246  DeclContext *PrevDC = CurContext;
4247  CurContext = Context.getTranslationUnitDecl();
4248
4249  FunctionDecl *FD =
4250 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4251  FD->setImplicit();
4252
4253  CurContext = PrevDC;
4254
4255  AddKnownFunctionAttributes(FD);
4256
4257  return FD;
4258}
4259
4260/// \brief Adds any function attributes that we know a priori based on
4261/// the declaration of this function.
4262///
4263/// These attributes can apply both to implicitly-declared builtins
4264/// (like __builtin___printf_chk) or to library-declared functions
4265/// like NSLog or printf.
4266void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4267  if (FD->isInvalidDecl())
4268    return;
4269
4270  // If this is a built-in function, map its builtin attributes to
4271  // actual attributes.
4272  if (unsigned BuiltinID = FD->getBuiltinID()) {
4273    // Handle printf-formatting attributes.
4274    unsigned FormatIdx;
4275    bool HasVAListArg;
4276    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4277      if (!FD->getAttr<FormatAttr>())
4278        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4279                                             HasVAListArg ? 0 : FormatIdx + 2));
4280    }
4281
4282    // Mark const if we don't care about errno and that is the only
4283    // thing preventing the function from being const. This allows
4284    // IRgen to use LLVM intrinsics for such functions.
4285    if (!getLangOptions().MathErrno &&
4286        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4287      if (!FD->getAttr<ConstAttr>())
4288        FD->addAttr(::new (Context) ConstAttr());
4289    }
4290
4291    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4292      FD->addAttr(::new (Context) NoReturnAttr());
4293  }
4294
4295  IdentifierInfo *Name = FD->getIdentifier();
4296  if (!Name)
4297    return;
4298  if ((!getLangOptions().CPlusPlus &&
4299       FD->getDeclContext()->isTranslationUnit()) ||
4300      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4301       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4302       LinkageSpecDecl::lang_c)) {
4303    // Okay: this could be a libc/libm/Objective-C function we know
4304    // about.
4305  } else
4306    return;
4307
4308  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4309    // FIXME: NSLog and NSLogv should be target specific
4310    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4311      // FIXME: We known better than our headers.
4312      const_cast<FormatAttr *>(Format)->setType("printf");
4313    } else
4314      FD->addAttr(::new (Context) FormatAttr("printf", 1,
4315                                             Name->isStr("NSLogv") ? 0 : 2));
4316  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4317    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4318    // target-specific builtins, perhaps?
4319    if (!FD->getAttr<FormatAttr>())
4320      FD->addAttr(::new (Context) FormatAttr("printf", 2,
4321                                             Name->isStr("vasprintf") ? 0 : 3));
4322  }
4323}
4324
4325TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4326                                    DeclaratorInfo *DInfo) {
4327  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4328  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4329
4330  if (!DInfo) {
4331    assert(D.isInvalidType() && "no declarator info for valid type");
4332    DInfo = Context.getTrivialDeclaratorInfo(T);
4333  }
4334
4335  // Scope manipulation handled by caller.
4336  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4337                                           D.getIdentifierLoc(),
4338                                           D.getIdentifier(),
4339                                           DInfo);
4340
4341  if (const TagType *TT = T->getAs<TagType>()) {
4342    TagDecl *TD = TT->getDecl();
4343
4344    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4345    // keep track of the TypedefDecl.
4346    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4347      TD->setTypedefForAnonDecl(NewTD);
4348  }
4349
4350  if (D.isInvalidType())
4351    NewTD->setInvalidDecl();
4352  return NewTD;
4353}
4354
4355
4356/// \brief Determine whether a tag with a given kind is acceptable
4357/// as a redeclaration of the given tag declaration.
4358///
4359/// \returns true if the new tag kind is acceptable, false otherwise.
4360bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4361                                        TagDecl::TagKind NewTag,
4362                                        SourceLocation NewTagLoc,
4363                                        const IdentifierInfo &Name) {
4364  // C++ [dcl.type.elab]p3:
4365  //   The class-key or enum keyword present in the
4366  //   elaborated-type-specifier shall agree in kind with the
4367  //   declaration to which the name in theelaborated-type-specifier
4368  //   refers. This rule also applies to the form of
4369  //   elaborated-type-specifier that declares a class-name or
4370  //   friend class since it can be construed as referring to the
4371  //   definition of the class. Thus, in any
4372  //   elaborated-type-specifier, the enum keyword shall be used to
4373  //   refer to an enumeration (7.2), the union class-keyshall be
4374  //   used to refer to a union (clause 9), and either the class or
4375  //   struct class-key shall be used to refer to a class (clause 9)
4376  //   declared using the class or struct class-key.
4377  TagDecl::TagKind OldTag = Previous->getTagKind();
4378  if (OldTag == NewTag)
4379    return true;
4380
4381  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4382      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4383    // Warn about the struct/class tag mismatch.
4384    bool isTemplate = false;
4385    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4386      isTemplate = Record->getDescribedClassTemplate();
4387
4388    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4389      << (NewTag == TagDecl::TK_class)
4390      << isTemplate << &Name
4391      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4392                              OldTag == TagDecl::TK_class? "class" : "struct");
4393    Diag(Previous->getLocation(), diag::note_previous_use);
4394    return true;
4395  }
4396  return false;
4397}
4398
4399/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4400/// former case, Name will be non-null.  In the later case, Name will be null.
4401/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4402/// reference/declaration/definition of a tag.
4403Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4404                               SourceLocation KWLoc, const CXXScopeSpec &SS,
4405                               IdentifierInfo *Name, SourceLocation NameLoc,
4406                               AttributeList *Attr, AccessSpecifier AS,
4407                               MultiTemplateParamsArg TemplateParameterLists,
4408                               bool &OwnedDecl, bool &IsDependent) {
4409  // If this is not a definition, it must have a name.
4410  assert((Name != 0 || TUK == TUK_Definition) &&
4411         "Nameless record must be a definition!");
4412
4413  OwnedDecl = false;
4414  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4415
4416  // FIXME: Check explicit specializations more carefully.
4417  bool isExplicitSpecialization = false;
4418  if (TUK != TUK_Reference) {
4419    if (TemplateParameterList *TemplateParams
4420          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4421                        (TemplateParameterList**)TemplateParameterLists.get(),
4422                                              TemplateParameterLists.size(),
4423                                                    isExplicitSpecialization)) {
4424      if (TemplateParams->size() > 0) {
4425        // This is a declaration or definition of a class template (which may
4426        // be a member of another template).
4427        OwnedDecl = false;
4428        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4429                                               SS, Name, NameLoc, Attr,
4430                                               TemplateParams,
4431                                               AS);
4432        TemplateParameterLists.release();
4433        return Result.get();
4434      } else {
4435        // The "template<>" header is extraneous.
4436        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4437          << ElaboratedType::getNameForTagKind(Kind) << Name;
4438        isExplicitSpecialization = true;
4439      }
4440    }
4441
4442    TemplateParameterLists.release();
4443  }
4444
4445  DeclContext *SearchDC = CurContext;
4446  DeclContext *DC = CurContext;
4447  bool isStdBadAlloc = false;
4448  bool Invalid = false;
4449
4450  RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4451                                                   : NotForRedeclaration);
4452
4453  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4454
4455  if (Name && SS.isNotEmpty()) {
4456    // We have a nested-name tag ('struct foo::bar').
4457
4458    // Check for invalid 'foo::'.
4459    if (SS.isInvalid()) {
4460      Name = 0;
4461      goto CreateNewDecl;
4462    }
4463
4464    // If this is a friend or a reference to a class in a dependent
4465    // context, don't try to make a decl for it.
4466    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4467      DC = computeDeclContext(SS, false);
4468      if (!DC) {
4469        IsDependent = true;
4470        return DeclPtrTy();
4471      }
4472    }
4473
4474    if (RequireCompleteDeclContext(SS))
4475      return DeclPtrTy::make((Decl *)0);
4476
4477    DC = computeDeclContext(SS, true);
4478    SearchDC = DC;
4479    // Look-up name inside 'foo::'.
4480    LookupQualifiedName(Previous, DC);
4481
4482    if (Previous.isAmbiguous())
4483      return DeclPtrTy();
4484
4485    // A tag 'foo::bar' must already exist.
4486    if (Previous.empty()) {
4487      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4488      Name = 0;
4489      Invalid = true;
4490      goto CreateNewDecl;
4491    }
4492  } else if (Name) {
4493    // If this is a named struct, check to see if there was a previous forward
4494    // declaration or definition.
4495    // FIXME: We're looking into outer scopes here, even when we
4496    // shouldn't be. Doing so can result in ambiguities that we
4497    // shouldn't be diagnosing.
4498    LookupName(Previous, S);
4499
4500    // Note:  there used to be some attempt at recovery here.
4501    if (Previous.isAmbiguous())
4502      return DeclPtrTy();
4503
4504    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4505      // FIXME: This makes sure that we ignore the contexts associated
4506      // with C structs, unions, and enums when looking for a matching
4507      // tag declaration or definition. See the similar lookup tweak
4508      // in Sema::LookupName; is there a better way to deal with this?
4509      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4510        SearchDC = SearchDC->getParent();
4511    }
4512  }
4513
4514  if (Previous.isSingleResult() &&
4515      Previous.getFoundDecl()->isTemplateParameter()) {
4516    // Maybe we will complain about the shadowed template parameter.
4517    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4518    // Just pretend that we didn't see the previous declaration.
4519    Previous.clear();
4520  }
4521
4522  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4523      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4524    // This is a declaration of or a reference to "std::bad_alloc".
4525    isStdBadAlloc = true;
4526
4527    if (Previous.empty() && StdBadAlloc) {
4528      // std::bad_alloc has been implicitly declared (but made invisible to
4529      // name lookup). Fill in this implicit declaration as the previous
4530      // declaration, so that the declarations get chained appropriately.
4531      Previous.addDecl(StdBadAlloc);
4532    }
4533  }
4534
4535  if (!Previous.empty()) {
4536    assert(Previous.isSingleResult());
4537    NamedDecl *PrevDecl = Previous.getFoundDecl();
4538    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4539      // If this is a use of a previous tag, or if the tag is already declared
4540      // in the same scope (so that the definition/declaration completes or
4541      // rementions the tag), reuse the decl.
4542      if (TUK == TUK_Reference || TUK == TUK_Friend ||
4543          isDeclInScope(PrevDecl, SearchDC, S)) {
4544        // Make sure that this wasn't declared as an enum and now used as a
4545        // struct or something similar.
4546        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4547          bool SafeToContinue
4548            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4549               Kind != TagDecl::TK_enum);
4550          if (SafeToContinue)
4551            Diag(KWLoc, diag::err_use_with_wrong_tag)
4552              << Name
4553              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4554                                                  PrevTagDecl->getKindName());
4555          else
4556            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4557          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4558
4559          if (SafeToContinue)
4560            Kind = PrevTagDecl->getTagKind();
4561          else {
4562            // Recover by making this an anonymous redefinition.
4563            Name = 0;
4564            Previous.clear();
4565            Invalid = true;
4566          }
4567        }
4568
4569        if (!Invalid) {
4570          // If this is a use, just return the declaration we found.
4571
4572          // FIXME: In the future, return a variant or some other clue
4573          // for the consumer of this Decl to know it doesn't own it.
4574          // For our current ASTs this shouldn't be a problem, but will
4575          // need to be changed with DeclGroups.
4576          if (TUK == TUK_Reference || TUK == TUK_Friend)
4577            return DeclPtrTy::make(PrevTagDecl);
4578
4579          // Diagnose attempts to redefine a tag.
4580          if (TUK == TUK_Definition) {
4581            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4582              // If we're defining a specialization and the previous definition
4583              // is from an implicit instantiation, don't emit an error
4584              // here; we'll catch this in the general case below.
4585              if (!isExplicitSpecialization ||
4586                  !isa<CXXRecordDecl>(Def) ||
4587                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4588                                               == TSK_ExplicitSpecialization) {
4589                Diag(NameLoc, diag::err_redefinition) << Name;
4590                Diag(Def->getLocation(), diag::note_previous_definition);
4591                // If this is a redefinition, recover by making this
4592                // struct be anonymous, which will make any later
4593                // references get the previous definition.
4594                Name = 0;
4595                Previous.clear();
4596                Invalid = true;
4597              }
4598            } else {
4599              // If the type is currently being defined, complain
4600              // about a nested redefinition.
4601              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4602              if (Tag->isBeingDefined()) {
4603                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4604                Diag(PrevTagDecl->getLocation(),
4605                     diag::note_previous_definition);
4606                Name = 0;
4607                Previous.clear();
4608                Invalid = true;
4609              }
4610            }
4611
4612            // Okay, this is definition of a previously declared or referenced
4613            // tag PrevDecl. We're going to create a new Decl for it.
4614          }
4615        }
4616        // If we get here we have (another) forward declaration or we
4617        // have a definition.  Just create a new decl.
4618
4619      } else {
4620        // If we get here, this is a definition of a new tag type in a nested
4621        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4622        // new decl/type.  We set PrevDecl to NULL so that the entities
4623        // have distinct types.
4624        Previous.clear();
4625      }
4626      // If we get here, we're going to create a new Decl. If PrevDecl
4627      // is non-NULL, it's a definition of the tag declared by
4628      // PrevDecl. If it's NULL, we have a new definition.
4629    } else {
4630      // PrevDecl is a namespace, template, or anything else
4631      // that lives in the IDNS_Tag identifier namespace.
4632      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4633        // The tag name clashes with a namespace name, issue an error and
4634        // recover by making this tag be anonymous.
4635        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4636        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4637        Name = 0;
4638        Previous.clear();
4639        Invalid = true;
4640      } else {
4641        // The existing declaration isn't relevant to us; we're in a
4642        // new scope, so clear out the previous declaration.
4643        Previous.clear();
4644      }
4645    }
4646  } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
4647             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
4648    // C++ [basic.scope.pdecl]p5:
4649    //   -- for an elaborated-type-specifier of the form
4650    //
4651    //          class-key identifier
4652    //
4653    //      if the elaborated-type-specifier is used in the
4654    //      decl-specifier-seq or parameter-declaration-clause of a
4655    //      function defined in namespace scope, the identifier is
4656    //      declared as a class-name in the namespace that contains
4657    //      the declaration; otherwise, except as a friend
4658    //      declaration, the identifier is declared in the smallest
4659    //      non-class, non-function-prototype scope that contains the
4660    //      declaration.
4661    //
4662    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4663    // C structs and unions.
4664    //
4665    // GNU C also supports this behavior as part of its incomplete
4666    // enum types extension, while GNU C++ does not.
4667    //
4668    // Find the context where we'll be declaring the tag.
4669    // FIXME: We would like to maintain the current DeclContext as the
4670    // lexical context,
4671    while (SearchDC->isRecord())
4672      SearchDC = SearchDC->getParent();
4673
4674    // Find the scope where we'll be declaring the tag.
4675    while (S->isClassScope() ||
4676           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4677           ((S->getFlags() & Scope::DeclScope) == 0) ||
4678           (S->getEntity() &&
4679            ((DeclContext *)S->getEntity())->isTransparentContext()))
4680      S = S->getParent();
4681
4682  } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4683    // C++ [namespace.memdef]p3:
4684    //   If a friend declaration in a non-local class first declares a
4685    //   class or function, the friend class or function is a member of
4686    //   the innermost enclosing namespace.
4687    while (!SearchDC->isFileContext())
4688      SearchDC = SearchDC->getParent();
4689
4690    // The entity of a decl scope is a DeclContext; see PushDeclContext.
4691    while (S->getEntity() != SearchDC)
4692      S = S->getParent();
4693  }
4694
4695CreateNewDecl:
4696
4697  TagDecl *PrevDecl = 0;
4698  if (Previous.isSingleResult())
4699    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4700
4701  // If there is an identifier, use the location of the identifier as the
4702  // location of the decl, otherwise use the location of the struct/union
4703  // keyword.
4704  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4705
4706  // Otherwise, create a new declaration. If there is a previous
4707  // declaration of the same entity, the two will be linked via
4708  // PrevDecl.
4709  TagDecl *New;
4710
4711  if (Kind == TagDecl::TK_enum) {
4712    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4713    // enum X { A, B, C } D;    D should chain to X.
4714    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4715                           cast_or_null<EnumDecl>(PrevDecl));
4716    // If this is an undefined enum, warn.
4717    if (TUK != TUK_Definition && !Invalid)  {
4718      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4719                                              : diag::ext_forward_ref_enum;
4720      Diag(Loc, DK);
4721    }
4722  } else {
4723    // struct/union/class
4724
4725    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4726    // struct X { int A; } D;    D should chain to X.
4727    if (getLangOptions().CPlusPlus) {
4728      // FIXME: Look for a way to use RecordDecl for simple structs.
4729      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4730                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4731
4732      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4733        StdBadAlloc = cast<CXXRecordDecl>(New);
4734    } else
4735      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4736                               cast_or_null<RecordDecl>(PrevDecl));
4737  }
4738
4739  if (Kind != TagDecl::TK_enum) {
4740    // Handle #pragma pack: if the #pragma pack stack has non-default
4741    // alignment, make up a packed attribute for this decl. These
4742    // attributes are checked when the ASTContext lays out the
4743    // structure.
4744    //
4745    // It is important for implementing the correct semantics that this
4746    // happen here (in act on tag decl). The #pragma pack stack is
4747    // maintained as a result of parser callbacks which can occur at
4748    // many points during the parsing of a struct declaration (because
4749    // the #pragma tokens are effectively skipped over during the
4750    // parsing of the struct).
4751    if (unsigned Alignment = getPragmaPackAlignment())
4752      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4753  }
4754
4755  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4756    // C++ [dcl.typedef]p3:
4757    //   [...] Similarly, in a given scope, a class or enumeration
4758    //   shall not be declared with the same name as a typedef-name
4759    //   that is declared in that scope and refers to a type other
4760    //   than the class or enumeration itself.
4761    LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4762                        ForRedeclaration);
4763    LookupName(Lookup, S);
4764    TypedefDecl *PrevTypedef = 0;
4765    if (NamedDecl *Prev = Lookup.getAsSingleDecl(Context))
4766      PrevTypedef = dyn_cast<TypedefDecl>(Prev);
4767
4768    NamedDecl *PrevTypedefNamed = PrevTypedef;
4769    if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4770        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4771          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4772      Diag(Loc, diag::err_tag_definition_of_typedef)
4773        << Context.getTypeDeclType(New)
4774        << PrevTypedef->getUnderlyingType();
4775      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4776      Invalid = true;
4777    }
4778  }
4779
4780  // If this is a specialization of a member class (of a class template),
4781  // check the specialization.
4782  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4783    Invalid = true;
4784
4785  if (Invalid)
4786    New->setInvalidDecl();
4787
4788  if (Attr)
4789    ProcessDeclAttributeList(S, New, Attr);
4790
4791  // If we're declaring or defining a tag in function prototype scope
4792  // in C, note that this type can only be used within the function.
4793  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4794    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4795
4796  // Set the lexical context. If the tag has a C++ scope specifier, the
4797  // lexical context will be different from the semantic context.
4798  New->setLexicalDeclContext(CurContext);
4799
4800  // Mark this as a friend decl if applicable.
4801  if (TUK == TUK_Friend)
4802    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4803
4804  // Set the access specifier.
4805  if (!Invalid && TUK != TUK_Friend)
4806    SetMemberAccessSpecifier(New, PrevDecl, AS);
4807
4808  if (TUK == TUK_Definition)
4809    New->startDefinition();
4810
4811  // If this has an identifier, add it to the scope stack.
4812  if (TUK == TUK_Friend) {
4813    // We might be replacing an existing declaration in the lookup tables;
4814    // if so, borrow its access specifier.
4815    if (PrevDecl)
4816      New->setAccess(PrevDecl->getAccess());
4817
4818    // Friend tag decls are visible in fairly strange ways.
4819    if (!CurContext->isDependentContext()) {
4820      DeclContext *DC = New->getDeclContext()->getLookupContext();
4821      DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4822      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4823        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4824    }
4825  } else if (Name) {
4826    S = getNonFieldDeclScope(S);
4827    PushOnScopeChains(New, S);
4828  } else {
4829    CurContext->addDecl(New);
4830  }
4831
4832  // If this is the C FILE type, notify the AST context.
4833  if (IdentifierInfo *II = New->getIdentifier())
4834    if (!New->isInvalidDecl() &&
4835        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4836        II->isStr("FILE"))
4837      Context.setFILEDecl(New);
4838
4839  OwnedDecl = true;
4840  return DeclPtrTy::make(New);
4841}
4842
4843void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4844  AdjustDeclIfTemplate(TagD);
4845  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4846
4847  // Enter the tag context.
4848  PushDeclContext(S, Tag);
4849
4850  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4851    FieldCollector->StartClass();
4852
4853    if (Record->getIdentifier()) {
4854      // C++ [class]p2:
4855      //   [...] The class-name is also inserted into the scope of the
4856      //   class itself; this is known as the injected-class-name. For
4857      //   purposes of access checking, the injected-class-name is treated
4858      //   as if it were a public member name.
4859      CXXRecordDecl *InjectedClassName
4860        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4861                                CurContext, Record->getLocation(),
4862                                Record->getIdentifier(),
4863                                Record->getTagKeywordLoc(),
4864                                Record);
4865      InjectedClassName->setImplicit();
4866      InjectedClassName->setAccess(AS_public);
4867      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4868        InjectedClassName->setDescribedClassTemplate(Template);
4869      PushOnScopeChains(InjectedClassName, S);
4870      assert(InjectedClassName->isInjectedClassName() &&
4871             "Broken injected-class-name");
4872    }
4873  }
4874}
4875
4876void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4877                                    SourceLocation RBraceLoc) {
4878  AdjustDeclIfTemplate(TagD);
4879  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4880  Tag->setRBraceLoc(RBraceLoc);
4881
4882  if (isa<CXXRecordDecl>(Tag))
4883    FieldCollector->FinishClass();
4884
4885  // Exit this scope of this tag's definition.
4886  PopDeclContext();
4887
4888  // Notify the consumer that we've defined a tag.
4889  Consumer.HandleTagDeclDefinition(Tag);
4890}
4891
4892// Note that FieldName may be null for anonymous bitfields.
4893bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4894                          QualType FieldTy, const Expr *BitWidth,
4895                          bool *ZeroWidth) {
4896  // Default to true; that shouldn't confuse checks for emptiness
4897  if (ZeroWidth)
4898    *ZeroWidth = true;
4899
4900  // C99 6.7.2.1p4 - verify the field type.
4901  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4902  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4903    // Handle incomplete types with specific error.
4904    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4905      return true;
4906    if (FieldName)
4907      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4908        << FieldName << FieldTy << BitWidth->getSourceRange();
4909    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4910      << FieldTy << BitWidth->getSourceRange();
4911  }
4912
4913  // If the bit-width is type- or value-dependent, don't try to check
4914  // it now.
4915  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4916    return false;
4917
4918  llvm::APSInt Value;
4919  if (VerifyIntegerConstantExpression(BitWidth, &Value))
4920    return true;
4921
4922  if (Value != 0 && ZeroWidth)
4923    *ZeroWidth = false;
4924
4925  // Zero-width bitfield is ok for anonymous field.
4926  if (Value == 0 && FieldName)
4927    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
4928
4929  if (Value.isSigned() && Value.isNegative()) {
4930    if (FieldName)
4931      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
4932               << FieldName << Value.toString(10);
4933    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4934      << Value.toString(10);
4935  }
4936
4937  if (!FieldTy->isDependentType()) {
4938    uint64_t TypeSize = Context.getTypeSize(FieldTy);
4939    if (Value.getZExtValue() > TypeSize) {
4940      if (FieldName)
4941        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4942          << FieldName << (unsigned)TypeSize;
4943      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4944        << (unsigned)TypeSize;
4945    }
4946  }
4947
4948  return false;
4949}
4950
4951/// ActOnField - Each field of a struct/union/class is passed into this in order
4952/// to create a FieldDecl object for it.
4953Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
4954                                 SourceLocation DeclStart,
4955                                 Declarator &D, ExprTy *BitfieldWidth) {
4956  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4957                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4958                               AS_public);
4959  return DeclPtrTy::make(Res);
4960}
4961
4962/// HandleField - Analyze a field of a C struct or a C++ data member.
4963///
4964FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4965                             SourceLocation DeclStart,
4966                             Declarator &D, Expr *BitWidth,
4967                             AccessSpecifier AS) {
4968  IdentifierInfo *II = D.getIdentifier();
4969  SourceLocation Loc = DeclStart;
4970  if (II) Loc = D.getIdentifierLoc();
4971
4972  DeclaratorInfo *DInfo = 0;
4973  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4974  if (getLangOptions().CPlusPlus)
4975    CheckExtraCXXDefaultArguments(D);
4976
4977  DiagnoseFunctionSpecifiers(D);
4978
4979  if (D.getDeclSpec().isThreadSpecified())
4980    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4981
4982  NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
4983                                         ForRedeclaration);
4984
4985  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4986    // Maybe we will complain about the shadowed template parameter.
4987    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4988    // Just pretend that we didn't see the previous declaration.
4989    PrevDecl = 0;
4990  }
4991
4992  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
4993    PrevDecl = 0;
4994
4995  bool Mutable
4996    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
4997  SourceLocation TSSL = D.getSourceRange().getBegin();
4998  FieldDecl *NewFD
4999    = CheckFieldDecl(II, T, DInfo, Record, Loc, Mutable, BitWidth, TSSL,
5000                     AS, PrevDecl, &D);
5001  if (NewFD->isInvalidDecl() && PrevDecl) {
5002    // Don't introduce NewFD into scope; there's already something
5003    // with the same name in the same scope.
5004  } else if (II) {
5005    PushOnScopeChains(NewFD, S);
5006  } else
5007    Record->addDecl(NewFD);
5008
5009  return NewFD;
5010}
5011
5012/// \brief Build a new FieldDecl and check its well-formedness.
5013///
5014/// This routine builds a new FieldDecl given the fields name, type,
5015/// record, etc. \p PrevDecl should refer to any previous declaration
5016/// with the same name and in the same scope as the field to be
5017/// created.
5018///
5019/// \returns a new FieldDecl.
5020///
5021/// \todo The Declarator argument is a hack. It will be removed once
5022FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5023                                DeclaratorInfo *DInfo,
5024                                RecordDecl *Record, SourceLocation Loc,
5025                                bool Mutable, Expr *BitWidth,
5026                                SourceLocation TSSL,
5027                                AccessSpecifier AS, NamedDecl *PrevDecl,
5028                                Declarator *D) {
5029  IdentifierInfo *II = Name.getAsIdentifierInfo();
5030  bool InvalidDecl = false;
5031  if (D) InvalidDecl = D->isInvalidType();
5032
5033  // If we receive a broken type, recover by assuming 'int' and
5034  // marking this declaration as invalid.
5035  if (T.isNull()) {
5036    InvalidDecl = true;
5037    T = Context.IntTy;
5038  }
5039
5040  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5041  // than a variably modified type.
5042  if (T->isVariablyModifiedType()) {
5043    bool SizeIsNegative;
5044    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5045                                                           SizeIsNegative);
5046    if (!FixedTy.isNull()) {
5047      Diag(Loc, diag::warn_illegal_constant_array_size);
5048      T = FixedTy;
5049    } else {
5050      if (SizeIsNegative)
5051        Diag(Loc, diag::err_typecheck_negative_array_size);
5052      else
5053        Diag(Loc, diag::err_typecheck_field_variable_size);
5054      InvalidDecl = true;
5055    }
5056  }
5057
5058  // Fields can not have abstract class types
5059  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
5060                             AbstractFieldType))
5061    InvalidDecl = true;
5062
5063  bool ZeroWidth = false;
5064  // If this is declared as a bit-field, check the bit-field.
5065  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5066    InvalidDecl = true;
5067    DeleteExpr(BitWidth);
5068    BitWidth = 0;
5069    ZeroWidth = false;
5070  }
5071
5072  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, DInfo,
5073                                       BitWidth, Mutable);
5074  if (InvalidDecl)
5075    NewFD->setInvalidDecl();
5076
5077  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5078    Diag(Loc, diag::err_duplicate_member) << II;
5079    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5080    NewFD->setInvalidDecl();
5081  }
5082
5083  if (getLangOptions().CPlusPlus) {
5084    QualType EltTy = Context.getBaseElementType(T);
5085
5086    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5087
5088    if (!T->isPODType())
5089      CXXRecord->setPOD(false);
5090    if (!ZeroWidth)
5091      CXXRecord->setEmpty(false);
5092
5093    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5094      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5095
5096      if (!RDecl->hasTrivialConstructor())
5097        CXXRecord->setHasTrivialConstructor(false);
5098      if (!RDecl->hasTrivialCopyConstructor())
5099        CXXRecord->setHasTrivialCopyConstructor(false);
5100      if (!RDecl->hasTrivialCopyAssignment())
5101        CXXRecord->setHasTrivialCopyAssignment(false);
5102      if (!RDecl->hasTrivialDestructor())
5103        CXXRecord->setHasTrivialDestructor(false);
5104
5105      // C++ 9.5p1: An object of a class with a non-trivial
5106      // constructor, a non-trivial copy constructor, a non-trivial
5107      // destructor, or a non-trivial copy assignment operator
5108      // cannot be a member of a union, nor can an array of such
5109      // objects.
5110      // TODO: C++0x alters this restriction significantly.
5111      if (Record->isUnion()) {
5112        // We check for copy constructors before constructors
5113        // because otherwise we'll never get complaints about
5114        // copy constructors.
5115
5116        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5117
5118        CXXSpecialMember member;
5119        if (!RDecl->hasTrivialCopyConstructor())
5120          member = CXXCopyConstructor;
5121        else if (!RDecl->hasTrivialConstructor())
5122          member = CXXDefaultConstructor;
5123        else if (!RDecl->hasTrivialCopyAssignment())
5124          member = CXXCopyAssignment;
5125        else if (!RDecl->hasTrivialDestructor())
5126          member = CXXDestructor;
5127        else
5128          member = invalid;
5129
5130        if (member != invalid) {
5131          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5132          DiagnoseNontrivial(RT, member);
5133          NewFD->setInvalidDecl();
5134        }
5135      }
5136    }
5137  }
5138
5139  // FIXME: We need to pass in the attributes given an AST
5140  // representation, not a parser representation.
5141  if (D)
5142    // FIXME: What to pass instead of TUScope?
5143    ProcessDeclAttributes(TUScope, NewFD, *D);
5144
5145  if (T.isObjCGCWeak())
5146    Diag(Loc, diag::warn_attribute_weak_on_field);
5147
5148  NewFD->setAccess(AS);
5149
5150  // C++ [dcl.init.aggr]p1:
5151  //   An aggregate is an array or a class (clause 9) with [...] no
5152  //   private or protected non-static data members (clause 11).
5153  // A POD must be an aggregate.
5154  if (getLangOptions().CPlusPlus &&
5155      (AS == AS_private || AS == AS_protected)) {
5156    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5157    CXXRecord->setAggregate(false);
5158    CXXRecord->setPOD(false);
5159  }
5160
5161  return NewFD;
5162}
5163
5164/// DiagnoseNontrivial - Given that a class has a non-trivial
5165/// special member, figure out why.
5166void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5167  QualType QT(T, 0U);
5168  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5169
5170  // Check whether the member was user-declared.
5171  switch (member) {
5172  case CXXDefaultConstructor:
5173    if (RD->hasUserDeclaredConstructor()) {
5174      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5175      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5176        const FunctionDecl *body = 0;
5177        ci->getBody(body);
5178        if (!body ||
5179            !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5180          SourceLocation CtorLoc = ci->getLocation();
5181          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5182          return;
5183        }
5184      }
5185
5186      assert(0 && "found no user-declared constructors");
5187      return;
5188    }
5189    break;
5190
5191  case CXXCopyConstructor:
5192    if (RD->hasUserDeclaredCopyConstructor()) {
5193      SourceLocation CtorLoc =
5194        RD->getCopyConstructor(Context, 0)->getLocation();
5195      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5196      return;
5197    }
5198    break;
5199
5200  case CXXCopyAssignment:
5201    if (RD->hasUserDeclaredCopyAssignment()) {
5202      // FIXME: this should use the location of the copy
5203      // assignment, not the type.
5204      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5205      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5206      return;
5207    }
5208    break;
5209
5210  case CXXDestructor:
5211    if (RD->hasUserDeclaredDestructor()) {
5212      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5213      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5214      return;
5215    }
5216    break;
5217  }
5218
5219  typedef CXXRecordDecl::base_class_iterator base_iter;
5220
5221  // Virtual bases and members inhibit trivial copying/construction,
5222  // but not trivial destruction.
5223  if (member != CXXDestructor) {
5224    // Check for virtual bases.  vbases includes indirect virtual bases,
5225    // so we just iterate through the direct bases.
5226    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5227      if (bi->isVirtual()) {
5228        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5229        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5230        return;
5231      }
5232
5233    // Check for virtual methods.
5234    typedef CXXRecordDecl::method_iterator meth_iter;
5235    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5236         ++mi) {
5237      if (mi->isVirtual()) {
5238        SourceLocation MLoc = mi->getSourceRange().getBegin();
5239        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5240        return;
5241      }
5242    }
5243  }
5244
5245  bool (CXXRecordDecl::*hasTrivial)() const;
5246  switch (member) {
5247  case CXXDefaultConstructor:
5248    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5249  case CXXCopyConstructor:
5250    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5251  case CXXCopyAssignment:
5252    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5253  case CXXDestructor:
5254    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5255  default:
5256    assert(0 && "unexpected special member"); return;
5257  }
5258
5259  // Check for nontrivial bases (and recurse).
5260  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5261    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5262    assert(BaseRT && "Don't know how to handle dependent bases");
5263    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5264    if (!(BaseRecTy->*hasTrivial)()) {
5265      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5266      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5267      DiagnoseNontrivial(BaseRT, member);
5268      return;
5269    }
5270  }
5271
5272  // Check for nontrivial members (and recurse).
5273  typedef RecordDecl::field_iterator field_iter;
5274  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5275       ++fi) {
5276    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5277    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5278      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5279
5280      if (!(EltRD->*hasTrivial)()) {
5281        SourceLocation FLoc = (*fi)->getLocation();
5282        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5283        DiagnoseNontrivial(EltRT, member);
5284        return;
5285      }
5286    }
5287  }
5288
5289  assert(0 && "found no explanation for non-trivial member");
5290}
5291
5292/// TranslateIvarVisibility - Translate visibility from a token ID to an
5293///  AST enum value.
5294static ObjCIvarDecl::AccessControl
5295TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5296  switch (ivarVisibility) {
5297  default: assert(0 && "Unknown visitibility kind");
5298  case tok::objc_private: return ObjCIvarDecl::Private;
5299  case tok::objc_public: return ObjCIvarDecl::Public;
5300  case tok::objc_protected: return ObjCIvarDecl::Protected;
5301  case tok::objc_package: return ObjCIvarDecl::Package;
5302  }
5303}
5304
5305/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5306/// in order to create an IvarDecl object for it.
5307Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5308                                SourceLocation DeclStart,
5309                                DeclPtrTy IntfDecl,
5310                                Declarator &D, ExprTy *BitfieldWidth,
5311                                tok::ObjCKeywordKind Visibility) {
5312
5313  IdentifierInfo *II = D.getIdentifier();
5314  Expr *BitWidth = (Expr*)BitfieldWidth;
5315  SourceLocation Loc = DeclStart;
5316  if (II) Loc = D.getIdentifierLoc();
5317
5318  // FIXME: Unnamed fields can be handled in various different ways, for
5319  // example, unnamed unions inject all members into the struct namespace!
5320
5321  DeclaratorInfo *DInfo = 0;
5322  QualType T = GetTypeForDeclarator(D, S, &DInfo);
5323
5324  if (BitWidth) {
5325    // 6.7.2.1p3, 6.7.2.1p4
5326    if (VerifyBitField(Loc, II, T, BitWidth)) {
5327      D.setInvalidType();
5328      DeleteExpr(BitWidth);
5329      BitWidth = 0;
5330    }
5331  } else {
5332    // Not a bitfield.
5333
5334    // validate II.
5335
5336  }
5337
5338  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5339  // than a variably modified type.
5340  if (T->isVariablyModifiedType()) {
5341    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5342    D.setInvalidType();
5343  }
5344
5345  // Get the visibility (access control) for this ivar.
5346  ObjCIvarDecl::AccessControl ac =
5347    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5348                                        : ObjCIvarDecl::None;
5349  // Must set ivar's DeclContext to its enclosing interface.
5350  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5351  DeclContext *EnclosingContext;
5352  if (ObjCImplementationDecl *IMPDecl =
5353      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5354    // Case of ivar declared in an implementation. Context is that of its class.
5355    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5356    assert(IDecl && "No class- ActOnIvar");
5357    EnclosingContext = cast_or_null<DeclContext>(IDecl);
5358  } else
5359    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5360  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5361
5362  // Construct the decl.
5363  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5364                                             EnclosingContext, Loc, II, T,
5365                                             DInfo, ac, (Expr *)BitfieldWidth);
5366
5367  if (II) {
5368    NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5369                                           ForRedeclaration);
5370    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5371        && !isa<TagDecl>(PrevDecl)) {
5372      Diag(Loc, diag::err_duplicate_member) << II;
5373      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5374      NewID->setInvalidDecl();
5375    }
5376  }
5377
5378  // Process attributes attached to the ivar.
5379  ProcessDeclAttributes(S, NewID, D);
5380
5381  if (D.isInvalidType())
5382    NewID->setInvalidDecl();
5383
5384  if (II) {
5385    // FIXME: When interfaces are DeclContexts, we'll need to add
5386    // these to the interface.
5387    S->AddDecl(DeclPtrTy::make(NewID));
5388    IdResolver.AddDecl(NewID);
5389  }
5390
5391  return DeclPtrTy::make(NewID);
5392}
5393
5394void Sema::ActOnFields(Scope* S,
5395                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5396                       DeclPtrTy *Fields, unsigned NumFields,
5397                       SourceLocation LBrac, SourceLocation RBrac,
5398                       AttributeList *Attr) {
5399  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5400  assert(EnclosingDecl && "missing record or interface decl");
5401
5402  // If the decl this is being inserted into is invalid, then it may be a
5403  // redeclaration or some other bogus case.  Don't try to add fields to it.
5404  if (EnclosingDecl->isInvalidDecl()) {
5405    // FIXME: Deallocate fields?
5406    return;
5407  }
5408
5409
5410  // Verify that all the fields are okay.
5411  unsigned NumNamedMembers = 0;
5412  llvm::SmallVector<FieldDecl*, 32> RecFields;
5413
5414  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5415  for (unsigned i = 0; i != NumFields; ++i) {
5416    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5417
5418    // Get the type for the field.
5419    Type *FDTy = FD->getType().getTypePtr();
5420
5421    if (!FD->isAnonymousStructOrUnion()) {
5422      // Remember all fields written by the user.
5423      RecFields.push_back(FD);
5424    }
5425
5426    // If the field is already invalid for some reason, don't emit more
5427    // diagnostics about it.
5428    if (FD->isInvalidDecl())
5429      continue;
5430
5431    // C99 6.7.2.1p2:
5432    //   A structure or union shall not contain a member with
5433    //   incomplete or function type (hence, a structure shall not
5434    //   contain an instance of itself, but may contain a pointer to
5435    //   an instance of itself), except that the last member of a
5436    //   structure with more than one named member may have incomplete
5437    //   array type; such a structure (and any union containing,
5438    //   possibly recursively, a member that is such a structure)
5439    //   shall not be a member of a structure or an element of an
5440    //   array.
5441    if (FDTy->isFunctionType()) {
5442      // Field declared as a function.
5443      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5444        << FD->getDeclName();
5445      FD->setInvalidDecl();
5446      EnclosingDecl->setInvalidDecl();
5447      continue;
5448    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5449               Record && Record->isStruct()) {
5450      // Flexible array member.
5451      if (NumNamedMembers < 1) {
5452        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5453          << FD->getDeclName();
5454        FD->setInvalidDecl();
5455        EnclosingDecl->setInvalidDecl();
5456        continue;
5457      }
5458      // Okay, we have a legal flexible array member at the end of the struct.
5459      if (Record)
5460        Record->setHasFlexibleArrayMember(true);
5461    } else if (!FDTy->isDependentType() &&
5462               RequireCompleteType(FD->getLocation(), FD->getType(),
5463                                   diag::err_field_incomplete)) {
5464      // Incomplete type
5465      FD->setInvalidDecl();
5466      EnclosingDecl->setInvalidDecl();
5467      continue;
5468    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5469      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5470        // If this is a member of a union, then entire union becomes "flexible".
5471        if (Record && Record->isUnion()) {
5472          Record->setHasFlexibleArrayMember(true);
5473        } else {
5474          // If this is a struct/class and this is not the last element, reject
5475          // it.  Note that GCC supports variable sized arrays in the middle of
5476          // structures.
5477          if (i != NumFields-1)
5478            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5479              << FD->getDeclName() << FD->getType();
5480          else {
5481            // We support flexible arrays at the end of structs in
5482            // other structs as an extension.
5483            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5484              << FD->getDeclName();
5485            if (Record)
5486              Record->setHasFlexibleArrayMember(true);
5487          }
5488        }
5489      }
5490      if (Record && FDTTy->getDecl()->hasObjectMember())
5491        Record->setHasObjectMember(true);
5492    } else if (FDTy->isObjCInterfaceType()) {
5493      /// A field cannot be an Objective-c object
5494      Diag(FD->getLocation(), diag::err_statically_allocated_object);
5495      FD->setInvalidDecl();
5496      EnclosingDecl->setInvalidDecl();
5497      continue;
5498    } else if (getLangOptions().ObjC1 &&
5499               getLangOptions().getGCMode() != LangOptions::NonGC &&
5500               Record &&
5501               (FD->getType()->isObjCObjectPointerType() ||
5502                FD->getType().isObjCGCStrong()))
5503      Record->setHasObjectMember(true);
5504    // Keep track of the number of named members.
5505    if (FD->getIdentifier())
5506      ++NumNamedMembers;
5507  }
5508
5509  // Okay, we successfully defined 'Record'.
5510  if (Record) {
5511    Record->completeDefinition(Context);
5512  } else {
5513    ObjCIvarDecl **ClsFields =
5514      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5515    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5516      ID->setIVarList(ClsFields, RecFields.size(), Context);
5517      ID->setLocEnd(RBrac);
5518      // Add ivar's to class's DeclContext.
5519      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5520        ClsFields[i]->setLexicalDeclContext(ID);
5521        ID->addDecl(ClsFields[i]);
5522      }
5523      // Must enforce the rule that ivars in the base classes may not be
5524      // duplicates.
5525      if (ID->getSuperClass()) {
5526        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5527             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5528          ObjCIvarDecl* Ivar = (*IVI);
5529
5530          if (IdentifierInfo *II = Ivar->getIdentifier()) {
5531            ObjCIvarDecl* prevIvar =
5532              ID->getSuperClass()->lookupInstanceVariable(II);
5533            if (prevIvar) {
5534              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5535              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5536            }
5537          }
5538        }
5539      }
5540    } else if (ObjCImplementationDecl *IMPDecl =
5541                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5542      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5543      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5544        // Ivar declared in @implementation never belongs to the implementation.
5545        // Only it is in implementation's lexical context.
5546        ClsFields[I]->setLexicalDeclContext(IMPDecl);
5547      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5548    }
5549  }
5550
5551  if (Attr)
5552    ProcessDeclAttributeList(S, Record, Attr);
5553}
5554
5555EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5556                                          EnumConstantDecl *LastEnumConst,
5557                                          SourceLocation IdLoc,
5558                                          IdentifierInfo *Id,
5559                                          ExprArg val) {
5560  Expr *Val = (Expr *)val.get();
5561
5562  llvm::APSInt EnumVal(32);
5563  QualType EltTy;
5564  if (Val) {
5565    if (Val->isTypeDependent())
5566      EltTy = Context.DependentTy;
5567    else {
5568      // Make sure to promote the operand type to int.
5569      UsualUnaryConversions(Val);
5570      if (Val != val.get()) {
5571        val.release();
5572        val = Val;
5573      }
5574
5575      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5576      SourceLocation ExpLoc;
5577      if (!Val->isValueDependent() &&
5578          VerifyIntegerConstantExpression(Val, &EnumVal)) {
5579        Val = 0;
5580      } else {
5581        EltTy = Val->getType();
5582      }
5583    }
5584  }
5585
5586  if (!Val) {
5587    if (LastEnumConst) {
5588      // Assign the last value + 1.
5589      EnumVal = LastEnumConst->getInitVal();
5590      ++EnumVal;
5591
5592      // Check for overflow on increment.
5593      if (EnumVal < LastEnumConst->getInitVal())
5594        Diag(IdLoc, diag::warn_enum_value_overflow);
5595
5596      EltTy = LastEnumConst->getType();
5597    } else {
5598      // First value, set to zero.
5599      EltTy = Context.IntTy;
5600      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5601    }
5602  }
5603
5604  assert(!EltTy.isNull() && "Enum constant with NULL type");
5605
5606  val.release();
5607  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5608                                  Val, EnumVal);
5609}
5610
5611
5612Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5613                                        DeclPtrTy lastEnumConst,
5614                                        SourceLocation IdLoc,
5615                                        IdentifierInfo *Id,
5616                                        SourceLocation EqualLoc, ExprTy *val) {
5617  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5618  EnumConstantDecl *LastEnumConst =
5619    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5620  Expr *Val = static_cast<Expr*>(val);
5621
5622  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5623  // we find one that is.
5624  S = getNonFieldDeclScope(S);
5625
5626  // Verify that there isn't already something declared with this name in this
5627  // scope.
5628  NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
5629  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5630    // Maybe we will complain about the shadowed template parameter.
5631    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5632    // Just pretend that we didn't see the previous declaration.
5633    PrevDecl = 0;
5634  }
5635
5636  if (PrevDecl) {
5637    // When in C++, we may get a TagDecl with the same name; in this case the
5638    // enum constant will 'hide' the tag.
5639    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5640           "Received TagDecl when not in C++!");
5641    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5642      if (isa<EnumConstantDecl>(PrevDecl))
5643        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5644      else
5645        Diag(IdLoc, diag::err_redefinition) << Id;
5646      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5647      if (Val) Val->Destroy(Context);
5648      return DeclPtrTy();
5649    }
5650  }
5651
5652  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5653                                            IdLoc, Id, Owned(Val));
5654
5655  // Register this decl in the current scope stack.
5656  if (New)
5657    PushOnScopeChains(New, S);
5658
5659  return DeclPtrTy::make(New);
5660}
5661
5662void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5663                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5664                         DeclPtrTy *Elements, unsigned NumElements,
5665                         Scope *S, AttributeList *Attr) {
5666  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5667  QualType EnumType = Context.getTypeDeclType(Enum);
5668
5669  if (Attr)
5670    ProcessDeclAttributeList(S, Enum, Attr);
5671
5672  // TODO: If the result value doesn't fit in an int, it must be a long or long
5673  // long value.  ISO C does not support this, but GCC does as an extension,
5674  // emit a warning.
5675  unsigned IntWidth = Context.Target.getIntWidth();
5676  unsigned CharWidth = Context.Target.getCharWidth();
5677  unsigned ShortWidth = Context.Target.getShortWidth();
5678
5679  // Verify that all the values are okay, compute the size of the values, and
5680  // reverse the list.
5681  unsigned NumNegativeBits = 0;
5682  unsigned NumPositiveBits = 0;
5683
5684  // Keep track of whether all elements have type int.
5685  bool AllElementsInt = true;
5686
5687  for (unsigned i = 0; i != NumElements; ++i) {
5688    EnumConstantDecl *ECD =
5689      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5690    if (!ECD) continue;  // Already issued a diagnostic.
5691
5692    // If the enum value doesn't fit in an int, emit an extension warning.
5693    const llvm::APSInt &InitVal = ECD->getInitVal();
5694    assert(InitVal.getBitWidth() >= IntWidth &&
5695           "Should have promoted value to int");
5696    if (InitVal.getBitWidth() > IntWidth) {
5697      llvm::APSInt V(InitVal);
5698      V.trunc(IntWidth);
5699      V.extend(InitVal.getBitWidth());
5700      if (V != InitVal)
5701        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5702          << InitVal.toString(10);
5703    }
5704
5705    // Keep track of the size of positive and negative values.
5706    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5707      NumPositiveBits = std::max(NumPositiveBits,
5708                                 (unsigned)InitVal.getActiveBits());
5709    else
5710      NumNegativeBits = std::max(NumNegativeBits,
5711                                 (unsigned)InitVal.getMinSignedBits());
5712
5713    // Keep track of whether every enum element has type int (very commmon).
5714    if (AllElementsInt)
5715      AllElementsInt = ECD->getType() == Context.IntTy;
5716  }
5717
5718  // Figure out the type that should be used for this enum.
5719  // FIXME: Support -fshort-enums.
5720  QualType BestType;
5721  unsigned BestWidth;
5722
5723  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5724
5725  if (NumNegativeBits) {
5726    // If there is a negative value, figure out the smallest integer type (of
5727    // int/long/longlong) that fits.
5728    // If it's packed, check also if it fits a char or a short.
5729    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5730        BestType = Context.SignedCharTy;
5731        BestWidth = CharWidth;
5732    } else if (Packed && NumNegativeBits <= ShortWidth &&
5733               NumPositiveBits < ShortWidth) {
5734        BestType = Context.ShortTy;
5735        BestWidth = ShortWidth;
5736    }
5737    else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5738      BestType = Context.IntTy;
5739      BestWidth = IntWidth;
5740    } else {
5741      BestWidth = Context.Target.getLongWidth();
5742
5743      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
5744        BestType = Context.LongTy;
5745      else {
5746        BestWidth = Context.Target.getLongLongWidth();
5747
5748        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5749          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5750        BestType = Context.LongLongTy;
5751      }
5752    }
5753  } else {
5754    // If there is no negative value, figure out which of uint, ulong, ulonglong
5755    // fits.
5756    // If it's packed, check also if it fits a char or a short.
5757    if (Packed && NumPositiveBits <= CharWidth) {
5758        BestType = Context.UnsignedCharTy;
5759        BestWidth = CharWidth;
5760    } else if (Packed && NumPositiveBits <= ShortWidth) {
5761        BestType = Context.UnsignedShortTy;
5762        BestWidth = ShortWidth;
5763    }
5764    else if (NumPositiveBits <= IntWidth) {
5765      BestType = Context.UnsignedIntTy;
5766      BestWidth = IntWidth;
5767    } else if (NumPositiveBits <=
5768               (BestWidth = Context.Target.getLongWidth())) {
5769      BestType = Context.UnsignedLongTy;
5770    } else {
5771      BestWidth = Context.Target.getLongLongWidth();
5772      assert(NumPositiveBits <= BestWidth &&
5773             "How could an initializer get larger than ULL?");
5774      BestType = Context.UnsignedLongLongTy;
5775    }
5776  }
5777
5778  // Loop over all of the enumerator constants, changing their types to match
5779  // the type of the enum if needed.
5780  for (unsigned i = 0; i != NumElements; ++i) {
5781    EnumConstantDecl *ECD =
5782      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5783    if (!ECD) continue;  // Already issued a diagnostic.
5784
5785    // Standard C says the enumerators have int type, but we allow, as an
5786    // extension, the enumerators to be larger than int size.  If each
5787    // enumerator value fits in an int, type it as an int, otherwise type it the
5788    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5789    // that X has type 'int', not 'unsigned'.
5790    if (ECD->getType() == Context.IntTy) {
5791      // Make sure the init value is signed.
5792      llvm::APSInt IV = ECD->getInitVal();
5793      IV.setIsSigned(true);
5794      ECD->setInitVal(IV);
5795
5796      if (getLangOptions().CPlusPlus)
5797        // C++ [dcl.enum]p4: Following the closing brace of an
5798        // enum-specifier, each enumerator has the type of its
5799        // enumeration.
5800        ECD->setType(EnumType);
5801      continue;  // Already int type.
5802    }
5803
5804    // Determine whether the value fits into an int.
5805    llvm::APSInt InitVal = ECD->getInitVal();
5806    bool FitsInInt;
5807    if (InitVal.isUnsigned() || !InitVal.isNegative())
5808      FitsInInt = InitVal.getActiveBits() < IntWidth;
5809    else
5810      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5811
5812    // If it fits into an integer type, force it.  Otherwise force it to match
5813    // the enum decl type.
5814    QualType NewTy;
5815    unsigned NewWidth;
5816    bool NewSign;
5817    if (FitsInInt) {
5818      NewTy = Context.IntTy;
5819      NewWidth = IntWidth;
5820      NewSign = true;
5821    } else if (ECD->getType() == BestType) {
5822      // Already the right type!
5823      if (getLangOptions().CPlusPlus)
5824        // C++ [dcl.enum]p4: Following the closing brace of an
5825        // enum-specifier, each enumerator has the type of its
5826        // enumeration.
5827        ECD->setType(EnumType);
5828      continue;
5829    } else {
5830      NewTy = BestType;
5831      NewWidth = BestWidth;
5832      NewSign = BestType->isSignedIntegerType();
5833    }
5834
5835    // Adjust the APSInt value.
5836    InitVal.extOrTrunc(NewWidth);
5837    InitVal.setIsSigned(NewSign);
5838    ECD->setInitVal(InitVal);
5839
5840    // Adjust the Expr initializer and type.
5841    if (ECD->getInitExpr())
5842      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5843                                                      CastExpr::CK_IntegralCast,
5844                                                      ECD->getInitExpr(),
5845                                                      /*isLvalue=*/false));
5846    if (getLangOptions().CPlusPlus)
5847      // C++ [dcl.enum]p4: Following the closing brace of an
5848      // enum-specifier, each enumerator has the type of its
5849      // enumeration.
5850      ECD->setType(EnumType);
5851    else
5852      ECD->setType(NewTy);
5853  }
5854
5855  Enum->completeDefinition(Context, BestType);
5856}
5857
5858Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5859                                            ExprArg expr) {
5860  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
5861
5862  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5863                                                   Loc, AsmString);
5864  CurContext->addDecl(New);
5865  return DeclPtrTy::make(New);
5866}
5867
5868void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5869                             SourceLocation PragmaLoc,
5870                             SourceLocation NameLoc) {
5871  Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
5872
5873  if (PrevDecl) {
5874    PrevDecl->addAttr(::new (Context) WeakAttr());
5875  } else {
5876    (void)WeakUndeclaredIdentifiers.insert(
5877      std::pair<IdentifierInfo*,WeakInfo>
5878        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
5879  }
5880}
5881
5882void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5883                                IdentifierInfo* AliasName,
5884                                SourceLocation PragmaLoc,
5885                                SourceLocation NameLoc,
5886                                SourceLocation AliasNameLoc) {
5887  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
5888  WeakInfo W = WeakInfo(Name, NameLoc);
5889
5890  if (PrevDecl) {
5891    if (!PrevDecl->hasAttr<AliasAttr>())
5892      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
5893        DeclApplyPragmaWeak(TUScope, ND, W);
5894  } else {
5895    (void)WeakUndeclaredIdentifiers.insert(
5896      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
5897  }
5898}
5899