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