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