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