clang API Documentation

SemaDecl.cpp

Go to the documentation of this file.
00001 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "Lookup.h"
00017 #include "clang/Analysis/AnalysisContext.h"
00018 #include "clang/AST/APValue.h"
00019 #include "clang/AST/ASTConsumer.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/CXXInheritance.h"
00022 #include "clang/AST/DeclTemplate.h"
00023 #include "clang/AST/ExprCXX.h"
00024 #include "clang/AST/StmtCXX.h"
00025 #include "clang/Parse/DeclSpec.h"
00026 #include "clang/Parse/ParseDiagnostic.h"
00027 #include "clang/Parse/Template.h"
00028 #include "clang/Basic/PartialDiagnostic.h"
00029 #include "clang/Basic/SourceManager.h"
00030 #include "clang/Basic/TargetInfo.h"
00031 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
00032 #include "clang/Lex/Preprocessor.h"
00033 #include "clang/Lex/HeaderSearch.h"
00034 #include "llvm/ADT/Triple.h"
00035 #include <algorithm>
00036 #include <cstring>
00037 #include <functional>
00038 using namespace clang;
00039 
00040 /// getDeclName - Return a pretty name for the specified decl if possible, or
00041 /// an empty string if not.  This is used for pretty crash reporting.
00042 std::string Sema::getDeclName(DeclPtrTy d) {
00043   Decl *D = d.getAs<Decl>();
00044   if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
00045     return DN->getQualifiedNameAsString();
00046   return "";
00047 }
00048 
00049 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
00050   return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
00051 }
00052 
00053 /// \brief If the identifier refers to a type name within this scope,
00054 /// return the declaration of that type.
00055 ///
00056 /// This routine performs ordinary name lookup of the identifier II
00057 /// within the given scope, with optional C++ scope specifier SS, to
00058 /// determine whether the name refers to a type. If so, returns an
00059 /// opaque pointer (actually a QualType) corresponding to that
00060 /// type. Otherwise, returns NULL.
00061 ///
00062 /// If name lookup results in an ambiguity, this routine will complain
00063 /// and then return NULL.
00064 Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
00065                                 Scope *S, const CXXScopeSpec *SS,
00066                                 bool isClassName,
00067                                 TypeTy *ObjectTypePtr) {
00068   // Determine where we will perform name lookup.
00069   DeclContext *LookupCtx = 0;
00070   if (ObjectTypePtr) {
00071     QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
00072     if (ObjectType->isRecordType())
00073       LookupCtx = computeDeclContext(ObjectType);
00074   } else if (SS && SS->isSet()) {
00075     LookupCtx = computeDeclContext(*SS, false);
00076 
00077     if (!LookupCtx) {
00078       if (isDependentScopeSpecifier(*SS)) {
00079         // C++ [temp.res]p3:
00080         //   A qualified-id that refers to a type and in which the
00081         //   nested-name-specifier depends on a template-parameter (14.6.2)
00082         //   shall be prefixed by the keyword typename to indicate that the
00083         //   qualified-id denotes a type, forming an
00084         //   elaborated-type-specifier (7.1.5.3).
00085         //
00086         // We therefore do not perform any name lookup if the result would
00087         // refer to a member of an unknown specialization.
00088         if (!isClassName)
00089           return 0;
00090         
00091         // We know from the grammar that this name refers to a type, so build a
00092         // TypenameType node to describe the type.
00093         // FIXME: Record somewhere that this TypenameType node has no "typename"
00094         // keyword associated with it.
00095         return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
00096                                  II, SS->getRange()).getAsOpaquePtr();
00097       }
00098       
00099       return 0;
00100     }
00101     
00102     if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
00103       return 0;
00104   }
00105 
00106   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
00107   // lookup for class-names.
00108   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
00109                                       LookupOrdinaryName;
00110   LookupResult Result(*this, &II, NameLoc, Kind);
00111   if (LookupCtx) {
00112     // Perform "qualified" name lookup into the declaration context we
00113     // computed, which is either the type of the base of a member access
00114     // expression or the declaration context associated with a prior
00115     // nested-name-specifier.
00116     LookupQualifiedName(Result, LookupCtx);
00117 
00118     if (ObjectTypePtr && Result.empty()) {
00119       // C++ [basic.lookup.classref]p3:
00120       //   If the unqualified-id is ~type-name, the type-name is looked up
00121       //   in the context of the entire postfix-expression. If the type T of 
00122       //   the object expression is of a class type C, the type-name is also
00123       //   looked up in the scope of class C. At least one of the lookups shall
00124       //   find a name that refers to (possibly cv-qualified) T.
00125       LookupName(Result, S);
00126     }
00127   } else {
00128     // Perform unqualified name lookup.
00129     LookupName(Result, S);
00130   }
00131   
00132   NamedDecl *IIDecl = 0;
00133   switch (Result.getResultKind()) {
00134   case LookupResult::NotFound:
00135   case LookupResult::NotFoundInCurrentInstantiation:
00136   case LookupResult::FoundOverloaded:
00137   case LookupResult::FoundUnresolvedValue:
00138     Result.suppressDiagnostics();
00139     return 0;
00140 
00141   case LookupResult::Ambiguous:
00142     // Recover from type-hiding ambiguities by hiding the type.  We'll
00143     // do the lookup again when looking for an object, and we can
00144     // diagnose the error then.  If we don't do this, then the error
00145     // about hiding the type will be immediately followed by an error
00146     // that only makes sense if the identifier was treated like a type.
00147     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
00148       Result.suppressDiagnostics();
00149       return 0;
00150     }
00151 
00152     // Look to see if we have a type anywhere in the list of results.
00153     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
00154          Res != ResEnd; ++Res) {
00155       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
00156         if (!IIDecl ||
00157             (*Res)->getLocation().getRawEncoding() <
00158               IIDecl->getLocation().getRawEncoding())
00159           IIDecl = *Res;
00160       }
00161     }
00162 
00163     if (!IIDecl) {
00164       // None of the entities we found is a type, so there is no way
00165       // to even assume that the result is a type. In this case, don't
00166       // complain about the ambiguity. The parser will either try to
00167       // perform this lookup again (e.g., as an object name), which
00168       // will produce the ambiguity, or will complain that it expected
00169       // a type name.
00170       Result.suppressDiagnostics();
00171       return 0;
00172     }
00173 
00174     // We found a type within the ambiguous lookup; diagnose the
00175     // ambiguity and then return that type. This might be the right
00176     // answer, or it might not be, but it suppresses any attempt to
00177     // perform the name lookup again.
00178     break;
00179 
00180   case LookupResult::Found:
00181     IIDecl = Result.getFoundDecl();
00182     break;
00183   }
00184 
00185   assert(IIDecl && "Didn't find decl");
00186 
00187   QualType T;
00188   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
00189     DiagnoseUseOfDecl(IIDecl, NameLoc);
00190 
00191     if (T.isNull())
00192       T = Context.getTypeDeclType(TD);
00193     
00194     if (SS)
00195       T = getQualifiedNameType(*SS, T);
00196     
00197   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
00198     T = Context.getObjCInterfaceType(IDecl);
00199   } else if (UnresolvedUsingTypenameDecl *UUDecl =
00200                dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
00201     // FIXME: preserve source structure information.
00202     T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
00203   } else {
00204     // If it's not plausibly a type, suppress diagnostics.
00205     Result.suppressDiagnostics();
00206     return 0;
00207   }
00208 
00209   return T.getAsOpaquePtr();
00210 }
00211 
00212 /// isTagName() - This method is called *for error recovery purposes only*
00213 /// to determine if the specified name is a valid tag name ("struct foo").  If
00214 /// so, this returns the TST for the tag corresponding to it (TST_enum,
00215 /// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
00216 /// where the user forgot to specify the tag.
00217 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
00218   // Do a tag name lookup in this scope.
00219   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
00220   LookupName(R, S, false);
00221   R.suppressDiagnostics();
00222   if (R.getResultKind() == LookupResult::Found)
00223     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
00224       switch (TD->getTagKind()) {
00225       case TagDecl::TK_struct: return DeclSpec::TST_struct;
00226       case TagDecl::TK_union:  return DeclSpec::TST_union;
00227       case TagDecl::TK_class:  return DeclSpec::TST_class;
00228       case TagDecl::TK_enum:   return DeclSpec::TST_enum;
00229       }
00230     }
00231 
00232   return DeclSpec::TST_unspecified;
00233 }
00234 
00235 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 
00236                                    SourceLocation IILoc,
00237                                    Scope *S,
00238                                    const CXXScopeSpec *SS,
00239                                    TypeTy *&SuggestedType) {
00240   // We don't have anything to suggest (yet).
00241   SuggestedType = 0;
00242   
00243   // There may have been a typo in the name of the type. Look up typo
00244   // results, in case we have something that we can suggest.
00245   LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName, 
00246                       NotForRedeclaration);
00247 
00248   // FIXME: It would be nice if we could correct for typos in built-in
00249   // names, such as "itn" for "int".
00250 
00251   if (CorrectTypo(Lookup, S, SS) && Lookup.isSingleResult()) {
00252     NamedDecl *Result = Lookup.getAsSingle<NamedDecl>();
00253     if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
00254         !Result->isInvalidDecl()) {
00255       // We found a similarly-named type or interface; suggest that.
00256       if (!SS || !SS->isSet())
00257         Diag(IILoc, diag::err_unknown_typename_suggest)
00258           << &II << Lookup.getLookupName()
00259           << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
00260                                                      Result->getNameAsString());
00261       else if (DeclContext *DC = computeDeclContext(*SS, false))
00262         Diag(IILoc, diag::err_unknown_nested_typename_suggest) 
00263           << &II << DC << Lookup.getLookupName() << SS->getRange()
00264           << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
00265                                                      Result->getNameAsString());
00266       else
00267         llvm_unreachable("could not have corrected a typo here");
00268 
00269       Diag(Result->getLocation(), diag::note_previous_decl)
00270         << Result->getDeclName();
00271       
00272       SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
00273       return true;
00274     }
00275   }
00276 
00277   // FIXME: Should we move the logic that tries to recover from a missing tag
00278   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
00279   
00280   if (!SS || (!SS->isSet() && !SS->isInvalid()))
00281     Diag(IILoc, diag::err_unknown_typename) << &II;
00282   else if (DeclContext *DC = computeDeclContext(*SS, false))
00283     Diag(IILoc, diag::err_typename_nested_not_found) 
00284       << &II << DC << SS->getRange();
00285   else if (isDependentScopeSpecifier(*SS)) {
00286     Diag(SS->getRange().getBegin(), diag::err_typename_missing)
00287       << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
00288       << SourceRange(SS->getRange().getBegin(), IILoc)
00289       << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
00290                                                "typename ");
00291     SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
00292   } else {
00293     assert(SS && SS->isInvalid() && 
00294            "Invalid scope specifier has already been diagnosed");
00295   }
00296   
00297   return true;
00298 }
00299 
00300 // Determines the context to return to after temporarily entering a
00301 // context.  This depends in an unnecessarily complicated way on the
00302 // exact ordering of callbacks from the parser.
00303 DeclContext *Sema::getContainingDC(DeclContext *DC) {
00304 
00305   // Functions defined inline within classes aren't parsed until we've
00306   // finished parsing the top-level class, so the top-level class is
00307   // the context we'll need to return to.
00308   if (isa<FunctionDecl>(DC)) {
00309     DC = DC->getLexicalParent();
00310 
00311     // A function not defined within a class will always return to its
00312     // lexical context.
00313     if (!isa<CXXRecordDecl>(DC))
00314       return DC;
00315 
00316     // A C++ inline method/friend is parsed *after* the topmost class
00317     // it was declared in is fully parsed ("complete");  the topmost
00318     // class is the context we need to return to.
00319     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
00320       DC = RD;
00321 
00322     // Return the declaration context of the topmost class the inline method is
00323     // declared in.
00324     return DC;
00325   }
00326 
00327   if (isa<ObjCMethodDecl>(DC))
00328     return Context.getTranslationUnitDecl();
00329 
00330   return DC->getLexicalParent();
00331 }
00332 
00333 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
00334   assert(getContainingDC(DC) == CurContext &&
00335       "The next DeclContext should be lexically contained in the current one.");
00336   CurContext = DC;
00337   S->setEntity(DC);
00338 }
00339 
00340 void Sema::PopDeclContext() {
00341   assert(CurContext && "DeclContext imbalance!");
00342 
00343   CurContext = getContainingDC(CurContext);
00344 }
00345 
00346 /// EnterDeclaratorContext - Used when we must lookup names in the context
00347 /// of a declarator's nested name specifier.
00348 ///
00349 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
00350   // C++0x [basic.lookup.unqual]p13:
00351   //   A name used in the definition of a static data member of class
00352   //   X (after the qualified-id of the static member) is looked up as
00353   //   if the name was used in a member function of X.
00354   // C++0x [basic.lookup.unqual]p14:
00355   //   If a variable member of a namespace is defined outside of the
00356   //   scope of its namespace then any name used in the definition of
00357   //   the variable member (after the declarator-id) is looked up as
00358   //   if the definition of the variable member occurred in its
00359   //   namespace.
00360   // Both of these imply that we should push a scope whose context
00361   // is the semantic context of the declaration.  We can't use
00362   // PushDeclContext here because that context is not necessarily
00363   // lexically contained in the current context.  Fortunately,
00364   // the containing scope should have the appropriate information.
00365 
00366   assert(!S->getEntity() && "scope already has entity");
00367 
00368 #ifndef NDEBUG
00369   Scope *Ancestor = S->getParent();
00370   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
00371   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
00372 #endif
00373 
00374   CurContext = DC;
00375   S->setEntity(DC);
00376 }
00377 
00378 void Sema::ExitDeclaratorContext(Scope *S) {
00379   assert(S->getEntity() == CurContext && "Context imbalance!");
00380 
00381   // Switch back to the lexical context.  The safety of this is
00382   // enforced by an assert in EnterDeclaratorContext.
00383   Scope *Ancestor = S->getParent();
00384   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
00385   CurContext = (DeclContext*) Ancestor->getEntity();
00386 
00387   // We don't need to do anything with the scope, which is going to
00388   // disappear.
00389 }
00390 
00391 /// \brief Determine whether we allow overloading of the function
00392 /// PrevDecl with another declaration.
00393 ///
00394 /// This routine determines whether overloading is possible, not
00395 /// whether some new function is actually an overload. It will return
00396 /// true in C++ (where we can always provide overloads) or, as an
00397 /// extension, in C when the previous function is already an
00398 /// overloaded function declaration or has the "overloadable"
00399 /// attribute.
00400 static bool AllowOverloadingOfFunction(LookupResult &Previous,
00401                                        ASTContext &Context) {
00402   if (Context.getLangOptions().CPlusPlus)
00403     return true;
00404 
00405   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
00406     return true;
00407 
00408   return (Previous.getResultKind() == LookupResult::Found
00409           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
00410 }
00411 
00412 /// Add this decl to the scope shadowed decl chains.
00413 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
00414   // Move up the scope chain until we find the nearest enclosing
00415   // non-transparent context. The declaration will be introduced into this
00416   // scope.
00417   while (S->getEntity() &&
00418          ((DeclContext *)S->getEntity())->isTransparentContext())
00419     S = S->getParent();
00420 
00421   // Add scoped declarations into their context, so that they can be
00422   // found later. Declarations without a context won't be inserted
00423   // into any context.
00424   if (AddToContext)
00425     CurContext->addDecl(D);
00426 
00427   // Out-of-line definitions shouldn't be pushed into scope in C++.
00428   // Out-of-line variable and function definitions shouldn't even in C.
00429   if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
00430       D->isOutOfLine())
00431     return;
00432 
00433   // Template instantiations should also not be pushed into scope.
00434   if (isa<FunctionDecl>(D) &&
00435       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
00436     return;
00437 
00438   // If this replaces anything in the current scope, 
00439   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
00440                                IEnd = IdResolver.end();
00441   for (; I != IEnd; ++I) {
00442     if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
00443       S->RemoveDecl(DeclPtrTy::make(*I));
00444       IdResolver.RemoveDecl(*I);
00445 
00446       // Should only need to replace one decl.
00447       break;
00448     }
00449   }
00450 
00451   S->AddDecl(DeclPtrTy::make(D));
00452   IdResolver.AddDecl(D);
00453 }
00454 
00455 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
00456   return IdResolver.isDeclInScope(D, Ctx, Context, S);
00457 }
00458 
00459 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
00460                                             DeclContext*,
00461                                             ASTContext&);
00462 
00463 /// Filters out lookup results that don't fall within the given scope
00464 /// as determined by isDeclInScope.
00465 static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
00466                                  DeclContext *Ctx, Scope *S,
00467                                  bool ConsiderLinkage) {
00468   LookupResult::Filter F = R.makeFilter();
00469   while (F.hasNext()) {
00470     NamedDecl *D = F.next();
00471 
00472     if (SemaRef.isDeclInScope(D, Ctx, S))
00473       continue;
00474 
00475     if (ConsiderLinkage &&
00476         isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
00477       continue;
00478     
00479     F.erase();
00480   }
00481 
00482   F.done();
00483 }
00484 
00485 static bool isUsingDecl(NamedDecl *D) {
00486   return isa<UsingShadowDecl>(D) ||
00487          isa<UnresolvedUsingTypenameDecl>(D) ||
00488          isa<UnresolvedUsingValueDecl>(D);
00489 }
00490 
00491 /// Removes using shadow declarations from the lookup results.
00492 static void RemoveUsingDecls(LookupResult &R) {
00493   LookupResult::Filter F = R.makeFilter();
00494   while (F.hasNext())
00495     if (isUsingDecl(F.next()))
00496       F.erase();
00497 
00498   F.done();
00499 }
00500 
00501 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
00502   if (D->isInvalidDecl())
00503     return false;
00504 
00505   if (D->isUsed() || D->hasAttr<UnusedAttr>())
00506     return false;
00507 
00508   // White-list anything that isn't a local variable.
00509   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
00510       !D->getDeclContext()->isFunctionOrMethod())
00511     return false;
00512 
00513   // Types of valid local variables should be complete, so this should succeed.
00514   if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
00515     if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
00516       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
00517         if (!RD->hasTrivialConstructor())
00518           return false;
00519         if (!RD->hasTrivialDestructor())
00520           return false;
00521       }
00522     }
00523   }
00524   
00525   return true;
00526 }
00527 
00528 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
00529   if (S->decl_empty()) return;
00530   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
00531          "Scope shouldn't contain decls!");
00532 
00533   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
00534        I != E; ++I) {
00535     Decl *TmpD = (*I).getAs<Decl>();
00536     assert(TmpD && "This decl didn't get pushed??");
00537 
00538     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
00539     NamedDecl *D = cast<NamedDecl>(TmpD);
00540 
00541     if (!D->getDeclName()) continue;
00542 
00543     // Diagnose unused variables in this scope.
00544     if (ShouldDiagnoseUnusedDecl(D) && 
00545         S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
00546       Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
00547     
00548     // Remove this name from our lexical scope.
00549     IdResolver.RemoveDecl(D);
00550   }
00551 }
00552 
00553 /// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
00554 /// return 0 if one not found.
00555 ///
00556 /// \param Id the name of the Objective-C class we're looking for. If
00557 /// typo-correction fixes this name, the Id will be updated
00558 /// to the fixed name.
00559 ///
00560 /// \param RecoverLoc if provided, this routine will attempt to
00561 /// recover from a typo in the name of an existing Objective-C class
00562 /// and, if successful, will return the lookup that results from
00563 /// typo-correction.
00564 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
00565                                               SourceLocation RecoverLoc) {
00566   // The third "scope" argument is 0 since we aren't enabling lazy built-in
00567   // creation from this context.
00568   NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
00569 
00570   if (!IDecl && !RecoverLoc.isInvalid()) {
00571     // Perform typo correction at the given location, but only if we
00572     // find an Objective-C class name.
00573     LookupResult R(*this, Id, RecoverLoc, LookupOrdinaryName);
00574     if (CorrectTypo(R, TUScope, 0) &&
00575         (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
00576       Diag(RecoverLoc, diag::err_undef_interface_suggest)
00577         << Id << IDecl->getDeclName() 
00578         << CodeModificationHint::CreateReplacement(RecoverLoc, 
00579                                                    IDecl->getNameAsString());
00580       Diag(IDecl->getLocation(), diag::note_previous_decl)
00581         << IDecl->getDeclName();
00582       
00583       Id = IDecl->getIdentifier();
00584     }
00585   }
00586 
00587   return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
00588 }
00589 
00590 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
00591 /// from S, where a non-field would be declared. This routine copes
00592 /// with the difference between C and C++ scoping rules in structs and
00593 /// unions. For example, the following code is well-formed in C but
00594 /// ill-formed in C++:
00595 /// @code
00596 /// struct S6 {
00597 ///   enum { BAR } e;
00598 /// };
00599 ///
00600 /// void test_S6() {
00601 ///   struct S6 a;
00602 ///   a.e = BAR;
00603 /// }
00604 /// @endcode
00605 /// For the declaration of BAR, this routine will return a different
00606 /// scope. The scope S will be the scope of the unnamed enumeration
00607 /// within S6. In C++, this routine will return the scope associated
00608 /// with S6, because the enumeration's scope is a transparent
00609 /// context but structures can contain non-field names. In C, this
00610 /// routine will return the translation unit scope, since the
00611 /// enumeration's scope is a transparent context and structures cannot
00612 /// contain non-field names.
00613 Scope *Sema::getNonFieldDeclScope(Scope *S) {
00614   while (((S->getFlags() & Scope::DeclScope) == 0) ||
00615          (S->getEntity() &&
00616           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
00617          (S->isClassScope() && !getLangOptions().CPlusPlus))
00618     S = S->getParent();
00619   return S;
00620 }
00621 
00622 void Sema::InitBuiltinVaListType() {
00623   if (!Context.getBuiltinVaListType().isNull())
00624     return;
00625 
00626   IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
00627   NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
00628   TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
00629   Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
00630 }
00631 
00632 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
00633 /// file scope.  lazily create a decl for it. ForRedeclaration is true
00634 /// if we're creating this built-in in anticipation of redeclaring the
00635 /// built-in.
00636 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
00637                                      Scope *S, bool ForRedeclaration,
00638                                      SourceLocation Loc) {
00639   Builtin::ID BID = (Builtin::ID)bid;
00640 
00641   if (Context.BuiltinInfo.hasVAListUse(BID))
00642     InitBuiltinVaListType();
00643 
00644   ASTContext::GetBuiltinTypeError Error;
00645   QualType R = Context.GetBuiltinType(BID, Error);
00646   switch (Error) {
00647   case ASTContext::GE_None:
00648     // Okay
00649     break;
00650 
00651   case ASTContext::GE_Missing_stdio:
00652     if (ForRedeclaration)
00653       Diag(Loc, diag::err_implicit_decl_requires_stdio)
00654         << Context.BuiltinInfo.GetName(BID);
00655     return 0;
00656 
00657   case ASTContext::GE_Missing_setjmp:
00658     if (ForRedeclaration)
00659       Diag(Loc, diag::err_implicit_decl_requires_setjmp)
00660         << Context.BuiltinInfo.GetName(BID);
00661     return 0;
00662   }
00663 
00664   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
00665     Diag(Loc, diag::ext_implicit_lib_function_decl)
00666       << Context.BuiltinInfo.GetName(BID)
00667       << R;
00668     if (Context.BuiltinInfo.getHeaderName(BID) &&
00669         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
00670           != Diagnostic::Ignored)
00671       Diag(Loc, diag::note_please_include_header)
00672         << Context.BuiltinInfo.getHeaderName(BID)
00673         << Context.BuiltinInfo.GetName(BID);
00674   }
00675 
00676   FunctionDecl *New = FunctionDecl::Create(Context,
00677                                            Context.getTranslationUnitDecl(),
00678                                            Loc, II, R, /*TInfo=*/0,
00679                                            FunctionDecl::Extern, false,
00680                                            /*hasPrototype=*/true);
00681   New->setImplicit();
00682 
00683   // Create Decl objects for each parameter, adding them to the
00684   // FunctionDecl.
00685   if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
00686     llvm::SmallVector<ParmVarDecl*, 16> Params;
00687     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
00688       Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
00689                                            FT->getArgType(i), /*TInfo=*/0,
00690                                            VarDecl::None, 0));
00691     New->setParams(Params.data(), Params.size());
00692   }
00693 
00694   AddKnownFunctionAttributes(New);
00695 
00696   // TUScope is the translation-unit scope to insert this function into.
00697   // FIXME: This is hideous. We need to teach PushOnScopeChains to
00698   // relate Scopes to DeclContexts, and probably eliminate CurContext
00699   // entirely, but we're not there yet.
00700   DeclContext *SavedContext = CurContext;
00701   CurContext = Context.getTranslationUnitDecl();
00702   PushOnScopeChains(New, TUScope);
00703   CurContext = SavedContext;
00704   return New;
00705 }
00706 
00707 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
00708 /// same name and scope as a previous declaration 'Old'.  Figure out
00709 /// how to resolve this situation, merging decls or emitting
00710 /// diagnostics as appropriate. If there was an error, set New to be invalid.
00711 ///
00712 void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
00713   // If the new decl is known invalid already, don't bother doing any
00714   // merging checks.
00715   if (New->isInvalidDecl()) return;
00716 
00717   // Allow multiple definitions for ObjC built-in typedefs.
00718   // FIXME: Verify the underlying types are equivalent!
00719   if (getLangOptions().ObjC1) {
00720     const IdentifierInfo *TypeID = New->getIdentifier();
00721     switch (TypeID->getLength()) {
00722     default: break;
00723     case 2:
00724       if (!TypeID->isStr("id"))
00725         break;
00726       Context.ObjCIdRedefinitionType = New->getUnderlyingType();
00727       // Install the built-in type for 'id', ignoring the current definition.
00728       New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
00729       return;
00730     case 5:
00731       if (!TypeID->isStr("Class"))
00732         break;
00733       Context.ObjCClassRedefinitionType = New->getUnderlyingType();
00734       // Install the built-in type for 'Class', ignoring the current definition.
00735       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
00736       return;
00737     case 3:
00738       if (!TypeID->isStr("SEL"))
00739         break;
00740       Context.ObjCSelRedefinitionType = New->getUnderlyingType();
00741       // Install the built-in type for 'SEL', ignoring the current definition.
00742       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
00743       return;
00744     case 8:
00745       if (!TypeID->isStr("Protocol"))
00746         break;
00747       Context.setObjCProtoType(New->getUnderlyingType());
00748       return;
00749     }
00750     // Fall through - the typedef name was not a builtin type.
00751   }
00752 
00753   // Verify the old decl was also a type.
00754   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
00755   if (!Old) {
00756     Diag(New->getLocation(), diag::err_redefinition_different_kind)
00757       << New->getDeclName();
00758 
00759     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
00760     if (OldD->getLocation().isValid())
00761       Diag(OldD->getLocation(), diag::note_previous_definition);
00762 
00763     return New->setInvalidDecl();
00764   }
00765 
00766   // If the old declaration is invalid, just give up here.
00767   if (Old->isInvalidDecl())
00768     return New->setInvalidDecl();
00769 
00770   // Determine the "old" type we'll use for checking and diagnostics.
00771   QualType OldType;
00772   if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
00773     OldType = OldTypedef->getUnderlyingType();
00774   else
00775     OldType = Context.getTypeDeclType(Old);
00776 
00777   // If the typedef types are not identical, reject them in all languages and
00778   // with any extensions enabled.
00779 
00780   if (OldType != New->getUnderlyingType() &&
00781       Context.getCanonicalType(OldType) !=
00782       Context.getCanonicalType(New->getUnderlyingType())) {
00783     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
00784       << New->getUnderlyingType() << OldType;
00785     if (Old->getLocation().isValid())
00786       Diag(Old->getLocation(), diag::note_previous_definition);
00787     return New->setInvalidDecl();
00788   }
00789 
00790   // The types match.  Link up the redeclaration chain if the old
00791   // declaration was a typedef.
00792   // FIXME: this is a potential source of wierdness if the type
00793   // spellings don't match exactly.
00794   if (isa<TypedefDecl>(Old))
00795     New->setPreviousDeclaration(cast<TypedefDecl>(Old));
00796 
00797   if (getLangOptions().Microsoft)
00798     return;
00799 
00800   if (getLangOptions().CPlusPlus) {
00801     // C++ [dcl.typedef]p2:
00802     //   In a given non-class scope, a typedef specifier can be used to
00803     //   redefine the name of any type declared in that scope to refer
00804     //   to the type to which it already refers.
00805     if (!isa<CXXRecordDecl>(CurContext))
00806       return;
00807 
00808     // C++0x [dcl.typedef]p4:
00809     //   In a given class scope, a typedef specifier can be used to redefine 
00810     //   any class-name declared in that scope that is not also a typedef-name
00811     //   to refer to the type to which it already refers.
00812     //
00813     // This wording came in via DR424, which was a correction to the
00814     // wording in DR56, which accidentally banned code like:
00815     //
00816     //   struct S {
00817     //     typedef struct A { } A;
00818     //   };
00819     //
00820     // in the C++03 standard. We implement the C++0x semantics, which
00821     // allow the above but disallow
00822     //
00823     //   struct S {
00824     //     typedef int I;
00825     //     typedef int I;
00826     //   };
00827     //
00828     // since that was the intent of DR56.
00829     if (!isa<TypedefDecl >(Old))
00830       return;
00831 
00832     Diag(New->getLocation(), diag::err_redefinition)
00833       << New->getDeclName();
00834     Diag(Old->getLocation(), diag::note_previous_definition);
00835     return New->setInvalidDecl();
00836   }
00837 
00838   // If we have a redefinition of a typedef in C, emit a warning.  This warning
00839   // is normally mapped to an error, but can be controlled with
00840   // -Wtypedef-redefinition.  If either the original or the redefinition is
00841   // in a system header, don't emit this for compatibility with GCC.
00842   if (getDiagnostics().getSuppressSystemWarnings() &&
00843       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
00844        Context.getSourceManager().isInSystemHeader(New->getLocation())))
00845     return;
00846 
00847   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
00848     << New->getDeclName();
00849   Diag(Old->getLocation(), diag::note_previous_definition);
00850   return;
00851 }
00852 
00853 /// DeclhasAttr - returns true if decl Declaration already has the target
00854 /// attribute.
00855 static bool
00856 DeclHasAttr(const Decl *decl, const Attr *target) {
00857   for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
00858     if (attr->getKind() == target->getKind())
00859       return true;
00860 
00861   return false;
00862 }
00863 
00864 /// MergeAttributes - append attributes from the Old decl to the New one.
00865 static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
00866   for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
00867     if (!DeclHasAttr(New, attr) && attr->isMerged()) {
00868       Attr *NewAttr = attr->clone(C);
00869       NewAttr->setInherited(true);
00870       New->addAttr(NewAttr);
00871     }
00872   }
00873 }
00874 
00875 /// Used in MergeFunctionDecl to keep track of function parameters in
00876 /// C.
00877 struct GNUCompatibleParamWarning {
00878   ParmVarDecl *OldParm;
00879   ParmVarDecl *NewParm;
00880   QualType PromotedType;
00881 };
00882 
00883 
00884 /// getSpecialMember - get the special member enum for a method.
00885 static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
00886                                                const CXXMethodDecl *MD) {
00887   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
00888     if (Ctor->isDefaultConstructor())
00889       return Sema::CXXDefaultConstructor;
00890     if (Ctor->isCopyConstructor())
00891       return Sema::CXXCopyConstructor;
00892   } 
00893   
00894   if (isa<CXXDestructorDecl>(MD))
00895     return Sema::CXXDestructor;
00896   
00897   assert(MD->isCopyAssignment() && "Must have copy assignment operator");
00898   return Sema::CXXCopyAssignment;
00899 }
00900 
00901 /// canREdefineFunction - checks if a function can be redefined. Currently,
00902 /// only extern inline functions can be redefined, and even then only in
00903 /// GNU89 mode.
00904 static bool canRedefineFunction(const FunctionDecl *FD,
00905                                 const LangOptions& LangOpts) {
00906   return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
00907           FD->isInlineSpecified() &&
00908           FD->getStorageClass() == FunctionDecl::Extern);
00909 }
00910 
00911 /// MergeFunctionDecl - We just parsed a function 'New' from
00912 /// declarator D which has the same name and scope as a previous
00913 /// declaration 'Old'.  Figure out how to resolve this situation,
00914 /// merging decls or emitting diagnostics as appropriate.
00915 ///
00916 /// In C++, New and Old must be declarations that are not
00917 /// overloaded. Use IsOverload to determine whether New and Old are
00918 /// overloaded, and to select the Old declaration that New should be
00919 /// merged with.
00920 ///
00921 /// Returns true if there was an error, false otherwise.
00922 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
00923   // Verify the old decl was also a function.
00924   FunctionDecl *Old = 0;
00925   if (FunctionTemplateDecl *OldFunctionTemplate
00926         = dyn_cast<FunctionTemplateDecl>(OldD))
00927     Old = OldFunctionTemplate->getTemplatedDecl();
00928   else
00929     Old = dyn_cast<FunctionDecl>(OldD);
00930   if (!Old) {
00931     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
00932       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
00933       Diag(Shadow->getTargetDecl()->getLocation(),
00934            diag::note_using_decl_target);
00935       Diag(Shadow->getUsingDecl()->getLocation(),
00936            diag::note_using_decl) << 0;
00937       return true;
00938     }
00939 
00940     Diag(New->getLocation(), diag::err_redefinition_different_kind)
00941       << New->getDeclName();
00942     Diag(OldD->getLocation(), diag::note_previous_definition);
00943     return true;
00944   }
00945 
00946   // Determine whether the previous declaration was a definition,
00947   // implicit declaration, or a declaration.
00948   diag::kind PrevDiag;
00949   if (Old->isThisDeclarationADefinition())
00950     PrevDiag = diag::note_previous_definition;
00951   else if (Old->isImplicit())
00952     PrevDiag = diag::note_previous_implicit_declaration;
00953   else
00954     PrevDiag = diag::note_previous_declaration;
00955 
00956   QualType OldQType = Context.getCanonicalType(Old->getType());
00957   QualType NewQType = Context.getCanonicalType(New->getType());
00958 
00959   // Don't complain about this if we're in GNU89 mode and the old function
00960   // is an extern inline function.
00961   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
00962       New->getStorageClass() == FunctionDecl::Static &&
00963       Old->getStorageClass() != FunctionDecl::Static &&
00964       !canRedefineFunction(Old, getLangOptions())) {
00965     Diag(New->getLocation(), diag::err_static_non_static)
00966       << New;
00967     Diag(Old->getLocation(), PrevDiag);
00968     return true;
00969   }
00970 
00971   // If a function is first declared with a calling convention, but is
00972   // later declared or defined without one, the second decl assumes the
00973   // calling convention of the first.
00974   //
00975   // For the new decl, we have to look at the NON-canonical type to tell the
00976   // difference between a function that really doesn't have a calling
00977   // convention and one that is declared cdecl. That's because in
00978   // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
00979   // because it is the default calling convention.
00980   //
00981   // Note also that we DO NOT return at this point, because we still have
00982   // other tests to run.
00983   const FunctionType *OldType = OldQType->getAs<FunctionType>();
00984   const FunctionType *NewType = New->getType()->getAs<FunctionType>();
00985   if (OldType->getCallConv() != CC_Default &&
00986       NewType->getCallConv() == CC_Default) {
00987     NewQType = Context.getCallConvType(NewQType, OldType->getCallConv());
00988     New->setType(NewQType);
00989     NewQType = Context.getCanonicalType(NewQType);
00990   } else if (!Context.isSameCallConv(OldType->getCallConv(),
00991                                      NewType->getCallConv())) {
00992     // Calling conventions really aren't compatible, so complain.
00993     Diag(New->getLocation(), diag::err_cconv_change)
00994       << FunctionType::getNameForCallConv(NewType->getCallConv())
00995       << (OldType->getCallConv() == CC_Default)
00996       << (OldType->getCallConv() == CC_Default ? "" :
00997           FunctionType::getNameForCallConv(OldType->getCallConv()));
00998     Diag(Old->getLocation(), diag::note_previous_declaration);
00999     return true;
01000   }
01001 
01002   // FIXME: diagnose the other way around?
01003   if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
01004     NewQType = Context.getNoReturnType(NewQType);
01005     New->setType(NewQType);
01006     assert(NewQType.isCanonical());
01007   }
01008 
01009   if (getLangOptions().CPlusPlus) {
01010     // (C++98 13.1p2):
01011     //   Certain function declarations cannot be overloaded:
01012     //     -- Function declarations that differ only in the return type
01013     //        cannot be overloaded.
01014     QualType OldReturnType
01015       = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
01016     QualType NewReturnType
01017       = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
01018     if (OldReturnType != NewReturnType) {
01019       Diag(New->getLocation(), diag::err_ovl_diff_return_type);
01020       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
01021       return true;
01022     }
01023 
01024     const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
01025     const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
01026     if (OldMethod && NewMethod) {
01027       if (!NewMethod->getFriendObjectKind() &&
01028           NewMethod->getLexicalDeclContext()->isRecord()) {
01029         //    -- Member function declarations with the same name and the
01030         //       same parameter types cannot be overloaded if any of them
01031         //       is a static member function declaration.
01032         if (OldMethod->isStatic() || NewMethod->isStatic()) {
01033           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
01034           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
01035           return true;
01036         }
01037       
01038         // C++ [class.mem]p1:
01039         //   [...] A member shall not be declared twice in the
01040         //   member-specification, except that a nested class or member
01041         //   class template can be declared and then later defined.
01042         unsigned NewDiag;
01043         if (isa<CXXConstructorDecl>(OldMethod))
01044           NewDiag = diag::err_constructor_redeclared;
01045         else if (isa<CXXDestructorDecl>(NewMethod))
01046           NewDiag = diag::err_destructor_redeclared;
01047         else if (isa<CXXConversionDecl>(NewMethod))
01048           NewDiag = diag::err_conv_function_redeclared;
01049         else
01050           NewDiag = diag::err_member_redeclared;
01051 
01052         Diag(New->getLocation(), NewDiag);
01053         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
01054       } else {
01055         if (OldMethod->isImplicit()) {
01056           Diag(NewMethod->getLocation(),
01057                diag::err_definition_of_implicitly_declared_member) 
01058           << New << getSpecialMember(Context, OldMethod);
01059         
01060           Diag(OldMethod->getLocation(),
01061                diag::note_previous_implicit_declaration);
01062           return true;
01063         }
01064       }
01065     }
01066 
01067     // (C++98 8.3.5p3):
01068     //   All declarations for a function shall agree exactly in both the
01069     //   return type and the parameter-type-list.
01070     // attributes should be ignored when comparing.
01071     if (Context.getNoReturnType(OldQType, false) ==
01072         Context.getNoReturnType(NewQType, false))
01073       return MergeCompatibleFunctionDecls(New, Old);
01074 
01075     // Fall through for conflicting redeclarations and redefinitions.
01076   }
01077 
01078   // C: Function types need to be compatible, not identical. This handles
01079   // duplicate function decls like "void f(int); void f(enum X);" properly.
01080   if (!getLangOptions().CPlusPlus &&
01081       Context.typesAreCompatible(OldQType, NewQType)) {
01082     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
01083     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
01084     const FunctionProtoType *OldProto = 0;
01085     if (isa<FunctionNoProtoType>(NewFuncType) &&
01086         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
01087       // The old declaration provided a function prototype, but the
01088       // new declaration does not. Merge in the prototype.
01089       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
01090       llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
01091                                                  OldProto->arg_type_end());
01092       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
01093                                          ParamTypes.data(), ParamTypes.size(),
01094                                          OldProto->isVariadic(),
01095                                          OldProto->getTypeQuals(),
01096                                          false, false, 0, 0,
01097                                          OldProto->getNoReturnAttr(),
01098                                          OldProto->getCallConv());
01099       New->setType(NewQType);
01100       New->setHasInheritedPrototype();
01101 
01102       // Synthesize a parameter for each argument type.
01103       llvm::SmallVector<ParmVarDecl*, 16> Params;
01104       for (FunctionProtoType::arg_type_iterator
01105              ParamType = OldProto->arg_type_begin(),
01106              ParamEnd = OldProto->arg_type_end();
01107            ParamType != ParamEnd; ++ParamType) {
01108         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
01109                                                  SourceLocation(), 0,
01110                                                  *ParamType, /*TInfo=*/0,
01111                                                  VarDecl::None, 0);
01112         Param->setImplicit();
01113         Params.push_back(Param);
01114       }
01115 
01116       New->setParams(Params.data(), Params.size());
01117     }
01118 
01119     return MergeCompatibleFunctionDecls(New, Old);
01120   }
01121 
01122   // GNU C permits a K&R definition to follow a prototype declaration
01123   // if the declared types of the parameters in the K&R definition
01124   // match the types in the prototype declaration, even when the
01125   // promoted types of the parameters from the K&R definition differ
01126   // from the types in the prototype. GCC then keeps the types from
01127   // the prototype.
01128   //
01129   // If a variadic prototype is followed by a non-variadic K&R definition,
01130   // the K&R definition becomes variadic.  This is sort of an edge case, but
01131   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
01132   // C99 6.9.1p8.
01133   if (!getLangOptions().CPlusPlus &&
01134       Old->hasPrototype() && !New->hasPrototype() &&
01135       New->getType()->getAs<FunctionProtoType>() &&
01136       Old->getNumParams() == New->getNumParams()) {
01137     llvm::SmallVector<QualType, 16> ArgTypes;
01138     llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
01139     const FunctionProtoType *OldProto
01140       = Old->getType()->getAs<FunctionProtoType>();
01141     const FunctionProtoType *NewProto
01142       = New->getType()->getAs<FunctionProtoType>();
01143 
01144     // Determine whether this is the GNU C extension.
01145     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
01146                                                NewProto->getResultType());
01147     bool LooseCompatible = !MergedReturn.isNull();
01148     for (unsigned Idx = 0, End = Old->getNumParams();
01149          LooseCompatible && Idx != End; ++Idx) {
01150       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
01151       ParmVarDecl *NewParm = New->getParamDecl(Idx);
01152       if (Context.typesAreCompatible(OldParm->getType(),
01153                                      NewProto->getArgType(Idx))) {
01154         ArgTypes.push_back(NewParm->getType());
01155       } else if (Context.typesAreCompatible(OldParm->getType(),
01156                                             NewParm->getType())) {
01157         GNUCompatibleParamWarning Warn
01158           = { OldParm, NewParm, NewProto->getArgType(Idx) };
01159         Warnings.push_back(Warn);
01160         ArgTypes.push_back(NewParm->getType());
01161       } else
01162         LooseCompatible = false;
01163     }
01164 
01165     if (LooseCompatible) {
01166       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
01167         Diag(Warnings[Warn].NewParm->getLocation(),
01168              diag::ext_param_promoted_not_compatible_with_prototype)
01169           << Warnings[Warn].PromotedType
01170           << Warnings[Warn].OldParm->getType();
01171         Diag(Warnings[Warn].OldParm->getLocation(),
01172              diag::note_previous_declaration);
01173       }
01174 
01175       New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
01176                                            ArgTypes.size(),
01177                                            OldProto->isVariadic(), 0,
01178                                            false, false, 0, 0,
01179                                            OldProto->getNoReturnAttr(),
01180                                            OldProto->getCallConv()));
01181       return MergeCompatibleFunctionDecls(New, Old);
01182     }
01183 
01184     // Fall through to diagnose conflicting types.
01185   }
01186 
01187   // A function that has already been declared has been redeclared or defined
01188   // with a different type- show appropriate diagnostic
01189   if (unsigned BuiltinID = Old->getBuiltinID()) {
01190     // The user has declared a builtin function with an incompatible
01191     // signature.
01192     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
01193       // The function the user is redeclaring is a library-defined
01194       // function like 'malloc' or 'printf'. Warn about the
01195       // redeclaration, then pretend that we don't know about this
01196       // library built-in.
01197       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
01198       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
01199         << Old << Old->getType();
01200       New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
01201       Old->setInvalidDecl();
01202       return false;
01203     }
01204 
01205     PrevDiag = diag::note_previous_builtin_declaration;
01206   }
01207 
01208   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
01209   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
01210   return true;
01211 }
01212 
01213 /// \brief Completes the merge of two function declarations that are
01214 /// known to be compatible.
01215 ///
01216 /// This routine handles the merging of attributes and other
01217 /// properties of function declarations form the old declaration to
01218 /// the new declaration, once we know that New is in fact a
01219 /// redeclaration of Old.
01220 ///
01221 /// \returns false
01222 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
01223   // Merge the attributes
01224   MergeAttributes(New, Old, Context);
01225 
01226   // Merge the storage class.
01227   if (Old->getStorageClass() != FunctionDecl::Extern &&
01228       Old->getStorageClass() != FunctionDecl::None)
01229     New->setStorageClass(Old->getStorageClass());
01230 
01231   // Merge "pure" flag.
01232   if (Old->isPure())
01233     New->setPure();
01234 
01235   // Merge the "deleted" flag.
01236   if (Old->isDeleted())
01237     New->setDeleted();
01238 
01239   if (getLangOptions().CPlusPlus)
01240     return MergeCXXFunctionDecl(New, Old);
01241 
01242   return false;
01243 }
01244 
01245 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
01246 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
01247 /// situation, merging decls or emitting diagnostics as appropriate.
01248 ///
01249 /// Tentative definition rules (C99 6.9.2p2) are checked by
01250 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
01251 /// definitions here, since the initializer hasn't been attached.
01252 ///
01253 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
01254   // If the new decl is already invalid, don't do any other checking.
01255   if (New->isInvalidDecl())
01256     return;
01257 
01258   // Verify the old decl was also a variable.
01259   VarDecl *Old = 0;
01260   if (!Previous.isSingleResult() ||
01261       !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
01262     Diag(New->getLocation(), diag::err_redefinition_different_kind)
01263       << New->getDeclName();
01264     Diag(Previous.getRepresentativeDecl()->getLocation(),
01265          diag::note_previous_definition);
01266     return New->setInvalidDecl();
01267   }
01268 
01269   MergeAttributes(New, Old, Context);
01270 
01271   // Merge the types
01272   QualType MergedT;
01273   if (getLangOptions().CPlusPlus) {
01274     if (Context.hasSameType(New->getType(), Old->getType()))
01275       MergedT = New->getType();
01276     // C++ [basic.link]p10:
01277     //   [...] the types specified by all declarations referring to a given
01278     //   object or function shall be identical, except that declarations for an
01279     //   array object can specify array types that differ by the presence or
01280     //   absence of a major array bound (8.3.4).
01281     else if (Old->getType()->isIncompleteArrayType() &&
01282              New->getType()->isArrayType()) {
01283       CanQual<ArrayType> OldArray
01284         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
01285       CanQual<ArrayType> NewArray
01286         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
01287       if (OldArray->getElementType() == NewArray->getElementType())
01288         MergedT = New->getType();
01289     } else if (Old->getType()->isArrayType() &&
01290              New->getType()->isIncompleteArrayType()) {
01291       CanQual<ArrayType> OldArray
01292         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
01293       CanQual<ArrayType> NewArray
01294         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
01295       if (OldArray->getElementType() == NewArray->getElementType())
01296         MergedT = Old->getType();
01297     }
01298   } else {
01299     MergedT = Context.mergeTypes(New->getType(), Old->getType());
01300   }
01301   if (MergedT.isNull()) {
01302     Diag(New->getLocation(), diag::err_redefinition_different_type)
01303       << New->getDeclName();
01304     Diag(Old->getLocation(), diag::note_previous_definition);
01305     return New->setInvalidDecl();
01306   }
01307   New->setType(MergedT);
01308 
01309   // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
01310   if (New->getStorageClass() == VarDecl::Static &&
01311       (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
01312     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
01313     Diag(Old->getLocation(), diag::note_previous_definition);
01314     return New->setInvalidDecl();
01315   }
01316   // C99 6.2.2p4:
01317   //   For an identifier declared with the storage-class specifier
01318   //   extern in a scope in which a prior declaration of that
01319   //   identifier is visible,23) if the prior declaration specifies
01320   //   internal or external linkage, the linkage of the identifier at
01321   //   the later declaration is the same as the linkage specified at
01322   //   the prior declaration. If no prior declaration is visible, or
01323   //   if the prior declaration specifies no linkage, then the
01324   //   identifier has external linkage.
01325   if (New->hasExternalStorage() && Old->hasLinkage())
01326     /* Okay */;
01327   else if (New->getStorageClass() != VarDecl::Static &&
01328            Old->getStorageClass() == VarDecl::Static) {
01329     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
01330     Diag(Old->getLocation(), diag::note_previous_definition);
01331     return New->setInvalidDecl();
01332   }
01333 
01334   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
01335 
01336   // FIXME: The test for external storage here seems wrong? We still
01337   // need to check for mismatches.
01338   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
01339       // Don't complain about out-of-line definitions of static members.
01340       !(Old->getLexicalDeclContext()->isRecord() &&
01341         !New->getLexicalDeclContext()->isRecord())) {
01342     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
01343     Diag(Old->getLocation(), diag::note_previous_definition);
01344     return New->setInvalidDecl();
01345   }
01346 
01347   if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
01348     Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
01349     Diag(Old->getLocation(), diag::note_previous_definition);
01350   } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
01351     Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
01352     Diag(Old->getLocation(), diag::note_previous_definition);
01353   }
01354 
01355   // C++ doesn't have tentative definitions, so go right ahead and check here.
01356   const VarDecl *Def;
01357   if (getLangOptions().CPlusPlus &&
01358       New->isThisDeclarationADefinition() == VarDecl::Definition &&
01359       (Def = Old->getDefinition())) {
01360     Diag(New->getLocation(), diag::err_redefinition)
01361       << New->getDeclName();
01362     Diag(Def->getLocation(), diag::note_previous_definition);
01363     New->setInvalidDecl();
01364     return;
01365   }
01366 
01367   // Keep a chain of previous declarations.
01368   New->setPreviousDeclaration(Old);
01369 
01370   // Inherit access appropriately.
01371   New->setAccess(Old->getAccess());
01372 }
01373 
01374 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
01375 /// no declarator (e.g. "struct foo;") is parsed.
01376 Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
01377   // FIXME: Error on auto/register at file scope
01378   // FIXME: Error on inline/virtual/explicit
01379   // FIXME: Warn on useless __thread
01380   // FIXME: Warn on useless const/volatile
01381   // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
01382   // FIXME: Warn on useless attributes
01383   Decl *TagD = 0;
01384   TagDecl *Tag = 0;
01385   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
01386       DS.getTypeSpecType() == DeclSpec::TST_struct ||
01387       DS.getTypeSpecType() == DeclSpec::TST_union ||
01388       DS.getTypeSpecType() == DeclSpec::TST_enum) {
01389     TagD = static_cast<Decl *>(DS.getTypeRep());
01390 
01391     if (!TagD) // We probably had an error
01392       return DeclPtrTy();
01393 
01394     // Note that the above type specs guarantee that the
01395     // type rep is a Decl, whereas in many of the others
01396     // it's a Type.
01397     Tag = dyn_cast<TagDecl>(TagD);
01398   }
01399 
01400   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
01401     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
01402     // or incomplete types shall not be restrict-qualified."
01403     if (TypeQuals & DeclSpec::TQ_restrict)
01404       Diag(DS.getRestrictSpecLoc(),
01405            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
01406            << DS.getSourceRange();
01407   }
01408 
01409   if (DS.isFriendSpecified()) {
01410     // If we're dealing with a class template decl, assume that the
01411     // template routines are handling it.
01412     if (TagD && isa<ClassTemplateDecl>(TagD))
01413       return DeclPtrTy();
01414     return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
01415   }
01416          
01417   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
01418     // If there are attributes in the DeclSpec, apply them to the record.
01419     if (const AttributeList *AL = DS.getAttributes())
01420       ProcessDeclAttributeList(S, Record, AL);
01421     
01422     if (!Record->getDeclName() && Record->isDefinition() &&
01423         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
01424       if (getLangOptions().CPlusPlus ||
01425           Record->getDeclContext()->isRecord())
01426         return BuildAnonymousStructOrUnion(S, DS, Record);
01427 
01428       Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
01429         << DS.getSourceRange();
01430     }
01431 
01432     // Microsoft allows unnamed struct/union fields. Don't complain
01433     // about them.
01434     // FIXME: Should we support Microsoft's extensions in this area?
01435     if (Record->getDeclName() && getLangOptions().Microsoft)
01436       return DeclPtrTy::make(Tag);
01437   }
01438   
01439   if (!DS.isMissingDeclaratorOk() &&
01440       DS.getTypeSpecType() != DeclSpec::TST_error) {
01441     // Warn about typedefs of enums without names, since this is an
01442     // extension in both Microsoft an GNU.
01443     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
01444         Tag && isa<EnumDecl>(Tag)) {
01445       Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
01446         << DS.getSourceRange();
01447       return DeclPtrTy::make(Tag);
01448     }
01449 
01450     Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
01451       << DS.getSourceRange();
01452     return DeclPtrTy();
01453   }
01454 
01455   return DeclPtrTy::make(Tag);
01456 }
01457 
01458 /// We are trying to inject an anonymous member into the given scope;
01459 /// check if there's an existing declaration that can't be overloaded.
01460 ///
01461 /// \return true if this is a forbidden redeclaration
01462 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
01463                                          Scope *S,
01464                                          DeclContext *Owner,
01465                                          DeclarationName Name,
01466                                          SourceLocation NameLoc,
01467                                          unsigned diagnostic) {
01468   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
01469                  Sema::ForRedeclaration);
01470   if (!SemaRef.LookupName(R, S)) return false;
01471 
01472   if (R.getAsSingle<TagDecl>())
01473     return false;
01474 
01475   // Pick a representative declaration.
01476   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
01477   if (PrevDecl && Owner->isRecord()) {
01478     RecordDecl *Record = cast<RecordDecl>(Owner);
01479     if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
01480       return false;
01481   }
01482 
01483   SemaRef.Diag(NameLoc, diagnostic) << Name;
01484   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
01485 
01486   return true;
01487 }
01488 
01489 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
01490 /// anonymous struct or union AnonRecord into the owning context Owner
01491 /// and scope S. This routine will be invoked just after we realize
01492 /// that an unnamed union or struct is actually an anonymous union or
01493 /// struct, e.g.,
01494 ///
01495 /// @code
01496 /// union {
01497 ///   int i;
01498 ///   float f;
01499 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
01500 ///    // f into the surrounding scope.x
01501 /// @endcode
01502 ///
01503 /// This routine is recursive, injecting the names of nested anonymous
01504 /// structs/unions into the owning context and scope as well.
01505 bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
01506                                                RecordDecl *AnonRecord) {
01507   unsigned diagKind
01508     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
01509                             : diag::err_anonymous_struct_member_redecl;
01510 
01511   bool Invalid = false;
01512   for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
01513                                FEnd = AnonRecord->field_end();
01514        F != FEnd; ++F) {
01515     if ((*F)->getDeclName()) {
01516       if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
01517                                        (*F)->getLocation(), diagKind)) {
01518         // C++ [class.union]p2:
01519         //   The names of the members of an anonymous union shall be
01520         //   distinct from the names of any other entity in the
01521         //   scope in which the anonymous union is declared.
01522         Invalid = true;
01523       } else {
01524         // C++ [class.union]p2:
01525         //   For the purpose of name lookup, after the anonymous union
01526         //   definition, the members of the anonymous union are
01527         //   considered to have been defined in the scope in which the
01528         //   anonymous union is declared.
01529         Owner->makeDeclVisibleInContext(*F);
01530         S->AddDecl(DeclPtrTy::make(*F));
01531         IdResolver.AddDecl(*F);
01532       }
01533     } else if (const RecordType *InnerRecordType
01534                  = (*F)->getType()->getAs<RecordType>()) {
01535       RecordDecl *InnerRecord = InnerRecordType->getDecl();
01536       if (InnerRecord->isAnonymousStructOrUnion())
01537         Invalid = Invalid ||
01538           InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
01539     }
01540   }
01541 
01542   return Invalid;
01543 }
01544 
01545 /// ActOnAnonymousStructOrUnion - Handle the declaration of an
01546 /// anonymous structure or union. Anonymous unions are a C++ feature
01547 /// (C++ [class.union]) and a GNU C extension; anonymous structures
01548 /// are a GNU C and GNU C++ extension.
01549 Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
01550                                                   RecordDecl *Record) {
01551   DeclContext *Owner = Record->getDeclContext();
01552 
01553   // Diagnose whether this anonymous struct/union is an extension.
01554   if (Record->isUnion() && !getLangOptions().CPlusPlus)
01555     Diag(Record->getLocation(), diag::ext_anonymous_union);
01556   else if (!Record->isUnion())
01557     Diag(Record->getLocation(), diag::ext_anonymous_struct);
01558 
01559   // C and C++ require different kinds of checks for anonymous
01560   // structs/unions.
01561   bool Invalid = false;
01562   if (getLangOptions().CPlusPlus) {
01563     const char* PrevSpec = 0;
01564     unsigned DiagID;
01565     // C++ [class.union]p3:
01566     //   Anonymous unions declared in a named namespace or in the
01567     //   global namespace shall be declared static.
01568     if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
01569         (isa<TranslationUnitDecl>(Owner) ||
01570          (isa<NamespaceDecl>(Owner) &&
01571           cast<NamespaceDecl>(Owner)->getDeclName()))) {
01572       Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
01573       Invalid = true;
01574 
01575       // Recover by adding 'static'.
01576       DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
01577                              PrevSpec, DiagID);
01578     }
01579     // C++ [class.union]p3:
01580     //   A storage class is not allowed in a declaration of an
01581     //   anonymous union in a class scope.
01582     else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
01583              isa<RecordDecl>(Owner)) {
01584       Diag(DS.getStorageClassSpecLoc(),
01585            diag::err_anonymous_union_with_storage_spec);
01586       Invalid = true;
01587 
01588       // Recover by removing the storage specifier.
01589       DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
01590                              PrevSpec, DiagID);
01591     }
01592 
01593     // C++ [class.union]p2:
01594     //   The member-specification of an anonymous union shall only
01595     //   define non-static data members. [Note: nested types and
01596     //   functions cannot be declared within an anonymous union. ]
01597     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
01598                                  MemEnd = Record->decls_end();
01599          Mem != MemEnd; ++Mem) {
01600       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
01601         // C++ [class.union]p3:
01602         //   An anonymous union shall not have private or protected
01603         //   members (clause 11).
01604         if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
01605           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
01606             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
01607           Invalid = true;
01608         }
01609       } else if ((*Mem)->isImplicit()) {
01610         // Any implicit members are fine.
01611       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
01612         // This is a type that showed up in an
01613         // elaborated-type-specifier inside the anonymous struct or
01614         // union, but which actually declares a type outside of the
01615         // anonymous struct or union. It's okay.
01616       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
01617         if (!MemRecord->isAnonymousStructOrUnion() &&
01618             MemRecord->getDeclName()) {
01619           // This is a nested type declaration.
01620           Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
01621             << (int)Record->isUnion();
01622           Invalid = true;
01623         }
01624       } else {
01625         // We have something that isn't a non-static data
01626         // member. Complain about it.
01627         unsigned DK = diag::err_anonymous_record_bad_member;
01628         if (isa<TypeDecl>(*Mem))
01629           DK = diag::err_anonymous_record_with_type;
01630         else if (isa<FunctionDecl>(*Mem))
01631           DK = diag::err_anonymous_record_with_function;
01632         else if (isa<VarDecl>(*Mem))
01633           DK = diag::err_anonymous_record_with_static;
01634         Diag((*Mem)->getLocation(), DK)
01635             << (int)Record->isUnion();
01636           Invalid = true;
01637       }
01638     }
01639   }
01640 
01641   if (!Record->isUnion() && !Owner->isRecord()) {
01642     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
01643       << (int)getLangOptions().CPlusPlus;
01644     Invalid = true;
01645   }
01646 
01647   // Mock up a declarator.
01648   Declarator Dc(DS, Declarator::TypeNameContext);
01649   TypeSourceInfo *TInfo = 0;
01650   GetTypeForDeclarator(Dc, S, &TInfo);
01651   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
01652 
01653   // Create a declaration for this anonymous struct/union.
01654   NamedDecl *Anon = 0;
01655   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
01656     Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
01657                              /*IdentifierInfo=*/0,
01658                              Context.getTypeDeclType(Record),
01659                              TInfo,
01660                              /*BitWidth=*/0, /*Mutable=*/false);
01661     Anon->setAccess(AS_public);
01662     if (getLangOptions().CPlusPlus)
01663       FieldCollector->Add(cast<FieldDecl>(Anon));
01664   } else {
01665     VarDecl::StorageClass SC;
01666     switch (DS.getStorageClassSpec()) {
01667     default: assert(0 && "Unknown storage class!");
01668     case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
01669     case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
01670     case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
01671     case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
01672     case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
01673     case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
01674     case DeclSpec::SCS_mutable:
01675       // mutable can only appear on non-static class members, so it's always
01676       // an error here
01677       Diag(Record->getLocation(), diag::err_mutable_nonmember);
01678       Invalid = true;
01679       SC = VarDecl::None;
01680       break;
01681     }
01682 
01683     Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
01684                            /*IdentifierInfo=*/0,
01685                            Context.getTypeDeclType(Record),
01686                            TInfo,
01687                            SC);
01688   }
01689   Anon->setImplicit();
01690 
01691   // Add the anonymous struct/union object to the current
01692   // context. We'll be referencing this object when we refer to one of
01693   // its members.
01694   Owner->addDecl(Anon);
01695 
01696   // Inject the members of the anonymous struct/union into the owning
01697   // context and into the identifier resolver chain for name lookup
01698   // purposes.
01699   if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
01700     Invalid = true;
01701 
01702   // Mark this as an anonymous struct/union type. Note that we do not
01703   // do this until after we have already checked and injected the
01704   // members of this anonymous struct/union type, because otherwise
01705   // the members could be injected twice: once by DeclContext when it
01706   // builds its lookup table, and once by
01707   // InjectAnonymousStructOrUnionMembers.
01708   Record->setAnonymousStructOrUnion(true);
01709 
01710   if (Invalid)
01711     Anon->setInvalidDecl();
01712 
01713   return DeclPtrTy::make(Anon);
01714 }
01715 
01716 
01717 /// GetNameForDeclarator - Determine the full declaration name for the
01718 /// given Declarator.
01719 DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
01720   return GetNameFromUnqualifiedId(D.getName());
01721 }
01722 
01723 /// \brief Retrieves the canonicalized name from a parsed unqualified-id.
01724 DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
01725   switch (Name.getKind()) {
01726     case UnqualifiedId::IK_Identifier:
01727       return DeclarationName(Name.Identifier);
01728       
01729     case UnqualifiedId::IK_OperatorFunctionId:
01730       return Context.DeclarationNames.getCXXOperatorName(
01731                                               Name.OperatorFunctionId.Operator);
01732 
01733     case UnqualifiedId::IK_LiteralOperatorId:
01734       return Context.DeclarationNames.getCXXLiteralOperatorName(
01735                                                                Name.Identifier);
01736 
01737     case UnqualifiedId::IK_ConversionFunctionId: {
01738       QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
01739       if (Ty.isNull())
01740         return DeclarationName();
01741       
01742       return Context.DeclarationNames.getCXXConversionFunctionName(
01743                                                   Context.getCanonicalType(Ty));
01744     }
01745       
01746     case UnqualifiedId::IK_ConstructorName: {
01747       QualType Ty = GetTypeFromParser(Name.ConstructorName);
01748       if (Ty.isNull())
01749         return DeclarationName();
01750       
01751       return Context.DeclarationNames.getCXXConstructorName(
01752                                                   Context.getCanonicalType(Ty));
01753     }
01754       
01755     case UnqualifiedId::IK_ConstructorTemplateId: {
01756       // In well-formed code, we can only have a constructor
01757       // template-id that refers to the current context, so go there
01758       // to find the actual type being constructed.
01759       CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
01760       if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
01761         return DeclarationName();
01762 
01763       // Determine the type of the class being constructed.
01764       QualType CurClassType = Context.getTypeDeclType(CurClass);
01765 
01766       // FIXME: Check two things: that the template-id names the same type as
01767       // CurClassType, and that the template-id does not occur when the name
01768       // was qualified.
01769 
01770       return Context.DeclarationNames.getCXXConstructorName(
01771                                        Context.getCanonicalType(CurClassType));
01772     }
01773 
01774     case UnqualifiedId::IK_DestructorName: {
01775       QualType Ty = GetTypeFromParser(Name.DestructorName);
01776       if (Ty.isNull())
01777         return DeclarationName();
01778       
01779       return Context.DeclarationNames.getCXXDestructorName(
01780                                                            Context.getCanonicalType(Ty));
01781     }
01782       
01783     case UnqualifiedId::IK_TemplateId: {
01784       TemplateName TName
01785         = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
01786       return Context.getNameForTemplate(TName);
01787     }
01788   }
01789   
01790   assert(false && "Unknown name kind");
01791   return DeclarationName();  
01792 }
01793 
01794 /// isNearlyMatchingFunction - Determine whether the C++ functions
01795 /// Declaration and Definition are "nearly" matching. This heuristic
01796 /// is used to improve diagnostics in the case where an out-of-line
01797 /// function definition doesn't match any declaration within
01798 /// the class or namespace.
01799 static bool isNearlyMatchingFunction(ASTContext &Context,
01800                                      FunctionDecl *Declaration,
01801                                      FunctionDecl *Definition) {
01802   if (Declaration->param_size() != Definition->param_size())
01803     return false;
01804   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
01805     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
01806     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
01807 
01808     if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
01809                                         DefParamTy.getNonReferenceType()))
01810       return false;
01811   }
01812 
01813   return true;
01814 }
01815 
01816 Sema::DeclPtrTy
01817 Sema::HandleDeclarator(Scope *S, Declarator &D,
01818                        MultiTemplateParamsArg TemplateParamLists,
01819                        bool IsFunctionDefinition) {
01820   DeclarationName Name = GetNameForDeclarator(D);
01821 
01822   // All of these full declarators require an identifier.  If it doesn't have
01823   // one, the ParsedFreeStandingDeclSpec action should be used.
01824   if (!Name) {
01825     if (!D.isInvalidType())  // Reject this if we think it is valid.
01826       Diag(D.getDeclSpec().getSourceRange().getBegin(),
01827            diag::err_declarator_need_ident)
01828         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
01829     return DeclPtrTy();
01830   }
01831 
01832   // The scope passed in may not be a decl scope.  Zip up the scope tree until
01833   // we find one that is.
01834   while ((S->getFlags() & Scope::DeclScope) == 0 ||
01835          (S->getFlags() & Scope::TemplateParamScope) != 0)
01836     S = S->getParent();
01837 
01838   // If this is an out-of-line definition of a member of a class template
01839   // or class template partial specialization, we may need to rebuild the
01840   // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
01841   // for more information.
01842   // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
01843   // handle expressions properly.
01844   DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
01845   if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
01846       isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
01847       (DS.getTypeSpecType() == DeclSpec::TST_typename ||
01848        DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
01849        DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
01850        DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
01851     if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
01852       // FIXME: Preserve type source info.
01853       QualType T = GetTypeFromParser(DS.getTypeRep());
01854 
01855       DeclContext *SavedContext = CurContext;
01856       CurContext = DC;
01857       T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
01858       CurContext = SavedContext;
01859 
01860       if (T.isNull())
01861         return DeclPtrTy();
01862       DS.UpdateTypeRep(T.getAsOpaquePtr());
01863     }
01864   }
01865 
01866   DeclContext *DC;
01867   NamedDecl *New;
01868 
01869   TypeSourceInfo *TInfo = 0;
01870   QualType R = GetTypeForDeclarator(D, S, &TInfo);
01871 
01872   LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
01873                         ForRedeclaration);
01874 
01875   // See if this is a redefinition of a variable in the same scope.
01876   if (D.getCXXScopeSpec().isInvalid()) {
01877     DC = CurContext;
01878     D.setInvalidType();
01879   } else if (!D.getCXXScopeSpec().isSet()) {
01880     bool IsLinkageLookup = false;
01881 
01882     // If the declaration we're planning to build will be a function
01883     // or object with linkage, then look for another declaration with
01884     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
01885     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
01886       /* Do nothing*/;
01887     else if (R->isFunctionType()) {
01888       if (CurContext->isFunctionOrMethod() ||
01889           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
01890         IsLinkageLookup = true;
01891     } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
01892       IsLinkageLookup = true;
01893     else if (CurContext->getLookupContext()->isTranslationUnit() &&
01894              D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
01895       IsLinkageLookup = true;
01896 
01897     if (IsLinkageLookup)
01898       Previous.clear(LookupRedeclarationWithLinkage);
01899 
01900     DC = CurContext;
01901     LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
01902   } else { // Something like "int foo::x;"
01903     DC = computeDeclContext(D.getCXXScopeSpec(), true);
01904 
01905     if (!DC) {
01906       // If we could not compute the declaration context, it's because the
01907       // declaration context is dependent but does not refer to a class,
01908       // class template, or class template partial specialization. Complain
01909       // and return early, to avoid the coming semantic disaster.
01910       Diag(D.getIdentifierLoc(),
01911            diag::err_template_qualified_declarator_no_match)
01912         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
01913         << D.getCXXScopeSpec().getRange();
01914       return DeclPtrTy();
01915     }
01916 
01917     if (!DC->isDependentContext() && 
01918         RequireCompleteDeclContext(D.getCXXScopeSpec()))
01919       return DeclPtrTy();
01920 
01921     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
01922       Diag(D.getIdentifierLoc(),
01923            diag::err_member_def_undefined_record)
01924         << Name << DC << D.getCXXScopeSpec().getRange();
01925       D.setInvalidType();
01926     }
01927     
01928     LookupQualifiedName(Previous, DC);
01929 
01930     // Don't consider using declarations as previous declarations for
01931     // out-of-line members.
01932     RemoveUsingDecls(Previous);
01933 
01934     // C++ 7.3.1.2p2:
01935     // Members (including explicit specializations of templates) of a named
01936     // namespace can also be defined outside that namespace by explicit
01937     // qualification of the name being defined, provided that the entity being
01938     // defined was already declared in the namespace and the definition appears
01939     // after the point of declaration in a namespace that encloses the
01940     // declarations namespace.
01941     //
01942     // Note that we only check the context at this point. We don't yet
01943     // have enough information to make sure that PrevDecl is actually
01944     // the declaration we want to match. For example, given:
01945     //
01946     //   class X {
01947     //     void f();
01948     //     void f(float);
01949     //   };
01950     //
01951     //   void X::f(int) { } // ill-formed
01952     //
01953     // In this case, PrevDecl will point to the overload set
01954     // containing the two f's declared in X, but neither of them
01955     // matches.
01956 
01957     // First check whether we named the global scope.
01958     if (isa<TranslationUnitDecl>(DC)) {
01959       Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
01960         << Name << D.getCXXScopeSpec().getRange();
01961     } else {
01962       DeclContext *Cur = CurContext;
01963       while (isa<LinkageSpecDecl>(Cur))
01964         Cur = Cur->getParent();
01965       if (!Cur->Encloses(DC)) {
01966         // The qualifying scope doesn't enclose the original declaration.
01967         // Emit diagnostic based on current scope.
01968         SourceLocation L = D.getIdentifierLoc();
01969         SourceRange R = D.getCXXScopeSpec().getRange();
01970         if (isa<FunctionDecl>(Cur))
01971           Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
01972         else
01973           Diag(L, diag::err_invalid_declarator_scope)
01974             << Name << cast<NamedDecl>(DC) << R;
01975         D.setInvalidType();
01976       }
01977     }
01978   }
01979 
01980   if (Previous.isSingleResult() &&
01981       Previous.getFoundDecl()->isTemplateParameter()) {
01982     // Maybe we will complain about the shadowed template parameter.
01983     if (!D.isInvalidType())
01984       if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
01985                                           Previous.getFoundDecl()))
01986         D.setInvalidType();
01987 
01988     // Just pretend that we didn't see the previous declaration.
01989     Previous.clear();
01990   }
01991 
01992   // In C++, the previous declaration we find might be a tag type
01993   // (class or enum). In this case, the new declaration will hide the
01994   // tag type. Note that this does does not apply if we're declaring a
01995   // typedef (C++ [dcl.typedef]p4).
01996   if (Previous.isSingleTagDecl() &&
01997       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
01998     Previous.clear();
01999 
02000   bool Redeclaration = false;
02001   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
02002     if (TemplateParamLists.size()) {
02003       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
02004       return DeclPtrTy();
02005     }
02006 
02007     New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
02008   } else if (R->isFunctionType()) {
02009     New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
02010                                   move(TemplateParamLists),
02011                                   IsFunctionDefinition, Redeclaration);
02012   } else {
02013     New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
02014                                   move(TemplateParamLists),
02015                                   Redeclaration);
02016   }
02017 
02018   if (New == 0)
02019     return DeclPtrTy();
02020 
02021   // If this has an identifier and is not an invalid redeclaration or 
02022   // function template specialization, add it to the scope stack.
02023   if (Name && !(Redeclaration && New->isInvalidDecl()))
02024     PushOnScopeChains(New, S);
02025 
02026   return DeclPtrTy::make(New);
02027 }
02028 
02029 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
02030 /// types into constant array types in certain situations which would otherwise
02031 /// be errors (for GCC compatibility).
02032 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
02033                                                     ASTContext &Context,
02034                                                     bool &SizeIsNegative) {
02035   // This method tries to turn a variable array into a constant
02036   // array even when the size isn't an ICE.  This is necessary
02037   // for compatibility with code that depends on gcc's buggy
02038   // constant expression folding, like struct {char x[(int)(char*)2];}
02039   SizeIsNegative = false;
02040 
02041   QualifierCollector Qs;
02042   const Type *Ty = Qs.strip(T);
02043 
02044   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
02045     QualType Pointee = PTy->getPointeeType();
02046     QualType FixedType =
02047         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
02048     if (FixedType.isNull()) return FixedType;
02049     FixedType = Context.getPointerType(FixedType);
02050     return Qs.apply(FixedType);
02051   }
02052 
02053   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
02054   if (!VLATy)
02055     return QualType();
02056   // FIXME: We should probably handle this case
02057   if (VLATy->getElementType()->isVariablyModifiedType())
02058     return QualType();
02059 
02060   Expr::EvalResult EvalResult;
02061   if (!VLATy->getSizeExpr() ||
02062       !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
02063       !EvalResult.Val.isInt())
02064     return QualType();
02065 
02066   llvm::APSInt &Res = EvalResult.Val.getInt();
02067   if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
02068     // TODO: preserve the size expression in declarator info
02069     return Context.getConstantArrayType(VLATy->getElementType(),
02070                                         Res, ArrayType::Normal, 0);
02071   }
02072 
02073   SizeIsNegative = true;
02074   return QualType();
02075 }
02076 
02077 /// \brief Register the given locally-scoped external C declaration so
02078 /// that it can be found later for redeclarations
02079 void
02080 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
02081                                        const LookupResult &Previous,
02082                                        Scope *S) {
02083   assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
02084          "Decl is not a locally-scoped decl!");
02085   // Note that we have a locally-scoped external with this name.
02086   LocallyScopedExternalDecls[ND->getDeclName()] = ND;
02087 
02088   if (!Previous.isSingleResult())
02089     return;
02090 
02091   NamedDecl *PrevDecl = Previous.getFoundDecl();
02092 
02093   // If there was a previous declaration of this variable, it may be
02094   // in our identifier chain. Update the identifier chain with the new
02095   // declaration.
02096   if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
02097     // The previous declaration was found on the identifer resolver
02098     // chain, so remove it from its scope.
02099     while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
02100       S = S->getParent();
02101 
02102     if (S)
02103       S->RemoveDecl(DeclPtrTy::make(PrevDecl));
02104   }
02105 }
02106 
02107 /// \brief Diagnose function specifiers on a declaration of an identifier that
02108 /// does not identify a function.
02109 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
02110   // FIXME: We should probably indicate the identifier in question to avoid
02111   // confusion for constructs like "inline int a(), b;"
02112   if (D.getDeclSpec().isInlineSpecified())
02113     Diag(D.getDeclSpec().getInlineSpecLoc(),
02114          diag::err_inline_non_function);
02115 
02116   if (D.getDeclSpec().isVirtualSpecified())
02117     Diag(D.getDeclSpec().getVirtualSpecLoc(),
02118          diag::err_virtual_non_function);
02119 
02120   if (D.getDeclSpec().isExplicitSpecified())
02121     Diag(D.getDeclSpec().getExplicitSpecLoc(),
02122          diag::err_explicit_non_function);
02123 }
02124 
02125 NamedDecl*
02126 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
02127                              QualType R,  TypeSourceInfo *TInfo,
02128                              LookupResult &Previous, bool &Redeclaration) {
02129   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
02130   if (D.getCXXScopeSpec().isSet()) {
02131     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
02132       << D.getCXXScopeSpec().getRange();
02133     D.setInvalidType();
02134     // Pretend we didn't see the scope specifier.
02135     DC = 0;
02136   }
02137 
02138   if (getLangOptions().CPlusPlus) {
02139     // Check that there are no default arguments (C++ only).
02140     CheckExtraCXXDefaultArguments(D);
02141   }
02142 
02143   DiagnoseFunctionSpecifiers(D);
02144 
02145   if (D.getDeclSpec().isThreadSpecified())
02146     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
02147 
02148   TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
02149   if (!NewTD) return 0;
02150 
02151   // Handle attributes prior to checking for duplicates in MergeVarDecl
02152   ProcessDeclAttributes(S, NewTD, D);
02153 
02154   // Merge the decl with the existing one if appropriate. If the decl is
02155   // in an outer scope, it isn't the same thing.
02156   FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
02157   if (!Previous.empty()) {
02158     Redeclaration = true;
02159     MergeTypeDefDecl(NewTD, Previous);
02160   }
02161 
02162   // C99 6.7.7p2: If a typedef name specifies a variably modified type
02163   // then it shall have block scope.
02164   QualType T = NewTD->getUnderlyingType();
02165   if (T->isVariablyModifiedType()) {
02166     FunctionNeedsScopeChecking() = true;
02167 
02168     if (S->getFnParent() == 0) {
02169       bool SizeIsNegative;
02170       QualType FixedTy =
02171           TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
02172       if (!FixedTy.isNull()) {
02173         Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
02174         NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
02175       } else {
02176         if (SizeIsNegative)
02177           Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
02178         else if (T->isVariableArrayType())
02179           Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
02180         else
02181           Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
02182         NewTD->setInvalidDecl();
02183       }
02184     }
02185   }
02186 
02187   // If this is the C FILE type, notify the AST context.
02188   if (IdentifierInfo *II = NewTD->getIdentifier())
02189     if (!NewTD->isInvalidDecl() &&
02190         NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
02191       if (II->isStr("FILE"))
02192         Context.setFILEDecl(NewTD);
02193       else if (II->isStr("jmp_buf"))
02194         Context.setjmp_bufDecl(NewTD);
02195       else if (II->isStr("sigjmp_buf"))
02196         Context.setsigjmp_bufDecl(NewTD);
02197     }
02198 
02199   return NewTD;
02200 }
02201 
02202 /// \brief Determines whether the given declaration is an out-of-scope
02203 /// previous declaration.
02204 ///
02205 /// This routine should be invoked when name lookup has found a
02206 /// previous declaration (PrevDecl) that is not in the scope where a
02207 /// new declaration by the same name is being introduced. If the new
02208 /// declaration occurs in a local scope, previous declarations with
02209 /// linkage may still be considered previous declarations (C99
02210 /// 6.2.2p4-5, C++ [basic.link]p6).
02211 ///
02212 /// \param PrevDecl the previous declaration found by name
02213 /// lookup
02214 ///
02215 /// \param DC the context in which the new declaration is being
02216 /// declared.
02217 ///
02218 /// \returns true if PrevDecl is an out-of-scope previous declaration
02219 /// for a new delcaration with the same name.
02220 static bool
02221 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
02222                                 ASTContext &Context) {
02223   if (!PrevDecl)
02224     return 0;
02225 
02226   if (!PrevDecl->hasLinkage())
02227     return false;
02228 
02229   if (Context.getLangOptions().CPlusPlus) {
02230     // C++ [basic.link]p6:
02231     //   If there is a visible declaration of an entity with linkage
02232     //   having the same name and type, ignoring entities declared
02233     //   outside the innermost enclosing namespace scope, the block
02234     //   scope declaration declares that same entity and receives the
02235     //   linkage of the previous declaration.
02236     DeclContext *OuterContext = DC->getLookupContext();
02237     if (!OuterContext->isFunctionOrMethod())
02238       // This rule only applies to block-scope declarations.
02239       return false;
02240     else {
02241       DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
02242       if (PrevOuterContext->isRecord())
02243         // We found a member function: ignore it.
02244         return false;
02245       else {
02246         // Find the innermost enclosing namespace for the new and
02247         // previous declarations.
02248         while (!OuterContext->isFileContext())
02249           OuterContext = OuterContext->getParent();
02250         while (!PrevOuterContext->isFileContext())
02251           PrevOuterContext = PrevOuterContext->getParent();
02252 
02253         // The previous declaration is in a different namespace, so it
02254         // isn't the same function.
02255         if (OuterContext->getPrimaryContext() !=
02256             PrevOuterContext->getPrimaryContext())
02257           return false;
02258       }
02259     }
02260   }
02261 
02262   return true;
02263 }
02264 
02265 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
02266   CXXScopeSpec &SS = D.getCXXScopeSpec();
02267   if (!SS.isSet()) return;
02268   DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
02269                        SS.getRange());
02270 }
02271 
02272 NamedDecl*
02273 Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
02274                               QualType R, TypeSourceInfo *TInfo,
02275                               LookupResult &Previous,
02276                               MultiTemplateParamsArg TemplateParamLists,
02277                               bool &Redeclaration) {
02278   DeclarationName Name = GetNameForDeclarator(D);
02279 
02280   // Check that there are no default arguments (C++ only).
02281   if (getLangOptions().CPlusPlus)
02282     CheckExtraCXXDefaultArguments(D);
02283 
02284   VarDecl *NewVD;
02285   VarDecl::StorageClass SC;
02286   switch (D.getDeclSpec().getStorageClassSpec()) {
02287   default: assert(0 && "Unknown storage class!");
02288   case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
02289   case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
02290   case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
02291   case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
02292   case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
02293   case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
02294   case DeclSpec::SCS_mutable:
02295     // mutable can only appear on non-static class members, so it's always
02296     // an error here
02297     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
02298     D.setInvalidType();
02299     SC = VarDecl::None;
02300     break;
02301   }
02302 
02303   IdentifierInfo *II = Name.getAsIdentifierInfo();
02304   if (!II) {
02305     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
02306       << Name.getAsString();
02307     return 0;
02308   }
02309 
02310   DiagnoseFunctionSpecifiers(D);
02311 
02312   if (!DC->isRecord() && S->getFnParent() == 0) {
02313     // C99 6.9p2: The storage-class specifiers auto and register shall not
02314     // appear in the declaration specifiers in an external declaration.
02315     if (SC == VarDecl::Auto || SC == VarDecl::Register) {
02316 
02317       // If this is a register variable with an asm label specified, then this
02318       // is a GNU extension.
02319       if (SC == VarDecl::Register && D.getAsmLabel())
02320         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
02321       else
02322         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
02323       D.setInvalidType();
02324     }
02325   }
02326   if (DC->isRecord() && !CurContext->isRecord()) {
02327     // This is an out-of-line definition of a static data member.
02328     if (SC == VarDecl::Static) {
02329       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
02330            diag::err_static_out_of_line)
02331         << CodeModificationHint::CreateRemoval(
02332                                       D.getDeclSpec().getStorageClassSpecLoc());
02333     } else if (SC == VarDecl::None)
02334       SC = VarDecl::Static;
02335   }
02336   if (SC == VarDecl::Static) {
02337     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
02338       if (RD->isLocalClass())
02339         Diag(D.getIdentifierLoc(),
02340              diag::err_static_data_member_not_allowed_in_local_class)
02341           << Name << RD->getDeclName();
02342     }
02343   }
02344 
02345   // Match up the template parameter lists with the scope specifier, then
02346   // determine whether we have a template or a template specialization.
02347   bool isExplicitSpecialization = false;
02348   if (TemplateParameterList *TemplateParams
02349         = MatchTemplateParametersToScopeSpecifier(
02350                                   D.getDeclSpec().getSourceRange().getBegin(),
02351                                                   D.getCXXScopeSpec(),
02352                         (TemplateParameterList**)TemplateParamLists.get(),
02353                                                    TemplateParamLists.size(),
02354                                                   isExplicitSpecialization)) {
02355     if (TemplateParams->size() > 0) {
02356       // There is no such thing as a variable template.
02357       Diag(D.getIdentifierLoc(), diag::err_template_variable)
02358         << II
02359         << SourceRange(TemplateParams->getTemplateLoc(),
02360                        TemplateParams->getRAngleLoc());
02361       return 0;
02362     } else {
02363       // There is an extraneous 'template<>' for this variable. Complain
02364       // about it, but allow the declaration of the variable.
02365       Diag(TemplateParams->getTemplateLoc(),
02366            diag::err_template_variable_noparams)
02367         << II
02368         << SourceRange(TemplateParams->getTemplateLoc(),
02369                        TemplateParams->getRAngleLoc());
02370       
02371       isExplicitSpecialization = true;
02372     }
02373   }
02374 
02375   NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
02376                           II, R, TInfo, SC);
02377 
02378   if (D.isInvalidType())
02379     NewVD->setInvalidDecl();
02380 
02381   SetNestedNameSpecifier(NewVD, D);
02382 
02383   if (D.getDeclSpec().isThreadSpecified()) {
02384     if (NewVD->hasLocalStorage())
02385       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
02386     else if (!Context.Target.isTLSSupported())
02387       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
02388     else
02389       NewVD->setThreadSpecified(true);
02390   }
02391 
02392   // Set the lexical context. If the declarator has a C++ scope specifier, the
02393   // lexical context will be different from the semantic context.
02394   NewVD->setLexicalDeclContext(CurContext);
02395 
02396   // Handle attributes prior to checking for duplicates in MergeVarDecl
02397   ProcessDeclAttributes(S, NewVD, D);
02398 
02399   // Handle GNU asm-label extension (encoded as an attribute).
02400   if (Expr *E = (Expr*) D.getAsmLabel()) {
02401     // The parser guarantees this is a string.
02402     StringLiteral *SE = cast<StringLiteral>(E);
02403     NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
02404   }
02405 
02406   // Don't consider existing declarations that are in a different
02407   // scope and are out-of-semantic-context declarations (if the new
02408   // declaration has linkage).
02409   FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
02410   
02411   // Merge the decl with the existing one if appropriate.
02412   if (!Previous.empty()) {
02413     if (Previous.isSingleResult() &&
02414         isa<FieldDecl>(Previous.getFoundDecl()) &&
02415         D.getCXXScopeSpec().isSet()) {
02416       // The user tried to define a non-static data member
02417       // out-of-line (C++ [dcl.meaning]p1).
02418       Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
02419         << D.getCXXScopeSpec().getRange();
02420       Previous.clear();
02421       NewVD->setInvalidDecl();
02422     }
02423   } else if (D.getCXXScopeSpec().isSet()) {
02424     // No previous declaration in the qualifying scope.
02425     Diag(D.getIdentifierLoc(), diag::err_no_member)
02426       << Name << computeDeclContext(D.getCXXScopeSpec(), true)
02427       << D.getCXXScopeSpec().getRange();
02428     NewVD->setInvalidDecl();
02429   }
02430 
02431   CheckVariableDeclaration(NewVD, Previous, Redeclaration);
02432 
02433   // This is an explicit specialization of a static data member. Check it.
02434   if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
02435       CheckMemberSpecialization(NewVD, Previous))
02436     NewVD->setInvalidDecl();
02437 
02438   // attributes declared post-definition are currently ignored
02439   if (Previous.isSingleResult()) {
02440     VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
02441     if (Def && (Def = Def->getDefinition()) &&
02442         Def != NewVD && D.hasAttributes()) {
02443       Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
02444       Diag(Def->getLocation(), diag::note_previous_definition);
02445     }
02446   }
02447 
02448   // If this is a locally-scoped extern C variable, update the map of
02449   // such variables.
02450   if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
02451       !NewVD->isInvalidDecl())
02452     RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
02453 
02454   return NewVD;
02455 }
02456 
02457 /// \brief Perform semantic checking on a newly-created variable
02458 /// declaration.
02459 ///
02460 /// This routine performs all of the type-checking required for a
02461 /// variable declaration once it has been built. It is used both to
02462 /// check variables after they have been parsed and their declarators
02463 /// have been translated into a declaration, and to check variables
02464 /// that have been instantiated from a template.
02465 ///
02466 /// Sets NewVD->isInvalidDecl() if an error was encountered.
02467 void Sema::CheckVariableDeclaration(VarDecl *NewVD,
02468                                     LookupResult &Previous,
02469                                     bool &Redeclaration) {
02470   // If the decl is already known invalid, don't check it.
02471   if (NewVD->isInvalidDecl())
02472     return;
02473 
02474   QualType T = NewVD->getType();
02475 
02476   if (T->isObjCInterfaceType()) {
02477     Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
02478     return NewVD->setInvalidDecl();
02479   }
02480 
02481   // Emit an error if an address space was applied to decl with local storage.
02482   // This includes arrays of objects with address space qualifiers, but not
02483   // automatic variables that point to other address spaces.
02484   // ISO/IEC TR 18037 S5.1.2
02485   if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
02486     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
02487     return NewVD->setInvalidDecl();
02488   }
02489 
02490   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
02491       && !NewVD->hasAttr<BlocksAttr>())
02492     Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
02493 
02494   bool isVM = T->isVariablyModifiedType();
02495   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
02496       NewVD->hasAttr<BlocksAttr>() ||
02497       // FIXME: We need to diagnose jumps passed initialized variables in C++.
02498       // However, this turns on the scope checker for everything with a variable
02499       // which may impact compile time.  See if we can find a better solution
02500       // to this, perhaps only checking functions that contain gotos in C++?
02501       (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
02502     FunctionNeedsScopeChecking() = true;
02503 
02504   if ((isVM && NewVD->hasLinkage()) ||
02505       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
02506     bool SizeIsNegative;
02507     QualType FixedTy =
02508         TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
02509 
02510     if (FixedTy.isNull() && T->isVariableArrayType()) {
02511       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
02512       // FIXME: This won't give the correct result for
02513       // int a[10][n];
02514       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
02515 
02516       if (NewVD->isFileVarDecl())
02517         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
02518         << SizeRange;
02519       else if (NewVD->getStorageClass() == VarDecl::Static)
02520         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
02521         << SizeRange;
02522       else
02523         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
02524         << SizeRange;
02525       return NewVD->setInvalidDecl();
02526     }
02527 
02528     if (FixedTy.isNull()) {
02529       if (NewVD->isFileVarDecl())
02530         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
02531       else
02532         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
02533       return NewVD->setInvalidDecl();
02534     }
02535 
02536     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
02537     NewVD->setType(FixedTy);
02538   }
02539 
02540   if (Previous.empty() && NewVD->isExternC()) {
02541     // Since we did not find anything by this name and we're declaring
02542     // an extern "C" variable, look for a non-visible extern "C"
02543     // declaration with the same name.
02544     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
02545       = LocallyScopedExternalDecls.find(NewVD->getDeclName());
02546     if (Pos != LocallyScopedExternalDecls.end())
02547       Previous.addDecl(Pos->second);
02548   }
02549 
02550   if (T->isVoidType() && !NewVD->hasExternalStorage()) {
02551     Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
02552       << T;
02553     return NewVD->setInvalidDecl();
02554   }
02555 
02556   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
02557     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
02558     return NewVD->setInvalidDecl();
02559   }
02560 
02561   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
02562     Diag(NewVD->getLocation(), diag::err_block_on_vm);
02563     return NewVD->setInvalidDecl();
02564   }
02565 
02566   if (!Previous.empty()) {
02567     Redeclaration = true;
02568     MergeVarDecl(NewVD, Previous);
02569   }
02570 }
02571 
02572 /// \brief Data used with FindOverriddenMethod
02573 struct FindOverriddenMethodData {
02574   Sema *S;
02575   CXXMethodDecl *Method;
02576 };
02577 
02578 /// \brief Member lookup function that determines whether a given C++
02579 /// method overrides a method in a base class, to be used with
02580 /// CXXRecordDecl::lookupInBases().
02581 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
02582                                  CXXBasePath &Path,
02583                                  void *UserData) {
02584   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
02585 
02586   FindOverriddenMethodData *Data 
02587     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
02588   
02589   DeclarationName Name = Data->Method->getDeclName();
02590   
02591   // FIXME: Do we care about other names here too?
02592   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
02593     // We really want to find the base class constructor here.
02594     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
02595     CanQualType CT = Data->S->Context.getCanonicalType(T);
02596     
02597     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
02598   }    
02599   
02600   for (Path.Decls = BaseRecord->lookup(Name);
02601        Path.Decls.first != Path.Decls.second;
02602        ++Path.Decls.first) {
02603     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
02604       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
02605         return true;
02606     }
02607   }
02608   
02609   return false;
02610 }
02611 
02612 /// AddOverriddenMethods - See if a method overrides any in the base classes,
02613 /// and if so, check that it's a valid override and remember it.
02614 void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
02615   // Look for virtual methods in base classes that this method might override.
02616   CXXBasePaths Paths;
02617   FindOverriddenMethodData Data;
02618   Data.Method = MD;
02619   Data.S = this;
02620   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
02621     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
02622          E = Paths.found_decls_end(); I != E; ++I) {
02623       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
02624         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
02625             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
02626             !CheckOverridingFunctionAttributes(MD, OldMD))
02627           MD->addOverriddenMethod(OldMD->getCanonicalDecl());
02628       }
02629     }
02630   }
02631 }
02632 
02633 NamedDecl*
02634 Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
02635                               QualType R, TypeSourceInfo *TInfo,
02636                               LookupResult &Previous,
02637                               MultiTemplateParamsArg TemplateParamLists,
02638                               bool IsFunctionDefinition, bool &Redeclaration) {
02639   assert(R.getTypePtr()->isFunctionType());
02640 
02641   DeclarationName Name = GetNameForDeclarator(D);
02642   FunctionDecl::StorageClass SC = FunctionDecl::None;
02643   switch (D.getDeclSpec().getStorageClassSpec()) {
02644   default: assert(0 && "Unknown storage class!");
02645   case DeclSpec::SCS_auto:
02646   case DeclSpec::SCS_register:
02647   case DeclSpec::SCS_mutable:
02648     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
02649          diag::err_typecheck_sclass_func);
02650     D.setInvalidType();
02651     break;
02652   case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
02653   case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
02654   case DeclSpec::SCS_static: {
02655     if (CurContext->getLookupContext()->isFunctionOrMethod()) {
02656       // C99 6.7.1p5:
02657       //   The declaration of an identifier for a function that has
02658       //   block scope shall have no explicit storage-class specifier
02659       //   other than extern
02660       // See also (C++ [dcl.stc]p4).
02661       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
02662            diag::err_static_block_func);
02663       SC = FunctionDecl::None;
02664     } else
02665       SC = FunctionDecl::Static;
02666     break;
02667   }
02668   case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
02669   }
02670 
02671   if (D.getDeclSpec().isThreadSpecified())
02672     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
02673 
02674   bool isFriend = D.getDeclSpec().isFriendSpecified();
02675   bool isInline = D.getDeclSpec().isInlineSpecified();
02676   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
02677   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
02678 
02679   // Check that the return type is not an abstract class type.
02680   // For record types, this is done by the AbstractClassUsageDiagnoser once
02681   // the class has been completely parsed.
02682   if (!DC->isRecord() &&
02683       RequireNonAbstractType(D.getIdentifierLoc(),
02684                              R->getAs<FunctionType>()->getResultType(),
02685                              diag::err_abstract_type_in_decl,
02686                              AbstractReturnType))
02687     D.setInvalidType();
02688 
02689   // Do not allow returning a objc interface by-value.
02690   if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
02691     Diag(D.getIdentifierLoc(),
02692          diag::err_object_cannot_be_passed_returned_by_value) << 0
02693       << R->getAs<FunctionType>()->getResultType();
02694     D.setInvalidType();
02695   }
02696 
02697   bool isVirtualOkay = false;
02698   FunctionDecl *NewFD;
02699 
02700   if (isFriend) {
02701     // C++ [class.friend]p5
02702     //   A function can be defined in a friend declaration of a
02703     //   class . . . . Such a function is implicitly inline.
02704     isInline |= IsFunctionDefinition;
02705   }
02706 
02707   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
02708     // This is a C++ constructor declaration.
02709     assert(DC->isRecord() &&
02710            "Constructors can only be declared in a member context");
02711 
02712     R = CheckConstructorDeclarator(D, R, SC);
02713 
02714     // Create the new declaration
02715     NewFD = CXXConstructorDecl::Create(Context,
02716                                        cast<CXXRecordDecl>(DC),
02717                                        D.getIdentifierLoc(), Name, R, TInfo,
02718                                        isExplicit, isInline,
02719                                        /*isImplicitlyDeclared=*/false);
02720   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
02721     // This is a C++ destructor declaration.
02722     if (DC->isRecord()) {
02723       R = CheckDestructorDeclarator(D, SC);
02724 
02725       NewFD = CXXDestructorDecl::Create(Context,
02726                                         cast<CXXRecordDecl>(DC),
02727                                         D.getIdentifierLoc(), Name, R,
02728                                         isInline,
02729                                         /*isImplicitlyDeclared=*/false);
02730       NewFD->setTypeSourceInfo(TInfo);
02731 
02732       isVirtualOkay = true;
02733     } else {
02734       Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
02735 
02736       // Create a FunctionDecl to satisfy the function definition parsing
02737       // code path.
02738       NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
02739                                    Name, R, TInfo, SC, isInline,
02740                                    /*hasPrototype=*/true);
02741       D.setInvalidType();
02742     }
02743   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
02744     if (!DC->isRecord()) {
02745       Diag(D.getIdentifierLoc(),
02746            diag::err_conv_function_not_member);
02747       return 0;
02748     }
02749 
02750     CheckConversionDeclarator(D, R, SC);
02751     NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
02752                                       D.getIdentifierLoc(), Name, R, TInfo,
02753                                       isInline, isExplicit);
02754 
02755     isVirtualOkay = true;
02756   } else if (DC->isRecord()) {
02757     // If the of the function is the same as the name of the record, then this
02758     // must be an invalid constructor that has a return type.
02759     // (The parser checks for a return type and makes the declarator a
02760     // constructor if it has no return type).
02761     // must have an invalid constructor that has a return type
02762     if (Name.getAsIdentifierInfo() &&
02763         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
02764       Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
02765         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
02766         << SourceRange(D.getIdentifierLoc());
02767       return 0;
02768     }
02769 
02770     bool isStatic = SC == FunctionDecl::Static;
02771     
02772     // [class.free]p1:
02773     // Any allocation function for a class T is a static member
02774     // (even if not explicitly declared static).
02775     if (Name.getCXXOverloadedOperator() == OO_New ||
02776         Name.getCXXOverloadedOperator() == OO_Array_New)
02777       isStatic = true;
02778 
02779     // [class.free]p6 Any deallocation function for a class X is a static member
02780     // (even if not explicitly declared static).
02781     if (Name.getCXXOverloadedOperator() == OO_Delete ||
02782         Name.getCXXOverloadedOperator() == OO_Array_Delete)
02783       isStatic = true;
02784     
02785     // This is a C++ method declaration.
02786     NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
02787                                   D.getIdentifierLoc(), Name, R, TInfo,
02788                                   isStatic, isInline);
02789 
02790     isVirtualOkay = !isStatic;
02791   } else {
02792     // Determine whether the function was written with a
02793     // prototype. This true when:
02794     //   - we're in C++ (where every function has a prototype),
02795     //   - there is a prototype in the declarator, or
02796     //   - the type R of the function is some kind of typedef or other reference
02797     //     to a type name (which eventually refers to a function type).
02798     bool HasPrototype =
02799        getLangOptions().CPlusPlus ||
02800        (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
02801        (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
02802 
02803     NewFD = FunctionDecl::Create(Context, DC,
02804                                  D.getIdentifierLoc(),
02805                                  Name, R, TInfo, SC, isInline, HasPrototype);
02806   }
02807 
02808   if (D.isInvalidType())
02809     NewFD->setInvalidDecl();
02810 
02811   SetNestedNameSpecifier(NewFD, D);
02812 
02813   // Set the lexical context. If the declarator has a C++
02814   // scope specifier, or is the object of a friend declaration, the
02815   // lexical context will be different from the semantic context.
02816   NewFD->setLexicalDeclContext(CurContext);
02817 
02818   // Match up the template parameter lists with the scope specifier, then
02819   // determine whether we have a template or a template specialization.
02820   FunctionTemplateDecl *FunctionTemplate = 0;
02821   bool isExplicitSpecialization = false;
02822   bool isFunctionTemplateSpecialization = false;
02823   if (TemplateParameterList *TemplateParams
02824         = MatchTemplateParametersToScopeSpecifier(
02825                                   D.getDeclSpec().getSourceRange().getBegin(),
02826                                   D.getCXXScopeSpec(),
02827                            (TemplateParameterList**)TemplateParamLists.get(),
02828                                                   TemplateParamLists.size(),
02829                                                   isExplicitSpecialization)) {
02830     if (TemplateParams->size() > 0) {
02831       // This is a function template
02832 
02833       // Check that we can declare a template here.
02834       if (CheckTemplateDeclScope(S, TemplateParams))
02835         return 0;
02836 
02837       FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
02838                                                       NewFD->getLocation(),
02839                                                       Name, TemplateParams,
02840                                                       NewFD);
02841       FunctionTemplate->setLexicalDeclContext(CurContext);
02842       NewFD->setDescribedFunctionTemplate(FunctionTemplate);
02843     } else {
02844       // This is a function template specialization.
02845       isFunctionTemplateSpecialization = true;
02846     }
02847 
02848     // FIXME: Free this memory properly.
02849     TemplateParamLists.release();
02850   }
02851   
02852   // C++ [dcl.fct.spec]p5:
02853   //   The virtual specifier shall only be used in declarations of
02854   //   nonstatic class member functions that appear within a
02855   //   member-specification of a class declaration; see 10.3.
02856   //
02857   if (isVirtual && !NewFD->isInvalidDecl()) {
02858     if (!isVirtualOkay) {
02859        Diag(D.getDeclSpec().getVirtualSpecLoc(),
02860            diag::err_virtual_non_function);
02861     } else if (!CurContext->isRecord()) {
02862       // 'virtual' was specified outside of the class.
02863       Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
02864         << CodeModificationHint::CreateRemoval(
02865                                            D.getDeclSpec().getVirtualSpecLoc());
02866     } else {
02867       // Okay: Add virtual to the method.
02868       CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
02869       CurClass->setMethodAsVirtual(NewFD);
02870     }
02871   }
02872 
02873   // C++ [dcl.fct.spec]p6:
02874   //  The explicit specifier shall be used only in the declaration of a
02875   //  constructor or conversion function within its class definition; see 12.3.1
02876   //  and 12.3.2.
02877   if (isExplicit && !NewFD->isInvalidDecl()) {
02878     if (!CurContext->isRecord()) {
02879       // 'explicit' was specified outside of the class.
02880       Diag(D.getDeclSpec().getExplicitSpecLoc(), 
02881            diag::err_explicit_out_of_class)
02882         << CodeModificationHint::CreateRemoval(
02883                                           D.getDeclSpec().getExplicitSpecLoc());
02884     } else if (!isa<CXXConstructorDecl>(NewFD) && 
02885                !isa<CXXConversionDecl>(NewFD)) {
02886       // 'explicit' was specified on a function that wasn't a constructor
02887       // or conversion function.
02888       Diag(D.getDeclSpec().getExplicitSpecLoc(),
02889            diag::err_explicit_non_ctor_or_conv_function)
02890         << CodeModificationHint::CreateRemoval(
02891                                           D.getDeclSpec().getExplicitSpecLoc());
02892     }      
02893   }
02894 
02895   // Filter out previous declarations that don't match the scope.
02896   FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
02897 
02898   if (isFriend) {
02899     // DC is the namespace in which the function is being declared.
02900     assert((DC->isFileContext() || !Previous.empty()) &&
02901            "previously-undeclared friend function being created "
02902            "in a non-namespace context");
02903 
02904     if (FunctionTemplate) {
02905       FunctionTemplate->setObjectOfFriendDecl(
02906                                    /* PreviouslyDeclared= */ !Previous.empty());
02907       FunctionTemplate->setAccess(AS_public);
02908     }
02909     else
02910       NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
02911 
02912     NewFD->setAccess(AS_public);
02913   }
02914 
02915   if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
02916       !CurContext->isRecord()) {
02917     // C++ [class.static]p1:
02918     //   A data or function member of a class may be declared static
02919     //   in a class definition, in which case it is a static member of
02920     //   the class.
02921 
02922     // Complain about the 'static' specifier if it's on an out-of-line
02923     // member function definition.
02924     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
02925          diag::err_static_out_of_line)
02926       << CodeModificationHint::CreateRemoval(
02927                                       D.getDeclSpec().getStorageClassSpecLoc());
02928   }
02929 
02930   // Handle GNU asm-label extension (encoded as an attribute).
02931   if (Expr *E = (Expr*) D.getAsmLabel()) {
02932     // The parser guarantees this is a string.
02933     StringLiteral *SE = cast<StringLiteral>(E);
02934     NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
02935   }
02936 
02937   // Copy the parameter declarations from the declarator D to the function
02938   // declaration NewFD, if they are available.  First scavenge them into Params.
02939   llvm::SmallVector<ParmVarDecl*, 16> Params;
02940   if (D.getNumTypeObjects() > 0) {
02941     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
02942 
02943     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
02944     // function that takes no arguments, not a function that takes a
02945     // single void argument.
02946     // We let through "const void" here because Sema::GetTypeForDeclarator
02947     // already checks for that case.
02948     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
02949         FTI.ArgInfo[0].Param &&
02950         FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
02951       // Empty arg list, don't push any params.
02952       ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
02953 
02954       // In C++, the empty parameter-type-list must be spelled "void"; a
02955       // typedef of void is not permitted.
02956       if (getLangOptions().CPlusPlus &&
02957           Param->getType().getUnqualifiedType() != Context.VoidTy)
02958         Diag(Param->getLocation(), diag::err_param_typedef_of_void);
02959       // FIXME: Leaks decl?
02960     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
02961       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
02962         ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
02963         assert(Param->getDeclContext() != NewFD && "Was set before ?");
02964         Param->setDeclContext(NewFD);
02965         Params.push_back(Param);
02966       }
02967     }
02968 
02969   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
02970     // When we're declaring a function with a typedef, typeof, etc as in the
02971     // following example, we'll need to synthesize (unnamed)
02972     // parameters for use in the declaration.
02973     //
02974     // @code
02975     // typedef void fn(int);
02976     // fn f;
02977     // @endcode
02978 
02979     // Synthesize a parameter for each argument type.
02980     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
02981          AE = FT->arg_type_end(); AI != AE; ++AI) {
02982       ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
02983                                                SourceLocation(), 0,
02984                                                *AI, /*TInfo=*/0,
02985                                                VarDecl::None, 0);
02986       Param->setImplicit();
02987       Params.push_back(Param);
02988     }
02989   } else {
02990     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
02991            "Should not need args for typedef of non-prototype fn");
02992   }
02993   // Finally, we know we have the right number of parameters, install them.
02994   NewFD->setParams(Params.data(), Params.size());
02995 
02996   // If the declarator is a template-id, translate the parser's template 
02997   // argument list into our AST format.
02998   bool HasExplicitTemplateArgs = false;
02999   TemplateArgumentListInfo TemplateArgs;
03000   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
03001     TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
03002     TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
03003     TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
03004     ASTTemplateArgsPtr TemplateArgsPtr(*this,
03005                                        TemplateId->getTemplateArgs(),
03006                                        TemplateId->NumArgs);
03007     translateTemplateArguments(TemplateArgsPtr,
03008                                TemplateArgs);
03009     TemplateArgsPtr.release();
03010     
03011     HasExplicitTemplateArgs = true;
03012     
03013     if (FunctionTemplate) {
03014       // FIXME: Diagnose function template with explicit template
03015       // arguments.
03016       HasExplicitTemplateArgs = false;
03017     } else if (!isFunctionTemplateSpecialization && 
03018                !D.getDeclSpec().isFriendSpecified()) {
03019       // We have encountered something that the user meant to be a 
03020       // specialization (because it has explicitly-specified template
03021       // arguments) but that was not introduced with a "template<>" (or had
03022       // too few of them).
03023       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
03024         << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
03025         << CodeModificationHint::CreateInsertion(
03026                                    D.getDeclSpec().getSourceRange().getBegin(),
03027                                                  "template<> ");
03028       isFunctionTemplateSpecialization = true;
03029     }
03030   }
03031 
03032   if (isFunctionTemplateSpecialization) {
03033       if (CheckFunctionTemplateSpecialization(NewFD,
03034                                (HasExplicitTemplateArgs ? &TemplateArgs : 0),
03035                                               Previous))
03036         NewFD->setInvalidDecl();
03037   } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
03038              CheckMemberSpecialization(NewFD, Previous))
03039     NewFD->setInvalidDecl();
03040     
03041   // Perform semantic checking on the function declaration.
03042   bool OverloadableAttrRequired = false; // FIXME: HACK!
03043   CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
03044                            Redeclaration, /*FIXME:*/OverloadableAttrRequired);
03045 
03046   assert((NewFD->isInvalidDecl() || !Redeclaration ||
03047           Previous.getResultKind() != LookupResult::FoundOverloaded) &&
03048          "previous declaration set still overloaded");
03049 
03050   // If we have a function template, check the template parameter
03051   // list. This will check and merge default template arguments.
03052   if (FunctionTemplate) {
03053     FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
03054     CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
03055                       PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
03056              D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
03057                                                 : TPC_FunctionTemplate);
03058   }
03059 
03060   if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
03061     // Fake up an access specifier if it's supposed to be a class member.
03062     if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
03063       NewFD->setAccess(AS_public);
03064 
03065     // An out-of-line member function declaration must also be a
03066     // definition (C++ [dcl.meaning]p1).
03067     // Note that this is not the case for explicit specializations of
03068     // function templates or member functions of class templates, per
03069     // C++ [temp.expl.spec]p2.
03070     if (!IsFunctionDefinition && !isFriend &&
03071         !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
03072       Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
03073         << D.getCXXScopeSpec().getRange();
03074       NewFD->setInvalidDecl();
03075     } else if (!Redeclaration && 
03076                !(isFriend && CurContext->isDependentContext())) {
03077       // The user tried to provide an out-of-line definition for a
03078       // function that is a member of a class or namespace, but there
03079       // was no such member function declared (C++ [class.mfct]p2,
03080       // C++ [namespace.memdef]p2). For example:
03081       //
03082       // class X {
03083       //   void f() const;
03084       // };
03085       //
03086       // void X::f() { } // ill-formed
03087       //
03088       // Complain about this problem, and attempt to suggest close
03089       // matches (e.g., those that differ only in cv-qualifiers and
03090       // whether the parameter types are references).
03091       Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
03092         << Name << DC << D.getCXXScopeSpec().getRange();
03093       NewFD->setInvalidDecl();
03094 
03095       LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
03096                         ForRedeclaration);
03097       LookupQualifiedName(Prev, DC);
03098       assert(!Prev.isAmbiguous() &&
03099              "Cannot have an ambiguity in previous-declaration lookup");
03100       for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
03101            Func != FuncEnd; ++Func) {
03102         if (isa<FunctionDecl>(*Func) &&
03103             isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
03104           Diag((*Func)->getLocation(), diag::note_member_def_close_match);
03105       }
03106     }
03107   }
03108 
03109   // Handle attributes. We need to have merged decls when handling attributes
03110   // (for example to check for conflicts, etc).
03111   // FIXME: This needs to happen before we merge declarations. Then,
03112   // let attribute merging cope with attribute conflicts.
03113   ProcessDeclAttributes(S, NewFD, D);
03114 
03115   // attributes declared post-definition are currently ignored
03116   if (Redeclaration && Previous.isSingleResult()) {
03117     const FunctionDecl *Def;
03118     FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
03119     if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
03120       Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
03121       Diag(Def->getLocation(), diag::note_previous_definition);
03122     }
03123   }
03124 
03125   AddKnownFunctionAttributes(NewFD);
03126 
03127   if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
03128     // If a function name is overloadable in C, then every function
03129     // with that name must be marked "overloadable".
03130     Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
03131       << Redeclaration << NewFD;
03132     if (!Previous.empty())
03133       Diag(Previous.getRepresentativeDecl()->getLocation(),
03134            diag::note_attribute_overloadable_prev_overload);
03135     NewFD->addAttr(::new (Context) OverloadableAttr());
03136   }
03137 
03138   // If this is a locally-scoped extern C function, update the
03139   // map of such names.
03140   if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
03141       && !NewFD->isInvalidDecl())
03142     RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
03143 
03144   // Set this FunctionDecl's range up to the right paren.
03145   NewFD->setLocEnd(D.getSourceRange().getEnd());
03146 
03147   if (FunctionTemplate && NewFD->isInvalidDecl())
03148     FunctionTemplate->setInvalidDecl();
03149 
03150   if (FunctionTemplate)
03151     return FunctionTemplate;
03152 
03153   
03154   // Keep track of static, non-inlined function definitions that
03155   // have not been used. We will warn later.
03156   // FIXME: Also include static functions declared but not defined.
03157   if (!NewFD->isInvalidDecl() && IsFunctionDefinition 
03158       && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
03159       && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>())
03160     UnusedStaticFuncs.push_back(NewFD);
03161   
03162   return NewFD;
03163 }
03164 
03165 /// \brief Perform semantic checking of a new function declaration.
03166 ///
03167 /// Performs semantic analysis of the new function declaration
03168 /// NewFD. This routine performs all semantic checking that does not
03169 /// require the actual declarator involved in the declaration, and is
03170 /// used both for the declaration of functions as they are parsed
03171 /// (called via ActOnDeclarator) and for the declaration of functions
03172 /// that have been instantiated via C++ template instantiation (called
03173 /// via InstantiateDecl).
03174 ///
03175 /// \param IsExplicitSpecialiation whether this new function declaration is
03176 /// an explicit specialization of the previous declaration.
03177 ///
03178 /// This sets NewFD->isInvalidDecl() to true if there was an error.
03179 void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
03180                                     LookupResult &Previous,
03181                                     bool IsExplicitSpecialization,
03182                                     bool &Redeclaration,
03183                                     bool &OverloadableAttrRequired) {
03184   // If NewFD is already known erroneous, don't do any of this checking.
03185   if (NewFD->isInvalidDecl())
03186     return;
03187 
03188   if (NewFD->getResultType()->isVariablyModifiedType()) {
03189     // Functions returning a variably modified type violate C99 6.7.5.2p2
03190     // because all functions have linkage.
03191     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
03192     return NewFD->setInvalidDecl();
03193   }
03194 
03195   if (NewFD->isMain()) 
03196     CheckMain(NewFD);
03197 
03198   // Check for a previous declaration of this name.
03199   if (Previous.empty() && NewFD->isExternC()) {
03200     // Since we did not find anything by this name and we're declaring
03201     // an extern "C" function, look for a non-visible extern "C"
03202     // declaration with the same name.
03203     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
03204       = LocallyScopedExternalDecls.find(NewFD->getDeclName());
03205     if (Pos != LocallyScopedExternalDecls.end())
03206       Previous.addDecl(Pos->second);
03207   }
03208 
03209   // Merge or overload the declaration with an existing declaration of
03210   // the same name, if appropriate.
03211   if (!Previous.empty()) {
03212     // Determine whether NewFD is an overload of PrevDecl or
03213     // a declaration that requires merging. If it's an overload,
03214     // there's no more work to do here; we'll just add the new
03215     // function to the scope.
03216 
03217     NamedDecl *OldDecl = 0;
03218     if (!AllowOverloadingOfFunction(Previous, Context)) {
03219       Redeclaration = true;
03220       OldDecl = Previous.getFoundDecl();
03221     } else {
03222       if (!getLangOptions().CPlusPlus) {
03223         OverloadableAttrRequired = true;
03224 
03225         // Functions marked "overloadable" must have a prototype (that
03226         // we can't get through declaration merging).
03227         if (!NewFD->getType()->getAs<FunctionProtoType>()) {
03228           Diag(NewFD->getLocation(),
03229                diag::err_attribute_overloadable_no_prototype)
03230             << NewFD;
03231           Redeclaration = true;
03232 
03233           // Turn this into a variadic function with no parameters.
03234           QualType R = Context.getFunctionType(
03235                      NewFD->getType()->getAs<FunctionType>()->getResultType(),
03236                      0, 0, true, 0, false, false, 0, 0, false, CC_Default);
03237           NewFD->setType(R);
03238           return NewFD->setInvalidDecl();
03239         }
03240       }
03241 
03242       switch (CheckOverload(NewFD, Previous, OldDecl)) {
03243       case Ovl_Match:
03244         Redeclaration = true;
03245         if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
03246           HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
03247           Redeclaration = false;
03248         }
03249         break;
03250 
03251       case Ovl_NonFunction:
03252         Redeclaration = true;
03253         break;
03254 
03255       case Ovl_Overload:
03256         Redeclaration = false;
03257         break;
03258       }
03259     }
03260 
03261     if (Redeclaration) {
03262       // NewFD and OldDecl represent declarations that need to be
03263       // merged.
03264       if (MergeFunctionDecl(NewFD, OldDecl))
03265         return NewFD->setInvalidDecl();
03266 
03267       Previous.clear();
03268       Previous.addDecl(OldDecl);
03269 
03270       if (FunctionTemplateDecl *OldTemplateDecl
03271                                     = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
03272         NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());        
03273         FunctionTemplateDecl *NewTemplateDecl
03274           = NewFD->getDescribedFunctionTemplate();
03275         assert(NewTemplateDecl && "Template/non-template mismatch");
03276         if (CXXMethodDecl *Method 
03277               = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
03278           Method->setAccess(OldTemplateDecl->getAccess());
03279           NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
03280         }
03281         
03282         // If this is an explicit specialization of a member that is a function
03283         // template, mark it as a member specialization.
03284         if (IsExplicitSpecialization && 
03285             NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
03286           NewTemplateDecl->setMemberSpecialization();
03287           assert(OldTemplateDecl->isMemberSpecialization());
03288         }
03289       } else {
03290         if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
03291           NewFD->setAccess(OldDecl->getAccess());
03292         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
03293       }
03294     }
03295   }
03296 
03297   // Semantic checking for this function declaration (in isolation).
03298   if (getLangOptions().CPlusPlus) {
03299     // C++-specific checks.
03300     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
03301       CheckConstructor(Constructor);
03302     } else if (CXXDestructorDecl *Destructor = 
03303                 dyn_cast<CXXDestructorDecl>(NewFD)) {
03304       CXXRecordDecl *Record = Destructor->getParent();
03305       QualType ClassType = Context.getTypeDeclType(Record);
03306       
03307       // FIXME: Shouldn't we be able to perform thisc heck even when the class
03308       // type is dependent? Both gcc and edg can handle that.
03309       if (!ClassType->isDependentType()) {
03310         DeclarationName Name
03311           = Context.DeclarationNames.getCXXDestructorName(
03312                                         Context.getCanonicalType(ClassType));
03313         if (NewFD->getDeclName() != Name) {
03314           Diag(NewFD->getLocation(), diag::err_destructor_name);
03315           return NewFD->setInvalidDecl();
03316         }
03317       }
03318 
03319       Record->setUserDeclaredDestructor(true);
03320       // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
03321       // user-defined destructor.
03322       Record->setPOD(false);
03323 
03324       // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
03325       // declared destructor.
03326       // FIXME: C++0x: don't do this for "= default" destructors
03327       Record->setHasTrivialDestructor(false);
03328     } else if (CXXConversionDecl *Conversion
03329                = dyn_cast<CXXConversionDecl>(NewFD)) {
03330       ActOnConversionDeclarator(Conversion);
03331     }
03332 
03333     // Find any virtual functions that this function overrides.
03334     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
03335       if (!Method->isFunctionTemplateSpecialization() && 
03336           !Method->getDescribedFunctionTemplate())
03337         AddOverriddenMethods(Method->getParent(), Method);
03338     }
03339 
03340     // Additional checks for the destructor; make sure we do this after we
03341     // figure out whether the destructor is virtual.
03342     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
03343       if (!Destructor->getParent()->isDependentType())
03344         CheckDestructor(Destructor);
03345 
03346     // Extra checking for C++ overloaded operators (C++ [over.oper]).
03347     if (NewFD->isOverloadedOperator() &&
03348         CheckOverloadedOperatorDeclaration(NewFD))
03349       return NewFD->setInvalidDecl();
03350 
03351     // Extra checking for C++0x literal operators (C++0x [over.literal]).
03352     if (NewFD->getLiteralIdentifier() &&
03353         CheckLiteralOperatorDeclaration(NewFD))
03354       return NewFD->setInvalidDecl();
03355 
03356     // In C++, check default arguments now that we have merged decls. Unless
03357     // the lexical context is the class, because in this case this is done
03358     // during delayed parsing anyway.
03359     if (!CurContext->isRecord())
03360       CheckCXXDefaultArguments(NewFD);
03361   }
03362 }
03363 
03364 void Sema::CheckMain(FunctionDecl* FD) {
03365   // C++ [basic.start.main]p3:  A program that declares main to be inline
03366   //   or static is ill-formed.
03367   // C99 6.7.4p4:  In a hosted environment, the inline function specifier
03368   //   shall not appear in a declaration of main.
03369   // static main is not an error under C99, but we should warn about it.
03370   bool isInline = FD->isInlineSpecified();
03371   bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
03372   if (isInline || isStatic) {
03373     unsigned diagID = diag::warn_unusual_main_decl;
03374     if (isInline || getLangOptions().CPlusPlus)
03375       diagID = diag::err_unusual_main_decl;
03376 
03377     int which = isStatic + (isInline << 1) - 1;
03378     Diag(FD->getLocation(), diagID) << which;
03379   }
03380 
03381   QualType T = FD->getType();
03382   assert(T->isFunctionType() && "function decl is not of function type");
03383   const FunctionType* FT = T->getAs<FunctionType>();
03384 
03385   if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
03386     // TODO: add a replacement fixit to turn the return type into 'int'.
03387     Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
03388     FD->setInvalidDecl(true);
03389   }
03390 
03391   // Treat protoless main() as nullary.
03392   if (isa<FunctionNoProtoType>(FT)) return;
03393 
03394   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
03395   unsigned nparams = FTP->getNumArgs();
03396   assert(FD->getNumParams() == nparams);
03397 
03398   bool HasExtraParameters = (nparams > 3);
03399 
03400   // Darwin passes an undocumented fourth argument of type char**.  If
03401   // other platforms start sprouting these, the logic below will start
03402   // getting shifty.
03403   if (nparams == 4 &&
03404       Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
03405     HasExtraParameters = false;
03406 
03407   if (HasExtraParameters) {
03408     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
03409     FD->setInvalidDecl(true);
03410     nparams = 3;
03411   }
03412 
03413   // FIXME: a lot of the following diagnostics would be improved
03414   // if we had some location information about types.
03415 
03416   QualType CharPP =
03417     Context.getPointerType(Context.getPointerType(Context.CharTy));
03418   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
03419 
03420   for (unsigned i = 0; i < nparams; ++i) {
03421     QualType AT = FTP->getArgType(i);
03422 
03423     bool mismatch = true;
03424 
03425     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
03426       mismatch = false;
03427     else if (Expected[i] == CharPP) {
03428       // As an extension, the following forms are okay:
03429       //   char const **
03430       //   char const * const *
03431       //   char * const *
03432 
03433       QualifierCollector qs;
03434       const PointerType* PT;
03435       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
03436           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
03437           (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
03438         qs.removeConst();
03439         mismatch = !qs.empty();
03440       }
03441     }
03442 
03443     if (mismatch) {
03444       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
03445       // TODO: suggest replacing given type with expected type
03446       FD->setInvalidDecl(true);
03447     }
03448   }
03449 
03450   if (nparams == 1 && !FD->isInvalidDecl()) {
03451     Diag(FD->getLocation(), diag::warn_main_one_arg);
03452   }
03453 }
03454 
03455 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
03456   // FIXME: Need strict checking.  In C89, we need to check for
03457   // any assignment, increment, decrement, function-calls, or
03458   // commas outside of a sizeof.  In C99, it's the same list,
03459   // except that the aforementioned are allowed in unevaluated
03460   // expressions.  Everything else falls under the
03461   // "may accept other forms of constant expressions" exception.
03462   // (We never end up here for C++, so the constant expression
03463   // rules there don't matter.)
03464   if (Init->isConstantInitializer(Context))
03465     return false;
03466   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
03467     << Init->getSourceRange();
03468   return true;
03469 }
03470 
03471 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
03472   AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
03473 }
03474 
03475 /// AddInitializerToDecl - Adds the initializer Init to the
03476 /// declaration dcl. If DirectInit is true, this is C++ direct
03477 /// initialization rather than copy initialization.
03478 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
03479   Decl *RealDecl = dcl.getAs<Decl>();
03480   // If there is no declaration, there was an error parsing it.  Just ignore
03481   // the initializer.
03482   if (RealDecl == 0)
03483     return;
03484 
03485   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
03486     // With declarators parsed the way they are, the parser cannot
03487     // distinguish between a normal initializer and a pure-specifier.
03488     // Thus this grotesque test.
03489     IntegerLiteral *IL;
03490     Expr *Init = static_cast<Expr *>(init.get());
03491     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
03492         Context.getCanonicalType(IL->getType()) == Context.IntTy)
03493       CheckPureMethod(Method, Init->getSourceRange());
03494     else {
03495       Diag(Method->getLocation(), diag::err_member_function_initialization)
03496         << Method->getDeclName() << Init->getSourceRange();
03497       Method->setInvalidDecl();
03498     }
03499     return;
03500   }
03501 
03502   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
03503   if (!VDecl) {
03504     if (getLangOptions().CPlusPlus &&
03505         RealDecl->getLexicalDeclContext()->isRecord() &&
03506         isa<NamedDecl>(RealDecl))
03507       Diag(RealDecl->getLocation(), diag::err_member_initialization)
03508         << cast<NamedDecl>(RealDecl)->getDeclName();
03509     else
03510       Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
03511     RealDecl->setInvalidDecl();
03512     return;
03513   }
03514 
03515   // A definition must end up with a complete type, which means it must be
03516   // complete with the restriction that an array type might be completed by the
03517   // initializer; note that later code assumes this restriction.
03518   QualType BaseDeclType = VDecl->getType();
03519   if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
03520     BaseDeclType = Array->getElementType();
03521   if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
03522                           diag::err_typecheck_decl_incomplete_type)) {
03523     RealDecl->setInvalidDecl();
03524     return;
03525   }
03526 
03527   // The variable can not have an abstract class type.
03528   if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
03529                              diag::err_abstract_type_in_decl,
03530                              AbstractVariableType))
03531     VDecl->setInvalidDecl();
03532 
03533   const VarDecl *Def;
03534   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
03535     Diag(VDecl->getLocation(), diag::err_redefinition)
03536       << VDecl->getDeclName();
03537     Diag(Def->getLocation(), diag::note_previous_definition);
03538     VDecl->setInvalidDecl();
03539     return;
03540   }
03541 
03542   // Take ownership of the expression, now that we're sure we have somewhere
03543   // to put it.
03544   Expr *Init = init.takeAs<Expr>();
03545   assert(Init && "missing initializer");
03546 
03547   // Capture the variable that is being initialized and the style of
03548   // initialization.
03549   InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
03550   
03551   // FIXME: Poor source location information.
03552   InitializationKind Kind
03553     = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
03554                                                    Init->getLocStart(),
03555                                                    Init->getLocEnd())
03556                 : InitializationKind::CreateCopy(VDecl->getLocation(),
03557                                                  Init->getLocStart());
03558   
03559   // Get the decls type and save a reference for later, since
03560   // CheckInitializerTypes may change it.
03561   QualType DclT = VDecl->getType(), SavT = DclT;
03562   if (VDecl->isBlockVarDecl()) {
03563     if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
03564       Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
03565       VDecl->setInvalidDecl();
03566     } else if (!VDecl->isInvalidDecl()) {
03567       InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
03568       OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
03569                                           MultiExprArg(*this, (void**)&Init, 1),
03570                                                 &DclT);
03571       if (Result.isInvalid()) {
03572         VDecl->setInvalidDecl();
03573         return;
03574       }
03575 
03576       Init = Result.takeAs<Expr>();
03577 
03578       // C++ 3.6.2p2, allow dynamic initialization of static initializers.
03579       // Don't check invalid declarations to avoid emitting useless diagnostics.
03580       if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
03581         if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
03582           CheckForConstantInitializer(Init, DclT);
03583       }
03584     }
03585   } else if (VDecl->isStaticDataMember() &&
03586              VDecl->getLexicalDeclContext()->isRecord()) {
03587     // This is an in-class initialization for a static data member, e.g.,
03588     //
03589     // struct S {
03590     //   static const int value = 17;
03591     // };
03592 
03593     // Attach the initializer
03594     VDecl->setInit(Init);
03595 
03596     // C++ [class.mem]p4:
03597     //   A member-declarator can contain a constant-initializer only
03598     //   if it declares a static member (9.4) of const integral or
03599     //   const enumeration type, see 9.4.2.
03600     QualType T = VDecl->getType();
03601     if (!T->isDependentType() &&
03602         (!Context.getCanonicalType(T).isConstQualified() ||
03603          !T->isIntegralType())) {
03604       Diag(VDecl->getLocation(), diag::err_member_initialization)
03605         << VDecl->getDeclName() << Init->getSourceRange();
03606       VDecl->setInvalidDecl();
03607     } else {
03608       // C++ [class.static.data]p4:
03609       //   If a static data member is of const integral or const
03610       //   enumeration type, its declaration in the class definition
03611       //   can specify a constant-initializer which shall be an
03612       //   integral constant expression (5.19).
03613       if (!Init->isTypeDependent() &&
03614           !Init->getType()->isIntegralType()) {
03615         // We have a non-dependent, non-integral or enumeration type.
03616         Diag(Init->getSourceRange().getBegin(),
03617              diag::err_in_class_initializer_non_integral_type)
03618           << Init->getType() << Init->getSourceRange();
03619         VDecl->setInvalidDecl();
03620       } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
03621         // Check whether the expression is a constant expression.
03622         llvm::APSInt Value;
03623         SourceLocation Loc;
03624         if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
03625           Diag(Loc, diag::err_in_class_initializer_non_constant)
03626             << Init->getSourceRange();
03627           VDecl->setInvalidDecl();
03628         } else if (!VDecl->getType()->isDependentType())
03629           ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
03630       }
03631     }
03632   } else if (VDecl->isFileVarDecl()) {
03633     if (VDecl->getStorageClass() == VarDecl::Extern)
03634       Diag(VDecl->getLocation(), diag::warn_extern_init);
03635     if (!VDecl->isInvalidDecl()) {
03636       InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
03637       OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
03638                                           MultiExprArg(*this, (void**)&Init, 1),
03639                                                 &DclT);
03640       if (Result.isInvalid()) {
03641         VDecl->setInvalidDecl();
03642         return;
03643       }
03644 
03645       Init = Result.takeAs<Expr>();
03646     }
03647 
03648     // C++ 3.6.2p2, allow dynamic initialization of static initializers.
03649     // Don't check invalid declarations to avoid emitting useless diagnostics.
03650     if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
03651       // C99 6.7.8p4. All file scoped initializers need to be constant.
03652       CheckForConstantInitializer(Init, DclT);
03653     }
03654   }
03655   // If the type changed, it means we had an incomplete type that was
03656   // completed by the initializer. For example:
03657   //   int ary[] = { 1, 3, 5 };
03658   // "ary" transitions from a VariableArrayType to a ConstantArrayType.
03659   if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
03660     VDecl->setType(DclT);
03661     Init->setType(DclT);
03662   }
03663 
03664   Init = MaybeCreateCXXExprWithTemporaries(Init);
03665   // Attach the initializer to the decl.
03666   VDecl->setInit(Init);
03667 
03668   if (getLangOptions().CPlusPlus) {
03669     // Make sure we mark the destructor as used if necessary.
03670     QualType InitType = VDecl->getType();
03671     while (const ArrayType *Array = Context.getAsArrayType(InitType))
03672       InitType = Context.getBaseElementType(Array);
03673     if (const RecordType *Record = InitType->getAs<RecordType>())
03674       FinalizeVarWithDestructor(VDecl, Record);
03675   }
03676 
03677   return;
03678 }
03679 
03680 void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
03681                                   bool TypeContainsUndeducedAuto) {
03682   Decl *RealDecl = dcl.getAs<Decl>();
03683 
03684   // If there is no declaration, there was an error parsing it. Just ignore it.
03685   if (RealDecl == 0)
03686     return;
03687 
03688   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
03689     QualType Type = Var->getType();
03690 
03691     // C++0x [dcl.spec.auto]p3
03692     if (TypeContainsUndeducedAuto) {
03693       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
03694         << Var->getDeclName() << Type;
03695       Var->setInvalidDecl();
03696       return;
03697     }
03698 
03699     switch (Var->isThisDeclarationADefinition()) {
03700     case VarDecl::Definition:
03701       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
03702         break;
03703 
03704       // We have an out-of-line definition of a static data member
03705       // that has an in-class initializer, so we type-check this like
03706       // a declaration. 
03707       //
03708       // Fall through
03709       
03710     case VarDecl::DeclarationOnly:
03711       // It's only a declaration. 
03712 
03713       // Block scope. C99 6.7p7: If an identifier for an object is
03714       // declared with no linkage (C99 6.2.2p6), the type for the
03715       // object shall be complete.
03716       if (!Type->isDependentType() && Var->isBlockVarDecl() && 
03717           !Var->getLinkage() && !Var->isInvalidDecl() &&
03718           RequireCompleteType(Var->getLocation(), Type,
03719                               diag::err_typecheck_decl_incomplete_type))
03720         Var->setInvalidDecl();
03721 
03722       // Make sure that the type is not abstract.
03723       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
03724           RequireNonAbstractType(Var->getLocation(), Type,
03725                                  diag::err_abstract_type_in_decl,
03726                                  AbstractVariableType))
03727         Var->setInvalidDecl();
03728       return;
03729 
03730     case VarDecl::TentativeDefinition:
03731       // File scope. C99 6.9.2p2: A declaration of an identifier for an
03732       // object that has file scope without an initializer, and without a
03733       // storage-class specifier or with the storage-class specifier "static",
03734       // constitutes a tentative definition. Note: A tentative definition with
03735       // external linkage is valid (C99 6.2.2p5).
03736       if (!Var->isInvalidDecl()) {
03737         if (const IncompleteArrayType *ArrayT
03738                                     = Context.getAsIncompleteArrayType(Type)) {
03739           if (RequireCompleteType(Var->getLocation(),
03740                                   ArrayT->getElementType(),
03741                                   diag::err_illegal_decl_array_incomplete_type))
03742             Var->setInvalidDecl();
03743         } else if (Var->getStorageClass() == VarDecl::Static) {
03744           // C99 6.9.2p3: If the declaration of an identifier for an object is
03745           // a tentative definition and has internal linkage (C99 6.2.2p3), the
03746           // declared type shall not be an incomplete type.
03747           // NOTE: code such as the following
03748           //     static struct s;
03749           //     struct s { int a; };
03750           // is accepted by gcc. Hence here we issue a warning instead of
03751           // an error and we do not invalidate the static declaration.
03752           // NOTE: to avoid multiple warnings, only check the first declaration.
03753           if (Var->getPreviousDeclaration() == 0)
03754             RequireCompleteType(Var->getLocation(), Type,
03755                                 diag::ext_typecheck_decl_incomplete_type);
03756         }
03757       }
03758 
03759       // Record the tentative definition; we're done.
03760       if (!Var->isInvalidDecl())
03761         TentativeDefinitions.push_back(Var);
03762       return;
03763     }
03764 
03765     // Provide a specific diagnostic for uninitialized variable
03766     // definitions with incomplete array type.
03767     if (Type->isIncompleteArrayType()) {
03768       Diag(Var->getLocation(),
03769            diag::err_typecheck_incomplete_array_needs_initializer);
03770       Var->setInvalidDecl();
03771       return;
03772     }
03773 
03774    // Provide a specific diagnostic for uninitialized variable
03775    // definitions with reference type.
03776    if (Type->isReferenceType()) {
03777      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
03778        << Var->getDeclName()
03779        << SourceRange(Var->getLocation(), Var->getLocation());
03780      Var->setInvalidDecl();
03781      return;
03782    }
03783 
03784     // Do not attempt to type-check the default initializer for a
03785     // variable with dependent type.
03786     if (Type->isDependentType())
03787       return;
03788 
03789     if (Var->isInvalidDecl())
03790       return;
03791 
03792     if (RequireCompleteType(Var->getLocation(), 
03793                             Context.getBaseElementType(Type),
03794                             diag::err_typecheck_decl_incomplete_type)) {
03795       Var->setInvalidDecl();
03796       return;
03797     }
03798 
03799     // The variable can not have an abstract class type.
03800     if (RequireNonAbstractType(Var->getLocation(), Type,
03801                                diag::err_abstract_type_in_decl,
03802                                AbstractVariableType)) {
03803       Var->setInvalidDecl();
03804       return;
03805     }
03806 
03807     const RecordType *Record
03808       = Context.getBaseElementType(Type)->getAs<RecordType>();
03809     if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
03810         cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
03811       // C++03 [dcl.init]p9:
03812       //   If no initializer is specified for an object, and the
03813       //   object is of (possibly cv-qualified) non-POD class type (or
03814       //   array thereof), the object shall be default-initialized; if
03815       //   the object is of const-qualified type, the underlying class
03816       //   type shall have a user-declared default
03817       //   constructor. Otherwise, if no initializer is specified for
03818       //   a non- static object, the object and its subobjects, if
03819       //   any, have an indeterminate initial value); if the object
03820       //   or any of its subobjects are of const-qualified type, the
03821       //   program is ill-formed.
03822       // FIXME: DPG thinks it is very fishy that C++0x disables this.
03823     } else {
03824       InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
03825       InitializationKind Kind
03826         = InitializationKind::CreateDefault(Var->getLocation());
03827     
03828       InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
03829       OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
03830                                               MultiExprArg(*this, 0, 0));
03831       if (Init.isInvalid())
03832         Var->setInvalidDecl();
03833       else if (Init.get())
03834         Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
03835     }
03836 
03837     if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
03838       FinalizeVarWithDestructor(Var, Record);
03839   }
03840 }
03841 
03842 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
03843                                                    DeclPtrTy *Group,
03844                                                    unsigned NumDecls) {
03845   llvm::SmallVector<Decl*, 8> Decls;
03846 
03847   if (DS.isTypeSpecOwned())
03848     Decls.push_back((Decl*)DS.getTypeRep());
03849 
03850   for (unsigned i = 0; i != NumDecls; ++i)
03851     if (Decl *D = Group[i].getAs<Decl>())
03852       Decls.push_back(D);
03853 
03854   return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
03855                                                    Decls.data(), Decls.size()));
03856 }
03857 
03858 
03859 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
03860 /// to introduce parameters into function prototype scope.
03861 Sema::DeclPtrTy
03862 Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
03863   const DeclSpec &DS = D.getDeclSpec();
03864 
03865   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
03866   VarDecl::StorageClass StorageClass = VarDecl::None;
03867   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
03868     StorageClass = VarDecl::Register;
03869   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
03870     Diag(DS.getStorageClassSpecLoc(),
03871          diag::err_invalid_storage_class_in_func_decl);
03872     D.getMutableDeclSpec().ClearStorageClassSpecs();
03873   }
03874 
03875   if (D.getDeclSpec().isThreadSpecified())
03876     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
03877 
03878   DiagnoseFunctionSpecifiers(D);
03879 
03880   // Check that there are no default arguments inside the type of this
03881   // parameter (C++ only).
03882   if (getLangOptions().CPlusPlus)
03883     CheckExtraCXXDefaultArguments(D);
03884 
03885   TypeSourceInfo *TInfo = 0;
03886   TagDecl *OwnedDecl = 0;
03887   QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
03888 
03889   if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
03890     // C++ [dcl.fct]p6:
03891     //   Types shall not be defined in return or parameter types.
03892     Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
03893       << Context.getTypeDeclType(OwnedDecl);
03894   }
03895 
03896   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
03897   IdentifierInfo *II = D.getIdentifier();
03898   if (II) {
03899     if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
03900       if (PrevDecl->isTemplateParameter()) {
03901         // Maybe we will complain about the shadowed template parameter.
03902         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
03903         // Just pretend that we didn't see the previous declaration.
03904         PrevDecl = 0;
03905       } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
03906         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
03907         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
03908 
03909         // Recover by removing the name
03910         II = 0;
03911         D.SetIdentifier(0, D.getIdentifierLoc());
03912         D.setInvalidType(true);
03913       }
03914     }
03915   }
03916 
03917   // Parameters can not be abstract class types.
03918   // For record types, this is done by the AbstractClassUsageDiagnoser once
03919   // the class has been completely parsed.
03920   if (!CurContext->isRecord() &&
03921       RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
03922                              diag::err_abstract_type_in_decl,
03923                              AbstractParamType))
03924     D.setInvalidType(true);
03925 
03926   QualType T = adjustParameterType(parmDeclType);
03927 
03928   // Temporarily put parameter variables in the translation unit, not
03929   // the enclosing context.  This prevents them from accidentally
03930   // looking like class members in C++.
03931   DeclContext *DC = Context.getTranslationUnitDecl();
03932 
03933   ParmVarDecl *New
03934     = ParmVarDecl::Create(Context, DC, D.getIdentifierLoc(), II,
03935                           T, TInfo, StorageClass, 0);
03936 
03937   if (D.isInvalidType())
03938     New->setInvalidDecl();
03939 
03940   // Parameter declarators cannot be interface types. All ObjC objects are
03941   // passed by reference.
03942   if (T->isObjCInterfaceType()) {
03943     Diag(D.getIdentifierLoc(),
03944          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
03945     New->setInvalidDecl();
03946   }
03947 
03948   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
03949   if (D.getCXXScopeSpec().isSet()) {
03950     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
03951       << D.getCXXScopeSpec().getRange();
03952     New->setInvalidDecl();
03953   }
03954   
03955   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
03956   // duration shall not be qualified by an address-space qualifier."
03957   // Since all parameters have automatic store duration, they can not have
03958   // an address space.
03959   if (T.getAddressSpace() != 0) {
03960     Diag(D.getIdentifierLoc(),  
03961          diag::err_arg_with_address_space);
03962     New->setInvalidDecl();
03963   }   
03964   
03965   
03966   // Add the parameter declaration into this scope.
03967   S->AddDecl(DeclPtrTy::make(New));
03968   if (II)
03969     IdResolver.AddDecl(New);
03970 
03971   ProcessDeclAttributes(S, New, D);
03972 
03973   if (New->hasAttr<BlocksAttr>()) {
03974     Diag(New->getLocation(), diag::err_block_on_nonlocal);
03975   }
03976   return DeclPtrTy::make(New);
03977 }
03978 
03979 void Sema::ActOnObjCCatchParam(DeclPtrTy D) {
03980   ParmVarDecl *Param = cast<ParmVarDecl>(D.getAs<Decl>());
03981   Param->setDeclContext(CurContext);
03982 }
03983 
03984 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
03985                                            SourceLocation LocAfterDecls) {
03986   assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
03987          "Not a function declarator!");
03988   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
03989 
03990   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
03991   // for a K&R function.
03992   if (!FTI.hasPrototype) {
03993     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
03994       --i;
03995       if (FTI.ArgInfo[i].Param == 0) {
03996         llvm::SmallString<256> Code;
03997         llvm::raw_svector_ostream(Code) << "  int "
03998                                         << FTI.ArgInfo[i].Ident->getName()
03999                                         << ";\n";
04000         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
04001           << FTI.ArgInfo[i].Ident
04002           << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
04003 
04004         // Implicitly declare the argument as type 'int' for lack of a better
04005         // type.
04006         DeclSpec DS;
04007         const char* PrevSpec; // unused
04008         unsigned DiagID; // unused
04009         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
04010                            PrevSpec, DiagID);
04011         Declarator ParamD(DS, Declarator::KNRTypeListContext);
04012         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
04013         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
04014       }
04015     }
04016   }
04017 }
04018 
04019 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
04020                                               Declarator &D) {
04021   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
04022   assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
04023          "Not a function declarator!");
04024   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
04025 
04026   if (FTI.hasPrototype) {
04027     // FIXME: Diagnose arguments without names in C.
04028   }
04029 
04030   Scope *ParentScope = FnBodyScope->getParent();
04031 
04032   DeclPtrTy DP = HandleDeclarator(ParentScope, D,
04033                                   MultiTemplateParamsArg(*this),
04034                                   /*IsFunctionDefinition=*/true);
04035   return ActOnStartOfFunctionDef(FnBodyScope, DP);
04036 }
04037 
04038 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
04039   // Don't warn about invalid declarations.
04040   if (FD->isInvalidDecl())
04041     return false;
04042 
04043   // Or declarations that aren't global.
04044   if (!FD->isGlobal())
04045     return false;
04046 
04047   // Don't warn about C++ member functions.
04048   if (isa<CXXMethodDecl>(FD))
04049     return false;
04050 
04051   // Don't warn about 'main'.
04052   if (FD->isMain())
04053     return false;
04054 
04055   // Don't warn about inline functions.
04056   if (FD->isInlineSpecified())
04057     return false;
04058 
04059   // Don't warn about function templates.
04060   if (FD->getDescribedFunctionTemplate())
04061     return false;
04062 
04063   // Don't warn about function template specializations.
04064   if (FD->isFunctionTemplateSpecialization())
04065     return false;
04066 
04067   bool MissingPrototype = true;
04068   for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
04069        Prev; Prev = Prev->getPreviousDeclaration()) {
04070     // Ignore any declarations that occur in function or method
04071     // scope, because they aren't visible from the header.
04072     if (Prev->getDeclContext()->isFunctionOrMethod())
04073       continue;
04074       
04075     MissingPrototype = !Prev->getType()->isFunctionProtoType();
04076     break;
04077   }
04078     
04079   return MissingPrototype;
04080 }
04081 
04082 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
04083   // Clear the last template instantiation error context.
04084   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
04085   
04086   if (!D)
04087     return D;
04088   FunctionDecl *FD = 0;
04089 
04090   if (FunctionTemplateDecl *FunTmpl
04091         = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
04092     FD = FunTmpl->getTemplatedDecl();
04093   else
04094     FD = cast<FunctionDecl>(D.getAs<Decl>());
04095 
04096   // Enter a new function scope
04097   PushFunctionScope();
04098 
04099   // See if this is a redefinition.
04100   // But don't complain if we're in GNU89 mode and the previous definition
04101   // was an extern inline function.
04102   const FunctionDecl *Definition;
04103   if (FD->getBody(Definition) &&
04104       !canRedefineFunction(Definition, getLangOptions())) {
04105     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
04106     Diag(Definition->getLocation(), diag::note_previous_definition);
04107   }
04108 
04109   // Builtin functions cannot be defined.
04110   if (unsigned BuiltinID = FD->getBuiltinID()) {
04111     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
04112       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
04113       FD->setInvalidDecl();
04114     }
04115   }
04116 
04117   // The return type of a function definition must be complete
04118   // (C99 6.9.1p3, C++ [dcl.fct]p6).
04119   QualType ResultType = FD->getResultType();
04120   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
04121       !FD->isInvalidDecl() &&
04122       RequireCompleteType(FD->getLocation(), ResultType,
04123                           diag::err_func_def_incomplete_result))
04124     FD->setInvalidDecl();
04125 
04126   // GNU warning -Wmissing-prototypes:
04127   //   Warn if a global function is defined without a previous
04128   //   prototype declaration. This warning is issued even if the
04129   //   definition itself provides a prototype. The aim is to detect
04130   //   global functions that fail to be declared in header files.
04131   if (ShouldWarnAboutMissingPrototype(FD))
04132     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
04133 
04134   if (FnBodyScope)
04135     PushDeclContext(FnBodyScope, FD);
04136 
04137   // Check the validity of our function parameters
04138   CheckParmsForFunctionDef(FD);
04139 
04140   // Introduce our parameters into the function scope
04141   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
04142     ParmVarDecl *Param = FD->getParamDecl(p);
04143     Param->setOwningFunction(FD);
04144 
04145     // If this has an identifier, add it to the scope stack.
04146     if (Param->getIdentifier() && FnBodyScope)
04147       PushOnScopeChains(Param, FnBodyScope);
04148   }
04149 
04150   // Checking attributes of current function definition
04151   // dllimport attribute.
04152   if (FD->getAttr<DLLImportAttr>() &&
04153       (!FD->getAttr<DLLExportAttr>())) {
04154     // dllimport attribute cannot be applied to definition.
04155     if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
04156       Diag(FD->getLocation(),
04157            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
04158         << "dllimport";
04159       FD->setInvalidDecl();
04160       return DeclPtrTy::make(FD);
04161     }
04162 
04163     // Visual C++ appears to not think this is an issue, so only issue
04164     // a warning when Microsoft extensions are disabled.
04165     if (!LangOpts.Microsoft) {
04166       // If a symbol previously declared dllimport is later defined, the
04167       // attribute is ignored in subsequent references, and a warning is
04168       // emitted.
04169       Diag(FD->getLocation(),
04170            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
04171         << FD->getNameAsCString() << "dllimport";
04172     }
04173   }
04174   return DeclPtrTy::make(FD);
04175 }
04176 
04177 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
04178   return ActOnFinishFunctionBody(D, move(BodyArg), false);
04179 }
04180 
04181 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
04182                                               bool IsInstantiation) {
04183   Decl *dcl = D.getAs<Decl>();
04184   Stmt *Body = BodyArg.takeAs<Stmt>();
04185 
04186   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
04187   // explosion for destrutors that can result and the compile time hit.
04188   AnalysisContext AC(dcl, false);
04189   FunctionDecl *FD = 0;
04190   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
04191   if (FunTmpl)
04192     FD = FunTmpl->getTemplatedDecl();
04193   else
04194     FD = dyn_cast_or_null<FunctionDecl>(dcl);
04195 
04196   if (FD) {
04197     FD->setBody(Body);
04198     if (FD->isMain())
04199       // C and C++ allow for main to automagically return 0.
04200       // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
04201       FD->setHasImplicitReturnZero(true);
04202     else
04203       CheckFallThroughForFunctionDef(FD, Body, AC);
04204 
04205     if (!FD->isInvalidDecl())
04206       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
04207 
04208     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
04209       MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
04210 
04211     assert(FD == getCurFunctionDecl() && "Function parsing confused");
04212   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
04213     assert(MD == getCurMethodDecl() && "Method parsing confused");
04214     MD->setBody(Body);
04215     CheckFallThroughForFunctionDef(MD, Body, AC);
04216     MD->setEndLoc(Body->getLocEnd());
04217 
04218     if (!MD->isInvalidDecl())
04219       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
04220   } else {
04221     Body->Destroy(Context);
04222     return DeclPtrTy();
04223   }
04224   if (!IsInstantiation)
04225     PopDeclContext();
04226 
04227   // Verify and clean out per-function state.
04228 
04229   // Check goto/label use.
04230   for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
04231        I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
04232     LabelStmt *L = I->second;
04233 
04234     // Verify that we have no forward references left.  If so, there was a goto
04235     // or address of a label taken, but no definition of it.  Label fwd
04236     // definitions are indicated with a null substmt.
04237     if (L->getSubStmt() != 0)
04238       continue;
04239 
04240     // Emit error.
04241     Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
04242 
04243     // At this point, we have gotos that use the bogus label.  Stitch it into
04244     // the function body so that they aren't leaked and that the AST is well
04245     // formed.
04246     if (Body == 0) {
04247       // The whole function wasn't parsed correctly, just delete this.
04248       L->Destroy(Context);
04249       continue;
04250     }
04251 
04252     // Otherwise, the body is valid: we want to stitch the label decl into the
04253     // function somewhere so that it is properly owned and so that the goto
04254     // has a valid target.  Do this by creating a new compound stmt with the
04255     // label in it.
04256 
04257     // Give the label a sub-statement.
04258     L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
04259 
04260     CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
04261                                cast<CXXTryStmt>(Body)->getTryBlock() :
04262                                cast<CompoundStmt>(Body);
04263     llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
04264                                           Compound->body_end());
04265     Elements.push_back(L);
04266     Compound->setStmts(Context, Elements.data(), Elements.size());
04267   }
04268 
04269   if (Body) {
04270     CheckUnreachable(AC);
04271 
04272     // C++ constructors that have function-try-blocks can't have return
04273     // statements in the handlers of that block. (C++ [except.handle]p14)
04274     // Verify this.
04275     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
04276       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
04277     
04278   // Verify that that gotos and switch cases don't jump into scopes illegally.
04279   // Verify that that gotos and switch cases don't jump into scopes illegally.
04280     if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
04281       DiagnoseInvalidJumps(Body);
04282 
04283     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
04284       MarkBaseAndMemberDestructorsReferenced(Destructor);
04285     
04286     // If any errors have occurred, clear out any temporaries that may have
04287     // been leftover. This ensures that these temporaries won't be picked up for
04288     // deletion in some later function.
04289     if (PP.getDiagnostics().hasErrorOccurred())
04290       ExprTemporaries.clear();
04291     
04292     assert(ExprTemporaries.empty() && "Leftover temporaries in function");
04293   }
04294   
04295   PopFunctionOrBlockScope();
04296   
04297   // If any errors have occurred, clear out any temporaries that may have
04298   // been leftover. This ensures that these temporaries won't be picked up for
04299   // deletion in some later function.
04300   if (getDiagnostics().hasErrorOccurred())
04301     ExprTemporaries.clear();
04302   
04303   return D;
04304 }
04305 
04306 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
04307 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
04308 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
04309                                           IdentifierInfo &II, Scope *S) {
04310   // Before we produce a declaration for an implicitly defined
04311   // function, see whether there was a locally-scoped declaration of
04312   // this name as a function or variable. If so, use that
04313   // (non-visible) declaration, and complain about it.
04314   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
04315     = LocallyScopedExternalDecls.find(&II);
04316   if (Pos != LocallyScopedExternalDecls.end()) {
04317     Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
04318     Diag(Pos->second->getLocation(), diag::note_previous_declaration);
04319     return Pos->second;
04320   }
04321 
04322   // Extension in C99.  Legal in C90, but warn about it.
04323   if (II.getName().startswith("__builtin_"))
04324     Diag(Loc, diag::warn_builtin_unknown) << &II;
04325   else if (getLangOptions().C99)
04326     Diag(Loc, diag::ext_implicit_function_decl) << &II;
04327   else
04328     Diag(Loc, diag::warn_implicit_function_decl) << &II;
04329 
04330   // Set a Declarator for the implicit definition: int foo();
04331   const char *Dummy;
04332   DeclSpec DS;
04333   unsigned DiagID;
04334   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
04335   Error = Error; // Silence warning.
04336   assert(!Error && "Error setting up implicit decl!");
04337   Declarator D(DS, Declarator::BlockContext);
04338   D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
04339                                              0, 0, false, SourceLocation(),
04340                                              false, 0,0,0, Loc, Loc, D),
04341                 SourceLocation());
04342   D.SetIdentifier(&II, Loc);
04343 
04344   // Insert this function into translation-unit scope.
04345 
04346   DeclContext *PrevDC = CurContext;
04347   CurContext = Context.getTranslationUnitDecl();
04348 
04349   FunctionDecl *FD =
04350  dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
04351   FD->setImplicit();
04352 
04353   CurContext = PrevDC;
04354 
04355   AddKnownFunctionAttributes(FD);
04356 
04357   return FD;
04358 }
04359 
04360 /// \brief Adds any function attributes that we know a priori based on
04361 /// the declaration of this function.
04362 ///
04363 /// These attributes can apply both to implicitly-declared builtins
04364 /// (like __builtin___printf_chk) or to library-declared functions
04365 /// like NSLog or printf.
04366 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
04367   if (FD->isInvalidDecl())
04368     return;
04369 
04370   // If this is a built-in function, map its builtin attributes to
04371   // actual attributes.
04372   if (unsigned BuiltinID = FD->getBuiltinID()) {
04373     // Handle printf-formatting attributes.
04374     unsigned FormatIdx;
04375     bool HasVAListArg;
04376     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
04377       if (!FD->getAttr<FormatAttr>())
04378         FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
04379                                                HasVAListArg ? 0 : FormatIdx+2));
04380     }
04381 
04382     // Mark const if we don't care about errno and that is the only
04383     // thing preventing the function from being const. This allows
04384     // IRgen to use LLVM intrinsics for such functions.
04385     if (!getLangOptions().MathErrno &&
04386         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
04387       if (!FD->getAttr<ConstAttr>())
04388         FD->addAttr(::new (Context) ConstAttr());
04389     }
04390 
04391     if (Context.BuiltinInfo.isNoReturn(BuiltinID))
04392       FD->setType(Context.getNoReturnType(FD->getType()));
04393     if (Context.BuiltinInfo.isNoThrow(BuiltinID))
04394       FD->addAttr(::new (Context) NoThrowAttr());
04395     if (Context.BuiltinInfo.isConst(BuiltinID))
04396       FD->addAttr(::new (Context) ConstAttr());
04397   }
04398 
04399   IdentifierInfo *Name = FD->getIdentifier();
04400   if (!Name)
04401     return;
04402   if ((!getLangOptions().CPlusPlus &&
04403        FD->getDeclContext()->isTranslationUnit()) ||
04404       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
04405        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
04406        LinkageSpecDecl::lang_c)) {
04407     // Okay: this could be a libc/libm/Objective-C function we know
04408     // about.
04409   } else
04410     return;
04411 
04412   if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
04413     // FIXME: NSLog and NSLogv should be target specific
04414     if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
04415       // FIXME: We known better than our headers.
04416       const_cast<FormatAttr *>(Format)->setType(Context, "printf");
04417     } else
04418       FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
04419                                              Name->isStr("NSLogv") ? 0 : 2));
04420   } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
04421     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
04422     // target-specific builtins, perhaps?
04423     if (!FD->getAttr<FormatAttr>())
04424       FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
04425                                              Name->isStr("vasprintf") ? 0 : 3));
04426   }
04427 }
04428 
04429 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
04430                                     TypeSourceInfo *TInfo) {
04431   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
04432   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
04433 
04434   if (!TInfo) {
04435     assert(D.isInvalidType() && "no declarator info for valid type");
04436     TInfo = Context.getTrivialTypeSourceInfo(T);
04437   }
04438 
04439   // Scope manipulation handled by caller.
04440   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
04441                                            D.getIdentifierLoc(),
04442                                            D.getIdentifier(),
04443                                            TInfo);
04444 
04445   if (const TagType *TT = T->getAs<TagType>()) {
04446     TagDecl *TD = TT->getDecl();
04447 
04448     // If the TagDecl that the TypedefDecl points to is an anonymous decl
04449     // keep track of the TypedefDecl.
04450     if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
04451       TD->setTypedefForAnonDecl(NewTD);
04452   }
04453 
04454   if (D.isInvalidType())
04455     NewTD->setInvalidDecl();
04456   return NewTD;
04457 }
04458 
04459 
04460 /// \brief Determine whether a tag with a given kind is acceptable
04461 /// as a redeclaration of the given tag declaration.
04462 ///
04463 /// \returns true if the new tag kind is acceptable, false otherwise.
04464 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
04465                                         TagDecl::TagKind NewTag,
04466                                         SourceLocation NewTagLoc,
04467                                         const IdentifierInfo &Name) {
04468   // C++ [dcl.type.elab]p3:
04469   //   The class-key or enum keyword present in the
04470   //   elaborated-type-specifier shall agree in kind with the
04471   //   declaration to which the name in theelaborated-type-specifier
04472   //   refers. This rule also applies to the form of
04473   //   elaborated-type-specifier that declares a class-name or
04474   //   friend class since it can be construed as referring to the
04475   //   definition of the class. Thus, in any
04476   //   elaborated-type-specifier, the enum keyword shall be used to
04477   //   refer to an enumeration (7.2), the union class-keyshall be
04478   //   used to refer to a union (clause 9), and either the class or
04479   //   struct class-key shall be used to refer to a class (clause 9)
04480   //   declared using the class or struct class-key.
04481   TagDecl::TagKind OldTag = Previous->getTagKind();
04482   if (OldTag == NewTag)
04483     return true;
04484 
04485   if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
04486       (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
04487     // Warn about the struct/class tag mismatch.
04488     bool isTemplate = false;
04489     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
04490       isTemplate = Record->getDescribedClassTemplate();
04491 
04492     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
04493       << (NewTag == TagDecl::TK_class)
04494       << isTemplate << &Name
04495       << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
04496                               OldTag == TagDecl::TK_class? "class" : "struct");
04497     Diag(Previous->getLocation(), diag::note_previous_use);
04498     return true;
04499   }
04500   return false;
04501 }
04502 
04503 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
04504 /// former case, Name will be non-null.  In the later case, Name will be null.
04505 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
04506 /// reference/declaration/definition of a tag.
04507 Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
04508                                SourceLocation KWLoc, const CXXScopeSpec &SS,
04509                                IdentifierInfo *Name, SourceLocation NameLoc,
04510                                AttributeList *Attr, AccessSpecifier AS,
04511                                MultiTemplateParamsArg TemplateParameterLists,
04512                                bool &OwnedDecl, bool &IsDependent) {
04513   // If this is not a definition, it must have a name.
04514   assert((Name != 0 || TUK == TUK_Definition) &&
04515          "Nameless record must be a definition!");
04516 
04517   OwnedDecl = false;
04518   TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
04519 
04520   // FIXME: Check explicit specializations more carefully.
04521   bool isExplicitSpecialization = false;
04522   if (TUK != TUK_Reference) {
04523     if (TemplateParameterList *TemplateParams
04524           = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
04525                         (TemplateParameterList**)TemplateParameterLists.get(),
04526                                               TemplateParameterLists.size(),
04527                                                     isExplicitSpecialization)) {
04528       if (TemplateParams->size() > 0) {
04529         // This is a declaration or definition of a class template (which may
04530         // be a member of another template).
04531         OwnedDecl = false;
04532         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
04533                                                SS, Name, NameLoc, Attr,
04534                                                TemplateParams,
04535                                                AS);
04536         TemplateParameterLists.release();
04537         return Result.get();
04538       } else {
04539         // The "template<>" header is extraneous.
04540         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
04541           << ElaboratedType::getNameForTagKind(Kind) << Name;
04542         isExplicitSpecialization = true;
04543       }
04544     }
04545              
04546     TemplateParameterLists.release();
04547   }
04548 
04549   DeclContext *SearchDC = CurContext;
04550   DeclContext *DC = CurContext;
04551   bool isStdBadAlloc = false;
04552   bool Invalid = false;
04553 
04554   RedeclarationKind Redecl = ForRedeclaration;
04555   if (TUK == TUK_Friend || TUK == TUK_Reference)
04556     Redecl = NotForRedeclaration;
04557 
04558   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
04559 
04560   if (Name && SS.isNotEmpty()) {
04561     // We have a nested-name tag ('struct foo::bar').
04562 
04563     // Check for invalid 'foo::'.
04564     if (SS.isInvalid()) {
04565       Name = 0;
04566       goto CreateNewDecl;
04567     }
04568 
04569     // If this is a friend or a reference to a class in a dependent
04570     // context, don't try to make a decl for it.
04571     if (TUK == TUK_Friend || TUK == TUK_Reference) {
04572       DC = computeDeclContext(SS, false);
04573       if (!DC) {
04574         IsDependent = true;
04575         return DeclPtrTy();
04576       }
04577     }
04578 
04579     if (RequireCompleteDeclContext(SS))
04580       return DeclPtrTy::make((Decl *)0);
04581 
04582     DC = computeDeclContext(SS, true);
04583     SearchDC = DC;
04584     // Look-up name inside 'foo::'.
04585     LookupQualifiedName(Previous, DC);
04586 
04587     if (Previous.isAmbiguous())
04588       return DeclPtrTy();
04589 
04590     if (Previous.empty()) {
04591       // Name lookup did not find anything. However, if the
04592       // nested-name-specifier refers to the current instantiation,
04593       // and that current instantiation has any dependent base
04594       // classes, we might find something at instantiation time: treat
04595       // this as a dependent elaborated-type-specifier.
04596       if (Previous.wasNotFoundInCurrentInstantiation()) {
04597         IsDependent = true;
04598         return DeclPtrTy();
04599       }
04600 
04601       // A tag 'foo::bar' must already exist.
04602       Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
04603       Name = 0;
04604       Invalid = true;
04605       goto CreateNewDecl;
04606     }
04607   } else if (Name) {
04608     // If this is a named struct, check to see if there was a previous forward
04609     // declaration or definition.
04610     // FIXME: We're looking into outer scopes here, even when we
04611     // shouldn't be. Doing so can result in ambiguities that we
04612     // shouldn't be diagnosing.
04613     LookupName(Previous, S);
04614 
04615     // Note:  there used to be some attempt at recovery here.
04616     if (Previous.isAmbiguous())
04617       return DeclPtrTy();
04618 
04619     if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
04620       // FIXME: This makes sure that we ignore the contexts associated
04621       // with C structs, unions, and enums when looking for a matching
04622       // tag declaration or definition. See the similar lookup tweak
04623       // in Sema::LookupName; is there a better way to deal with this?
04624       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
04625         SearchDC = SearchDC->getParent();
04626     }
04627   }
04628 
04629   if (Previous.isSingleResult() &&
04630       Previous.getFoundDecl()->isTemplateParameter()) {
04631     // Maybe we will complain about the shadowed template parameter.
04632     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
04633     // Just pretend that we didn't see the previous declaration.
04634     Previous.clear();
04635   }
04636 
04637   if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
04638       DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
04639     // This is a declaration of or a reference to "std::bad_alloc".
04640     isStdBadAlloc = true;
04641     
04642     if (Previous.empty() && StdBadAlloc) {
04643       // std::bad_alloc has been implicitly declared (but made invisible to
04644       // name lookup). Fill in this implicit declaration as the previous 
04645       // declaration, so that the declarations get chained appropriately.
04646       Previous.addDecl(StdBadAlloc);
04647     }
04648   }
04649 
04650   if (!Previous.empty()) {
04651     assert(Previous.isSingleResult());
04652     NamedDecl *PrevDecl = Previous.getFoundDecl();
04653     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
04654       // If this is a use of a previous tag, or if the tag is already declared
04655       // in the same scope (so that the definition/declaration completes or
04656       // rementions the tag), reuse the decl.
04657       if (TUK == TUK_Reference || TUK == TUK_Friend ||
04658           isDeclInScope(PrevDecl, SearchDC, S)) {
04659         // Make sure that this wasn't declared as an enum and now used as a
04660         // struct or something similar.
04661         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
04662           bool SafeToContinue
04663             = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
04664                Kind != TagDecl::TK_enum);
04665           if (SafeToContinue)
04666             Diag(KWLoc, diag::err_use_with_wrong_tag)
04667               << Name
04668               << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
04669                                                   PrevTagDecl->getKindName());
04670           else
04671             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
04672           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
04673 
04674           if (SafeToContinue)
04675             Kind = PrevTagDecl->getTagKind();
04676           else {
04677             // Recover by making this an anonymous redefinition.
04678             Name = 0;
04679             Previous.clear();
04680             Invalid = true;
04681           }
04682         }
04683 
04684         if (!Invalid) {
04685           // If this is a use, just return the declaration we found.
04686 
04687           // FIXME: In the future, return a variant or some other clue
04688           // for the consumer of this Decl to know it doesn't own it.
04689           // For our current ASTs this shouldn't be a problem, but will
04690           // need to be changed with DeclGroups.
04691           if (TUK == TUK_Reference || TUK == TUK_Friend)
04692             return DeclPtrTy::make(PrevTagDecl);
04693 
04694           // Diagnose attempts to redefine a tag.
04695           if (TUK == TUK_Definition) {
04696             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
04697               // If we're defining a specialization and the previous definition
04698               // is from an implicit instantiation, don't emit an error
04699               // here; we'll catch this in the general case below.
04700               if (!isExplicitSpecialization ||
04701                   !isa<CXXRecordDecl>(Def) ||
04702                   cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 
04703                                                == TSK_ExplicitSpecialization) {
04704                 Diag(NameLoc, diag::err_redefinition) << Name;
04705                 Diag(Def->getLocation(), diag::note_previous_definition);
04706                 // If this is a redefinition, recover by making this
04707                 // struct be anonymous, which will make any later
04708                 // references get the previous definition.
04709                 Name = 0;
04710                 Previous.clear();
04711                 Invalid = true;
04712               }
04713             } else {
04714               // If the type is currently being defined, complain
04715               // about a nested redefinition.
04716               TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
04717               if (Tag->isBeingDefined()) {
04718                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
04719                 Diag(PrevTagDecl->getLocation(),
04720                      diag::note_previous_definition);
04721                 Name = 0;
04722                 Previous.clear();
04723                 Invalid = true;
04724               }
04725             }
04726 
04727             // Okay, this is definition of a previously declared or referenced
04728             // tag PrevDecl. We're going to create a new Decl for it.
04729           }
04730         }
04731         // If we get here we have (another) forward declaration or we
04732         // have a definition.  Just create a new decl.
04733 
04734       } else {
04735         // If we get here, this is a definition of a new tag type in a nested
04736         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
04737         // new decl/type.  We set PrevDecl to NULL so that the entities
04738         // have distinct types.
04739         Previous.clear();
04740       }
04741       // If we get here, we're going to create a new Decl. If PrevDecl
04742       // is non-NULL, it's a definition of the tag declared by
04743       // PrevDecl. If it's NULL, we have a new definition.
04744     } else {
04745       // PrevDecl is a namespace, template, or anything else
04746       // that lives in the IDNS_Tag identifier namespace.
04747       if (isDeclInScope(PrevDecl, SearchDC, S)) {
04748         // The tag name clashes with a namespace name, issue an error and
04749         // recover by making this tag be anonymous.
04750         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
04751         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
04752         Name = 0;
04753         Previous.clear();
04754         Invalid = true;
04755       } else {
04756         // The existing declaration isn't relevant to us; we're in a
04757         // new scope, so clear out the previous declaration.
04758         Previous.clear();
04759       }
04760     }
04761   } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
04762     // C++ [basic.scope.pdecl]p5:
04763     //   -- for an elaborated-type-specifier of the form
04764     //
04765     //          class-key identifier
04766     //
04767     //      if the elaborated-type-specifier is used in the
04768     //      decl-specifier-seq or parameter-declaration-clause of a
04769     //      function defined in namespace scope, the identifier is
04770     //      declared as a class-name in the namespace that contains
04771     //      the declaration; otherwise, except as a friend
04772     //      declaration, the identifier is declared in the smallest
04773     //      non-class, non-function-prototype scope that contains the
04774     //      declaration.
04775     //
04776     // C99 6.7.2.3p8 has a similar (but not identical!) provision for
04777     // C structs and unions.
04778     //
04779     // It is an error in C++ to declare (rather than define) an enum
04780     // type, including via an elaborated type specifier.  We'll
04781     // diagnose that later; for now, declare the enum in the same
04782     // scope as we would have picked for any other tag type.
04783     //
04784     // GNU C also supports this behavior as part of its incomplete
04785     // enum types extension, while GNU C++ does not.
04786     //
04787     // Find the context where we'll be declaring the tag.
04788     // FIXME: We would like to maintain the current DeclContext as the
04789     // lexical context,
04790     while (SearchDC->isRecord())
04791       SearchDC = SearchDC->getParent();
04792 
04793     // Find the scope where we'll be declaring the tag.
04794     while (S->isClassScope() ||
04795            (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
04796            ((S->getFlags() & Scope::DeclScope) == 0) ||
04797            (S->getEntity() &&
04798             ((DeclContext *)S->getEntity())->isTransparentContext()))
04799       S = S->getParent();
04800 
04801   } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
04802     // C++ [namespace.memdef]p3:
04803     //   If a friend declaration in a non-local class first declares a
04804     //   class or function, the friend class or function is a member of
04805     //   the innermost enclosing namespace.
04806     SearchDC = SearchDC->getEnclosingNamespaceContext();
04807 
04808     // Look up through our scopes until we find one with an entity which
04809     // matches our declaration context.
04810     while (S->getEntity() &&
04811            ((DeclContext *)S->getEntity())->getPrimaryContext() != SearchDC) {
04812       S = S->getParent();
04813       assert(S && "No enclosing scope matching the enclosing namespace.");
04814     }
04815   }
04816 
04817 CreateNewDecl:
04818 
04819   TagDecl *PrevDecl = 0;
04820   if (Previous.isSingleResult())
04821     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
04822 
04823   // If there is an identifier, use the location of the identifier as the
04824   // location of the decl, otherwise use the location of the struct/union
04825   // keyword.
04826   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
04827 
04828   // Otherwise, create a new declaration. If there is a previous
04829   // declaration of the same entity, the two will be linked via
04830   // PrevDecl.
04831   TagDecl *New;
04832 
04833   if (Kind == TagDecl::TK_enum) {
04834     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
04835     // enum X { A, B, C } D;    D should chain to X.
04836     New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
04837                            cast_or_null<EnumDecl>(PrevDecl));
04838     // If this is an undefined enum, warn.
04839     if (TUK != TUK_Definition && !Invalid)  {
04840       unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
04841                                               : diag::ext_forward_ref_enum;
04842       Diag(Loc, DK);
04843     }
04844   } else {
04845     // struct/union/class
04846 
04847     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
04848     // struct X { int A; } D;    D should chain to X.
04849     if (getLangOptions().CPlusPlus) {
04850       // FIXME: Look for a way to use RecordDecl for simple structs.
04851       New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
04852                                   cast_or_null<CXXRecordDecl>(PrevDecl));
04853       
04854       if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
04855         StdBadAlloc = cast<CXXRecordDecl>(New);
04856     } else
04857       New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
04858                                cast_or_null<RecordDecl>(PrevDecl));
04859   }
04860 
04861   // Maybe add qualifier info.
04862   if (SS.isNotEmpty()) {
04863     NestedNameSpecifier *NNS
04864       = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
04865     New->setQualifierInfo(NNS, SS.getRange());
04866   }
04867 
04868   if (Kind != TagDecl::TK_enum) {
04869     // Handle #pragma pack: if the #pragma pack stack has non-default
04870     // alignment, make up a packed attribute for this decl. These
04871     // attributes are checked when the ASTContext lays out the
04872     // structure.
04873     //
04874     // It is important for implementing the correct semantics that this
04875     // happen here (in act on tag decl). The #pragma pack stack is
04876     // maintained as a result of parser callbacks which can occur at
04877     // many points during the parsing of a struct declaration (because
04878     // the #pragma tokens are effectively skipped over during the
04879     // parsing of the struct).
04880     if (unsigned Alignment = getPragmaPackAlignment())
04881       New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
04882   }
04883 
04884   if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
04885     // C++ [dcl.typedef]p3:
04886     //   [...] Similarly, in a given scope, a class or enumeration
04887     //   shall not be declared with the same name as a typedef-name
04888     //   that is declared in that scope and refers to a type other
04889     //   than the class or enumeration itself.
04890     LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
04891                         ForRedeclaration);
04892     LookupName(Lookup, S);
04893     TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
04894     NamedDecl *PrevTypedefNamed = PrevTypedef;
04895     if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
04896         Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
04897           Context.getCanonicalType(Context.getTypeDeclType(New))) {
04898       Diag(Loc, diag::err_tag_definition_of_typedef)
04899         << Context.getTypeDeclType(New)
04900         << PrevTypedef->getUnderlyingType();
04901       Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
04902       Invalid = true;
04903     }
04904   }
04905 
04906   // If this is a specialization of a member class (of a class template),
04907   // check the specialization.
04908   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
04909     Invalid = true;
04910       
04911   if (Invalid)
04912     New->setInvalidDecl();
04913 
04914   if (Attr)
04915     ProcessDeclAttributeList(S, New, Attr);
04916 
04917   // If we're declaring or defining a tag in function prototype scope
04918   // in C, note that this type can only be used within the function.
04919   if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
04920     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
04921 
04922   // Set the lexical context. If the tag has a C++ scope specifier, the
04923   // lexical context will be different from the semantic context.
04924   New->setLexicalDeclContext(CurContext);
04925 
04926   // Mark this as a friend decl if applicable.
04927   if (TUK == TUK_Friend)
04928     New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
04929 
04930   // Set the access specifier.
04931   if (!Invalid && TUK != TUK_Friend)
04932     SetMemberAccessSpecifier(New, PrevDecl, AS);
04933 
04934   if (TUK == TUK_Definition)
04935     New->startDefinition();
04936 
04937   // If this has an identifier, add it to the scope stack.
04938   if (TUK == TUK_Friend) {
04939     // We might be replacing an existing declaration in the lookup tables;
04940     // if so, borrow its access specifier.
04941     if (PrevDecl)
04942       New->setAccess(PrevDecl->getAccess());
04943 
04944     // Friend tag decls are visible in fairly strange ways.
04945     if (!CurContext->isDependentContext()) {
04946       DeclContext *DC = New->getDeclContext()->getLookupContext();
04947       DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
04948       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
04949         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
04950     }
04951   } else if (Name) {
04952     S = getNonFieldDeclScope(S);
04953     PushOnScopeChains(New, S);
04954   } else {
04955     CurContext->addDecl(New);
04956   }
04957 
04958   // If this is the C FILE type, notify the AST context.
04959   if (IdentifierInfo *II = New->getIdentifier())
04960     if (!New->isInvalidDecl() &&
04961         New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
04962         II->isStr("FILE"))
04963       Context.setFILEDecl(New);
04964 
04965   OwnedDecl = true;
04966   return DeclPtrTy::make(New);
04967 }
04968 
04969 void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
04970   AdjustDeclIfTemplate(TagD);
04971   TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
04972 
04973   // Enter the tag context.
04974   PushDeclContext(S, Tag);
04975 }
04976 
04977 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
04978                                            SourceLocation LBraceLoc) {
04979   AdjustDeclIfTemplate(TagD);
04980   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
04981 
04982   FieldCollector->StartClass();
04983 
04984   if (!Record->getIdentifier())
04985     return;
04986 
04987   // C++ [class]p2:
04988   //   [...] The class-name is also inserted into the scope of the
04989   //   class itself; this is known as the injected-class-name. For
04990   //   purposes of access checking, the injected-class-name is treated
04991   //   as if it were a public member name.
04992   CXXRecordDecl *InjectedClassName
04993     = CXXRecordDecl::Create(Context, Record->getTagKind(),
04994                             CurContext, Record->getLocation(),
04995                             Record->getIdentifier(),
04996                             Record->getTagKeywordLoc(),
04997                             Record);
04998   InjectedClassName->setImplicit();
04999   InjectedClassName->setAccess(AS_public);
05000   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
05001       InjectedClassName->setDescribedClassTemplate(Template);
05002   PushOnScopeChains(InjectedClassName, S);
05003   assert(InjectedClassName->isInjectedClassName() &&
05004          "Broken injected-class-name");
05005 }
05006 
05007 // Traverses the class and any nested classes, making a note of any 
05008 // dynamic classes that have no key function so that we can mark all of
05009 // their virtual member functions as "used" at the end of the translation
05010 // unit. This ensures that all functions needed by the vtable will get
05011 // instantiated/synthesized.
05012 static void 
05013 RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
05014                                       SourceLocation Loc) {
05015   // We don't look at dependent or undefined classes.
05016   if (Record->isDependentContext() || !Record->isDefinition())
05017     return;
05018   
05019   if (Record->isDynamicClass()) {
05020     const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
05021   
05022     if (!KeyFunction)
05023       S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
05024                                                                    Loc));
05025 
05026     if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
05027         && Record->getLinkage() == ExternalLinkage)
05028       S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
05029   }
05030   for (DeclContext::decl_iterator D = Record->decls_begin(), 
05031                                DEnd = Record->decls_end();
05032        D != DEnd; ++D) {
05033     if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
05034       RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
05035   }
05036 }
05037 
05038 void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
05039                                     SourceLocation RBraceLoc) {
05040   AdjustDeclIfTemplate(TagD);
05041   TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
05042   Tag->setRBraceLoc(RBraceLoc);
05043 
05044   if (isa<CXXRecordDecl>(Tag))
05045     FieldCollector->FinishClass();
05046 
05047   // Exit this scope of this tag's definition.
05048   PopDeclContext();
05049 
05050   if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord())
05051     RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
05052                                           RBraceLoc);
05053                                           
05054   // Notify the consumer that we've defined a tag.
05055   Consumer.HandleTagDeclDefinition(Tag);
05056 }
05057 
05058 // Note that FieldName may be null for anonymous bitfields.
05059 bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
05060                           QualType FieldTy, const Expr *BitWidth,
05061                           bool *ZeroWidth) {
05062   // Default to true; that shouldn't confuse checks for emptiness
05063   if (ZeroWidth)
05064     *ZeroWidth = true;
05065 
05066   // C99 6.7.2.1p4 - verify the field type.
05067   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
05068   if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
05069     // Handle incomplete types with specific error.
05070     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
05071       return true;
05072     if (FieldName)
05073       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
05074         << FieldName << FieldTy << BitWidth->getSourceRange();
05075     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
05076       << FieldTy << BitWidth->getSourceRange();
05077   }
05078 
05079   // If the bit-width is type- or value-dependent, don't try to check
05080   // it now.
05081   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
05082     return false;
05083 
05084   llvm::APSInt Value;
05085   if (VerifyIntegerConstantExpression(BitWidth, &Value))
05086     return true;
05087 
05088   if (Value != 0 && ZeroWidth)
05089     *ZeroWidth = false;
05090 
05091   // Zero-width bitfield is ok for anonymous field.
05092   if (Value == 0 && FieldName)
05093     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
05094 
05095   if (Value.isSigned() && Value.isNegative()) {
05096     if (FieldName)
05097       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
05098                << FieldName << Value.toString(10);
05099     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
05100       << Value.toString(10);
05101   }
05102 
05103   if (!FieldTy->isDependentType()) {
05104     uint64_t TypeSize = Context.getTypeSize(FieldTy);
05105     if (Value.getZExtValue() > TypeSize) {
05106       if (FieldName)
05107         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
05108           << FieldName << (unsigned)TypeSize;
05109       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
05110         << (unsigned)TypeSize;
05111     }
05112   }
05113 
05114   return false;
05115 }
05116 
05117 /// ActOnField - Each field of a struct/union/class is passed into this in order
05118 /// to create a FieldDecl object for it.
05119 Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
05120                                  SourceLocation DeclStart,
05121                                  Declarator &D, ExprTy *BitfieldWidth) {
05122   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
05123                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
05124                                AS_public);
05125   return DeclPtrTy::make(Res);
05126 }
05127 
05128 /// HandleField - Analyze a field of a C struct or a C++ data member.
05129 ///
05130 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
05131                              SourceLocation DeclStart,
05132                              Declarator &D, Expr *BitWidth,
05133                              AccessSpecifier AS) {
05134   IdentifierInfo *II = D.getIdentifier();
05135   SourceLocation Loc = DeclStart;
05136   if (II) Loc = D.getIdentifierLoc();
05137 
05138   TypeSourceInfo *TInfo = 0;
05139   QualType T = GetTypeForDeclarator(D, S, &TInfo);
05140   if (getLangOptions().CPlusPlus)
05141     CheckExtraCXXDefaultArguments(D);
05142 
05143   DiagnoseFunctionSpecifiers(D);
05144 
05145   if (D.getDeclSpec().isThreadSpecified())
05146     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
05147 
05148   NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
05149                                          ForRedeclaration);
05150 
05151   if (PrevDecl && PrevDecl->isTemplateParameter()) {
05152     // Maybe we will complain about the shadowed template parameter.
05153     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
05154     // Just pretend that we didn't see the previous declaration.
05155     PrevDecl = 0;
05156   }
05157 
05158   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
05159     PrevDecl = 0;
05160 
05161   bool Mutable
05162     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
05163   SourceLocation TSSL = D.getSourceRange().getBegin();
05164   FieldDecl *NewFD
05165     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
05166                      AS, PrevDecl, &D);
05167   if (NewFD->isInvalidDecl() && PrevDecl) {
05168     // Don't introduce NewFD into scope; there's already something
05169     // with the same name in the same scope.
05170   } else if (II) {
05171     PushOnScopeChains(NewFD, S);
05172   } else
05173     Record->addDecl(NewFD);
05174 
05175   return NewFD;
05176 }
05177 
05178 /// \brief Build a new FieldDecl and check its well-formedness.
05179 ///
05180 /// This routine builds a new FieldDecl given the fields name, type,
05181 /// record, etc. \p PrevDecl should refer to any previous declaration
05182 /// with the same name and in the same scope as the field to be
05183 /// created.
05184 ///
05185 /// \returns a new FieldDecl.
05186 ///
05187 /// \todo The Declarator argument is a hack. It will be removed once
05188 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
05189                                 TypeSourceInfo *TInfo,
05190                                 RecordDecl *Record, SourceLocation Loc,
05191                                 bool Mutable, Expr *BitWidth,
05192                                 SourceLocation TSSL,
05193                                 AccessSpecifier AS, NamedDecl *PrevDecl,
05194                                 Declarator *D) {
05195   IdentifierInfo *II = Name.getAsIdentifierInfo();
05196   bool InvalidDecl = false;
05197   if (D) InvalidDecl = D->isInvalidType();
05198 
05199   // If we receive a broken type, recover by assuming 'int' and
05200   // marking this declaration as invalid.
05201   if (T.isNull()) {
05202     InvalidDecl = true;
05203     T = Context.IntTy;
05204   }
05205 
05206   QualType EltTy = Context.getBaseElementType(T);
05207   if (!EltTy->isDependentType() &&
05208       RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
05209     InvalidDecl = true;
05210 
05211   // C99 6.7.2.1p8: A member of a structure or union may have any type other
05212   // than a variably modified type.
05213   if (!InvalidDecl && T->isVariablyModifiedType()) {
05214     bool SizeIsNegative;
05215     QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
05216                                                            SizeIsNegative);
05217     if (!FixedTy.isNull()) {
05218       Diag(Loc, diag::warn_illegal_constant_array_size);
05219       T = FixedTy;
05220     } else {
05221       if (SizeIsNegative)
05222         Diag(Loc, diag::err_typecheck_negative_array_size);
05223       else
05224         Diag(Loc, diag::err_typecheck_field_variable_size);
05225       InvalidDecl = true;
05226     }
05227   }
05228 
05229   // Fields can not have abstract class types
05230   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
05231                                              diag::err_abstract_type_in_decl,
05232                                              AbstractFieldType))
05233     InvalidDecl = true;
05234 
05235   bool ZeroWidth = false;
05236   // If this is declared as a bit-field, check the bit-field.
05237   if (!InvalidDecl && BitWidth &&
05238       VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
05239     InvalidDecl = true;
05240     DeleteExpr(BitWidth);
05241     BitWidth = 0;
05242     ZeroWidth = false;
05243   }
05244 
05245   FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
05246                                        BitWidth, Mutable);
05247   if (InvalidDecl)
05248     NewFD->setInvalidDecl();
05249 
05250   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
05251     Diag(Loc, diag::err_duplicate_member) << II;
05252     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
05253     NewFD->setInvalidDecl();
05254   }
05255 
05256   if (!InvalidDecl && getLangOptions().CPlusPlus) {
05257     CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
05258 
05259     if (!T->isPODType())
05260       CXXRecord->setPOD(false);
05261     if (!ZeroWidth)
05262       CXXRecord->setEmpty(false);
05263 
05264     if (const RecordType *RT = EltTy->getAs<RecordType>()) {
05265       CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
05266 
05267       if (!RDecl->hasTrivialConstructor())
05268         CXXRecord->setHasTrivialConstructor(false);
05269       if (!RDecl->hasTrivialCopyConstructor())
05270         CXXRecord->setHasTrivialCopyConstructor(false);
05271       if (!RDecl->hasTrivialCopyAssignment())
05272         CXXRecord->setHasTrivialCopyAssignment(false);
05273       if (!RDecl->hasTrivialDestructor())
05274         CXXRecord->setHasTrivialDestructor(false);
05275 
05276       // C++ 9.5p1: An object of a class with a non-trivial
05277       // constructor, a non-trivial copy constructor, a non-trivial
05278       // destructor, or a non-trivial copy assignment operator
05279       // cannot be a member of a union, nor can an array of such
05280       // objects.
05281       // TODO: C++0x alters this restriction significantly.
05282       if (Record->isUnion()) {
05283         // We check for copy constructors before constructors
05284         // because otherwise we'll never get complaints about
05285         // copy constructors.
05286 
05287         const CXXSpecialMember invalid = (CXXSpecialMember) -1;
05288 
05289         CXXSpecialMember member;
05290         if (!RDecl->hasTrivialCopyConstructor())
05291           member = CXXCopyConstructor;
05292         else if (!RDecl->hasTrivialConstructor())
05293           member = CXXDefaultConstructor;
05294         else if (!RDecl->hasTrivialCopyAssignment())
05295           member = CXXCopyAssignment;
05296         else if (!RDecl->hasTrivialDestructor())
05297           member = CXXDestructor;
05298         else
05299           member = invalid;
05300 
05301         if (member != invalid) {
05302           Diag(Loc, diag::err_illegal_union_member) << Name << member;
05303           DiagnoseNontrivial(RT, member);
05304           NewFD->setInvalidDecl();
05305         }
05306       }
05307     }
05308   }
05309 
05310   // FIXME: We need to pass in the attributes given an AST
05311   // representation, not a parser representation.
05312   if (D)
05313     // FIXME: What to pass instead of TUScope?
05314     ProcessDeclAttributes(TUScope, NewFD, *D);
05315 
05316   if (T.isObjCGCWeak())
05317     Diag(Loc, diag::warn_attribute_weak_on_field);
05318 
05319   NewFD->setAccess(AS);
05320 
05321   // C++ [dcl.init.aggr]p1:
05322   //   An aggregate is an array or a class (clause 9) with [...] no
05323   //   private or protected non-static data members (clause 11).
05324   // A POD must be an aggregate.
05325   if (getLangOptions().CPlusPlus &&
05326       (AS == AS_private || AS == AS_protected)) {
05327     CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
05328     CXXRecord->setAggregate(false);
05329     CXXRecord->setPOD(false);
05330   }
05331 
05332   return NewFD;
05333 }
05334 
05335 /// DiagnoseNontrivial - Given that a class has a non-trivial
05336 /// special member, figure out why.
05337 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
05338   QualType QT(T, 0U);
05339   CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
05340 
05341   // Check whether the member was user-declared.
05342   switch (member) {
05343   case CXXDefaultConstructor:
05344     if (RD->hasUserDeclaredConstructor()) {
05345       typedef CXXRecordDecl::ctor_iterator ctor_iter;
05346       for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
05347         const FunctionDecl *body = 0;
05348         ci->getBody(body);
05349         if (!body ||
05350             !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
05351           SourceLocation CtorLoc = ci->getLocation();
05352           Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
05353           return;
05354         }
05355       }
05356 
05357       assert(0 && "found no user-declared constructors");
05358       return;
05359     }
05360     break;
05361 
05362   case CXXCopyConstructor:
05363     if (RD->hasUserDeclaredCopyConstructor()) {
05364       SourceLocation CtorLoc =
05365         RD->getCopyConstructor(Context, 0)->getLocation();
05366       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
05367       return;
05368     }
05369     break;
05370 
05371   case CXXCopyAssignment:
05372     if (RD->hasUserDeclaredCopyAssignment()) {
05373       // FIXME: this should use the location of the copy
05374       // assignment, not the type.
05375       SourceLocation TyLoc = RD->getSourceRange().getBegin();
05376       Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
05377       return;
05378     }
05379     break;
05380 
05381   case CXXDestructor:
05382     if (RD->hasUserDeclaredDestructor()) {
05383       SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
05384       Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
05385       return;
05386     }
05387     break;
05388   }
05389 
05390   typedef CXXRecordDecl::base_class_iterator base_iter;
05391 
05392   // Virtual bases and members inhibit trivial copying/construction,
05393   // but not trivial destruction.
05394   if (member != CXXDestructor) {
05395     // Check for virtual bases.  vbases includes indirect virtual bases,
05396     // so we just iterate through the direct bases.
05397     for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
05398       if (bi->isVirtual()) {
05399         SourceLocation BaseLoc = bi->getSourceRange().getBegin();
05400         Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
05401         return;
05402       }
05403 
05404     // Check for virtual methods.
05405     typedef CXXRecordDecl::method_iterator meth_iter;
05406     for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
05407          ++mi) {
05408       if (mi->isVirtual()) {
05409         SourceLocation MLoc = mi->getSourceRange().getBegin();
05410         Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
05411         return;
05412       }
05413     }
05414   }
05415 
05416   bool (CXXRecordDecl::*hasTrivial)() const;
05417   switch (member) {
05418   case CXXDefaultConstructor:
05419     hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
05420   case CXXCopyConstructor:
05421     hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
05422   case CXXCopyAssignment:
05423     hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
05424   case CXXDestructor:
05425     hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
05426   default:
05427     assert(0 && "unexpected special member"); return;
05428   }
05429 
05430   // Check for nontrivial bases (and recurse).
05431   for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
05432     const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
05433     assert(BaseRT && "Don't know how to handle dependent bases");
05434     CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
05435     if (!(BaseRecTy->*hasTrivial)()) {
05436       SourceLocation BaseLoc = bi->getSourceRange().getBegin();
05437       Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
05438       DiagnoseNontrivial(BaseRT, member);
05439       return;
05440     }
05441   }
05442 
05443   // Check for nontrivial members (and recurse).
05444   typedef RecordDecl::field_iterator field_iter;
05445   for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
05446        ++fi) {
05447     QualType EltTy = Context.getBaseElementType((*fi)->getType());
05448     if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
05449       CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
05450 
05451       if (!(EltRD->*hasTrivial)()) {
05452         SourceLocation FLoc = (*fi)->getLocation();
05453         Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
05454         DiagnoseNontrivial(EltRT, member);
05455         return;
05456       }
05457     }
05458   }
05459 
05460   assert(0 && "found no explanation for non-trivial member");
05461 }
05462 
05463 /// TranslateIvarVisibility - Translate visibility from a token ID to an
05464 ///  AST enum value.
05465 static ObjCIvarDecl::AccessControl
05466 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
05467   switch (ivarVisibility) {
05468   default: assert(0 && "Unknown visitibility kind");
05469   case tok::objc_private: return ObjCIvarDecl::Private;
05470   case tok::objc_public: return ObjCIvarDecl::Public;
05471   case tok::objc_protected: return ObjCIvarDecl::Protected;
05472   case tok::objc_package: return ObjCIvarDecl::Package;
05473   }
05474 }
05475 
05476 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
05477 /// in order to create an IvarDecl object for it.
05478 Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
05479                                 SourceLocation DeclStart,
05480                                 DeclPtrTy IntfDecl,
05481                                 Declarator &D, ExprTy *BitfieldWidth,
05482                                 tok::ObjCKeywordKind Visibility) {
05483 
05484   IdentifierInfo *II = D.getIdentifier();
05485   Expr *BitWidth = (Expr*)BitfieldWidth;
05486   SourceLocation Loc = DeclStart;
05487   if (II) Loc = D.getIdentifierLoc();
05488 
05489   // FIXME: Unnamed fields can be handled in various different ways, for
05490   // example, unnamed unions inject all members into the struct namespace!
05491 
05492   TypeSourceInfo *TInfo = 0;
05493   QualType T = GetTypeForDeclarator(D, S, &TInfo);
05494 
05495   if (BitWidth) {
05496     // 6.7.2.1p3, 6.7.2.1p4
05497     if (VerifyBitField(Loc, II, T, BitWidth)) {
05498       D.setInvalidType();
05499       DeleteExpr(BitWidth);
05500       BitWidth = 0;
05501     }
05502   } else {
05503     // Not a bitfield.
05504 
05505     // validate II.
05506 
05507   }
05508 
05509   // C99 6.7.2.1p8: A member of a structure or union may have any type other
05510   // than a variably modified type.
05511   if (T->isVariablyModifiedType()) {
05512     Diag(Loc, diag::err_typecheck_ivar_variable_size);
05513     D.setInvalidType();
05514   }
05515 
05516   // Get the visibility (access control) for this ivar.
05517   ObjCIvarDecl::AccessControl ac =
05518     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
05519                                         : ObjCIvarDecl::None;
05520   // Must set ivar's DeclContext to its enclosing interface.
05521   Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
05522   DeclContext *EnclosingContext;
05523   if (ObjCImplementationDecl *IMPDecl =
05524       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
05525     // Case of ivar declared in an implementation. Context is that of its class.
05526     ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
05527     assert(IDecl && "No class- ActOnIvar");
05528     EnclosingContext = cast_or_null<DeclContext>(IDecl);
05529   } else
05530     EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
05531   assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
05532 
05533   // Construct the decl.
05534   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
05535                                              EnclosingContext, Loc, II, T,
05536                                              TInfo, ac, (Expr *)BitfieldWidth);
05537 
05538   if (II) {
05539     NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
05540                                            ForRedeclaration);
05541     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
05542         && !isa<TagDecl>(PrevDecl)) {
05543       Diag(Loc, diag::err_duplicate_member) << II;
05544       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
05545       NewID->setInvalidDecl();
05546     }
05547   }
05548 
05549   // Process attributes attached to the ivar.
05550   ProcessDeclAttributes(S, NewID, D);
05551 
05552   if (D.isInvalidType())
05553     NewID->setInvalidDecl();
05554 
05555   if (II) {
05556     // FIXME: When interfaces are DeclContexts, we'll need to add
05557     // these to the interface.
05558     S->AddDecl(DeclPtrTy::make(NewID));
05559     IdResolver.AddDecl(NewID);
05560   }
05561 
05562   return DeclPtrTy::make(NewID);
05563 }
05564 
05565 void Sema::ActOnFields(Scope* S,
05566                        SourceLocation RecLoc, DeclPtrTy RecDecl,
05567                        DeclPtrTy *Fields, unsigned NumFields,
05568                        SourceLocation LBrac, SourceLocation RBrac,
05569                        AttributeList *Attr) {
05570   Decl *EnclosingDecl = RecDecl.getAs<Decl>();
05571   assert(EnclosingDecl && "missing record or interface decl");
05572 
05573   // If the decl this is being inserted into is invalid, then it may be a
05574   // redeclaration or some other bogus case.  Don't try to add fields to it.
05575   if (EnclosingDecl->isInvalidDecl()) {
05576     // FIXME: Deallocate fields?
05577     return;
05578   }
05579 
05580 
05581   // Verify that all the fields are okay.
05582   unsigned NumNamedMembers = 0;
05583   llvm::SmallVector<FieldDecl*, 32> RecFields;
05584 
05585   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
05586   for (unsigned i = 0; i != NumFields; ++i) {
05587     FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
05588 
05589     // Get the type for the field.
05590     Type *FDTy = FD->getType().getTypePtr();
05591 
05592     if (!FD->isAnonymousStructOrUnion()) {
05593       // Remember all fields written by the user.
05594       RecFields.push_back(FD);
05595     }
05596 
05597     // If the field is already invalid for some reason, don't emit more
05598     // diagnostics about it.
05599     if (FD->isInvalidDecl()) {
05600       EnclosingDecl->setInvalidDecl();
05601       continue;
05602     }
05603 
05604     // C99 6.7.2.1p2:
05605     //   A structure or union shall not contain a member with
05606     //   incomplete or function type (hence, a structure shall not
05607     //   contain an instance of itself, but may contain a pointer to
05608     //   an instance of itself), except that the last member of a
05609     //   structure with more than one named member may have incomplete
05610     //   array type; such a structure (and any union containing,
05611     //   possibly recursively, a member that is such a structure)
05612     //   shall not be a member of a structure or an element of an
05613     //   array.
05614     if (FDTy->isFunctionType()) {
05615       // Field declared as a function.
05616       Diag(FD->getLocation(), diag::err_field_declared_as_function)
05617         << FD->getDeclName();
05618       FD->setInvalidDecl();
05619       EnclosingDecl->setInvalidDecl();
05620       continue;
05621     } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
05622                Record && Record->isStruct()) {
05623       // Flexible array member.
05624       if (NumNamedMembers < 1) {
05625         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
05626           << FD->getDeclName();
05627         FD->setInvalidDecl();
05628         EnclosingDecl->setInvalidDecl();
05629         continue;
05630       }
05631       // Okay, we have a legal flexible array member at the end of the struct.
05632       if (Record)
05633         Record->setHasFlexibleArrayMember(true);
05634     } else if (!FDTy->isDependentType() &&
05635                RequireCompleteType(FD->getLocation(), FD->getType(),
05636                                    diag::err_field_incomplete)) {
05637       // Incomplete type
05638       FD->setInvalidDecl();
05639       EnclosingDecl->setInvalidDecl();
05640       continue;
05641     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
05642       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
05643         // If this is a member of a union, then entire union becomes "flexible".
05644         if (Record && Record->isUnion()) {
05645           Record->setHasFlexibleArrayMember(true);
05646         } else {
05647           // If this is a struct/class and this is not the last element, reject
05648           // it.  Note that GCC supports variable sized arrays in the middle of
05649           // structures.
05650           if (i != NumFields-1)
05651             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
05652               << FD->getDeclName() << FD->getType();
05653           else {
05654             // We support flexible arrays at the end of structs in
05655             // other structs as an extension.
05656             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
05657               << FD->getDeclName();
05658             if (Record)
05659               Record->setHasFlexibleArrayMember(true);
05660           }
05661         }
05662       }
05663       if (Record && FDTTy->getDecl()->hasObjectMember())
05664         Record->setHasObjectMember(true);
05665     } else if (FDTy->isObjCInterfaceType()) {
05666       /// A field cannot be an Objective-c object
05667       Diag(FD->getLocation(), diag::err_statically_allocated_object);
05668       FD->setInvalidDecl();
05669       EnclosingDecl->setInvalidDecl();
05670       continue;
05671     } else if (getLangOptions().ObjC1 &&
05672                getLangOptions().getGCMode() != LangOptions::NonGC &&
05673                Record &&
05674                (FD->getType()->isObjCObjectPointerType() ||
05675                 FD->getType().isObjCGCStrong()))
05676       Record->setHasObjectMember(true);
05677     // Keep track of the number of named members.
05678     if (FD->getIdentifier())
05679       ++NumNamedMembers;
05680   }
05681 
05682   // Okay, we successfully defined 'Record'.
05683   if (Record) {
05684     Record->completeDefinition();
05685   } else {
05686     ObjCIvarDecl **ClsFields =
05687       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
05688     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
05689       ID->setLocEnd(RBrac);
05690       // Add ivar's to class's DeclContext.
05691       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
05692         ClsFields[i]->setLexicalDeclContext(ID);
05693         ID->addDecl(ClsFields[i]);
05694       }
05695       // Must enforce the rule that ivars in the base classes may not be
05696       // duplicates.
05697       if (ID->getSuperClass())
05698         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
05699     } else if (ObjCImplementationDecl *IMPDecl =
05700                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
05701       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
05702       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
05703         // Ivar declared in @implementation never belongs to the implementation.
05704         // Only it is in implementation's lexical context.
05705         ClsFields[I]->setLexicalDeclContext(IMPDecl);
05706       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
05707     } else if (ObjCCategoryDecl *CDecl = 
05708                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
05709       if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension())
05710         Diag(LBrac, diag::err_misplaced_ivar);
05711       else {
05712         // FIXME. Class extension does not have a LocEnd field.
05713         // CDecl->setLocEnd(RBrac);
05714         // Add ivar's to class extension's DeclContext.
05715         for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
05716           ClsFields[i]->setLexicalDeclContext(CDecl);
05717           CDecl->addDecl(ClsFields[i]);
05718         }
05719       }
05720     }
05721   }
05722 
05723   if (Attr)
05724     ProcessDeclAttributeList(S, Record, Attr);
05725 }
05726 
05727 /// \brief Determine whether the given integral value is representable within
05728 /// the given type T.
05729 static bool isRepresentableIntegerValue(ASTContext &Context,
05730                                         llvm::APSInt &Value,
05731                                         QualType T) {
05732   assert(T->isIntegralType() && "Integral type required!");
05733   unsigned BitWidth = Context.getTypeSize(T);
05734   
05735   if (Value.isUnsigned() || Value.isNonNegative())
05736     return Value.getActiveBits() < BitWidth;
05737   
05738   return Value.getMinSignedBits() <= BitWidth;
05739 }
05740 
05741 // \brief Given an integral type, return the next larger integral type
05742 // (or a NULL type of no such type exists).
05743 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
05744   // FIXME: Int128/UInt128 support, which also needs to be introduced into 
05745   // enum checking below.
05746   assert(T->isIntegralType() && "Integral type required!");
05747   const unsigned NumTypes = 4;
05748   QualType SignedIntegralTypes[NumTypes] = { 
05749     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
05750   };
05751   QualType UnsignedIntegralTypes[NumTypes] = { 
05752     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 
05753     Context.UnsignedLongLongTy
05754   };
05755   
05756   unsigned BitWidth = Context.getTypeSize(T);
05757   QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
05758                                             : UnsignedIntegralTypes;
05759   for (unsigned I = 0; I != NumTypes; ++I)
05760     if (Context.getTypeSize(Types[I]) > BitWidth)
05761       return Types[I];
05762   
05763   return QualType();
05764 }
05765 
05766 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
05767                                           EnumConstantDecl *LastEnumConst,
05768                                           SourceLocation IdLoc,
05769                                           IdentifierInfo *Id,
05770                                           ExprArg val) {
05771   Expr *Val = (Expr *)val.get();
05772 
05773   unsigned IntWidth = Context.Target.getIntWidth();
05774   llvm::APSInt EnumVal(IntWidth);
05775   QualType EltTy;
05776   if (Val) {
05777     if (Enum->isDependentType() || Val->isTypeDependent())
05778       EltTy = Context.DependentTy;
05779     else {
05780       // C99 6.7.2.2p2: Make sure we have an integer constant expression.
05781       SourceLocation ExpLoc;
05782       if (!Val->isValueDependent() &&
05783           VerifyIntegerConstantExpression(Val, &EnumVal)) {
05784         Val = 0;
05785       } else {        
05786         if (!getLangOptions().CPlusPlus) {
05787           // C99 6.7.2.2p2:
05788           //   The expression that defines the value of an enumeration constant
05789           //   shall be an integer constant expression that has a value 
05790           //   representable as an int.
05791           
05792           // Complain if the value is not representable in an int.
05793           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
05794             Diag(IdLoc, diag::ext_enum_value_not_int)
05795               << EnumVal.toString(10) << Val->getSourceRange()
05796               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
05797           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
05798             // Force the type of the expression to 'int'.
05799             ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
05800             
05801             if (Val != val.get()) {
05802               val.release();
05803               val = Val;
05804             }
05805           }
05806         }
05807         
05808         // C++0x [dcl.enum]p5:
05809         //   If the underlying type is not fixed, the type of each enumerator
05810         //   is the type of its initializing value:
05811         //     - If an initializer is specified for an enumerator, the 
05812         //       initializing value has the same type as the expression.
05813         EltTy = Val->getType();
05814       }
05815     }
05816   }
05817 
05818   if (!Val) {
05819     if (Enum->isDependentType())
05820       EltTy = Context.DependentTy;
05821     else if (!LastEnumConst) {
05822       // C++0x [dcl.enum]p5:
05823       //   If the underlying type is not fixed, the type of each enumerator
05824       //   is the type of its initializing value:
05825       //     - If no initializer is specified for the first enumerator, the 
05826       //       initializing value has an unspecified integral type.
05827       //
05828       // GCC uses 'int' for its unspecified integral type, as does 
05829       // C99 6.7.2.2p3.
05830       EltTy = Context.IntTy;
05831     } else {
05832       // Assign the last value + 1.
05833       EnumVal = LastEnumConst->getInitVal();
05834       ++EnumVal;
05835       EltTy = LastEnumConst->getType();
05836 
05837       // Check for overflow on increment.
05838       if (EnumVal < LastEnumConst->getInitVal()) {
05839         // C++0x [dcl.enum]p5:
05840         //   If the underlying type is not fixed, the type of each enumerator
05841         //   is the type of its initializing value:
05842         //
05843         //     - Otherwise the type of the initializing value is the same as
05844         //       the type of the initializing value of the preceding enumerator
05845         //       unless the incremented value is not representable in that type,
05846         //       in which case the type is an unspecified integral type 
05847         //       sufficient to contain the incremented value. If no such type
05848         //       exists, the program is ill-formed.
05849         QualType T = getNextLargerIntegralType(Context, EltTy);
05850         if (T.isNull()) {
05851           // There is no integral type larger enough to represent this 
05852           // value. Complain, then allow the value to wrap around.
05853           EnumVal = LastEnumConst->getInitVal();
05854           EnumVal.zext(EnumVal.getBitWidth() * 2);
05855           Diag(IdLoc, diag::warn_enumerator_too_large)
05856             << EnumVal.toString(10);
05857         } else {
05858           EltTy = T;
05859         }
05860         
05861         // Retrieve the last enumerator's value, extent that type to the
05862         // type that is supposed to be large enough to represent the incremented
05863         // value, then increment.
05864         EnumVal = LastEnumConst->getInitVal();
05865         EnumVal.setIsSigned(EltTy->isSignedIntegerType());
05866         EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
05867         ++EnumVal;        
05868         
05869         // If we're not in C++, diagnose the overflow of enumerator values,
05870         // which in C99 means that the enumerator value is not representable in
05871         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
05872         // permits enumerator values that are representable in some larger
05873         // integral type.
05874         if (!getLangOptions().CPlusPlus && !T.isNull())
05875           Diag(IdLoc, diag::warn_enum_value_overflow);
05876       } else if (!getLangOptions().CPlusPlus &&
05877                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
05878         // Enforce C99 6.7.2.2p2 even when we compute the next value.
05879         Diag(IdLoc, diag::ext_enum_value_not_int)
05880           << EnumVal.toString(10) << 1;
05881       }
05882     }
05883   }
05884 
05885   if (!EltTy->isDependentType()) {
05886     // Make the enumerator value match the signedness and size of the 
05887     // enumerator's type.
05888     EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
05889     EnumVal.setIsSigned(EltTy->isSignedIntegerType());
05890   }
05891   
05892   val.release();
05893   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
05894                                   Val, EnumVal);
05895 }
05896 
05897 
05898 Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
05899                                         DeclPtrTy lastEnumConst,
05900                                         SourceLocation IdLoc,
05901                                         IdentifierInfo *Id,
05902                                         SourceLocation EqualLoc, ExprTy *val) {
05903   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
05904   EnumConstantDecl *LastEnumConst =
05905     cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
05906   Expr *Val = static_cast<Expr*>(val);
05907 
05908   // The scope passed in may not be a decl scope.  Zip up the scope tree until
05909   // we find one that is.
05910   S = getNonFieldDeclScope(S);
05911 
05912   // Verify that there isn't already something declared with this name in this
05913   // scope.
05914   NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName,
05915                                          ForRedeclaration);
05916   if (PrevDecl && PrevDecl->isTemplateParameter()) {
05917     // Maybe we will complain about the shadowed template parameter.
05918     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
05919     // Just pretend that we didn't see the previous declaration.
05920     PrevDecl = 0;
05921   }
05922 
05923   if (PrevDecl) {
05924     // When in C++, we may get a TagDecl with the same name; in this case the
05925     // enum constant will 'hide' the tag.
05926     assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
05927            "Received TagDecl when not in C++!");
05928     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
05929       if (isa<EnumConstantDecl>(PrevDecl))
05930         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
05931       else
05932         Diag(IdLoc, diag::err_redefinition) << Id;
05933       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
05934       if (Val) Val->Destroy(Context);
05935       return DeclPtrTy();
05936     }
05937   }
05938 
05939   EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
05940                                             IdLoc, Id, Owned(Val));
05941 
05942   // Register this decl in the current scope stack.
05943   if (New) {
05944     New->setAccess(TheEnumDecl->getAccess());
05945     PushOnScopeChains(New, S);
05946   }
05947 
05948   return DeclPtrTy::make(New);
05949 }
05950 
05951 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
05952                          SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
05953                          DeclPtrTy *Elements, unsigned NumElements,
05954                          Scope *S, AttributeList *Attr) {
05955   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
05956   QualType EnumType = Context.getTypeDeclType(Enum);
05957 
05958   if (Attr)
05959     ProcessDeclAttributeList(S, Enum, Attr);
05960 
05961   if (Enum->isDependentType()) {
05962     for (unsigned i = 0; i != NumElements; ++i) {
05963       EnumConstantDecl *ECD =
05964         cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
05965       if (!ECD) continue;
05966 
05967       ECD->setType(EnumType);
05968     }
05969 
05970     Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
05971     return;
05972   }
05973 
05974   // TODO: If the result value doesn't fit in an int, it must be a long or long
05975   // long value.  ISO C does not support this, but GCC does as an extension,
05976   // emit a warning.
05977   unsigned IntWidth = Context.Target.getIntWidth();
05978   unsigned CharWidth = Context.Target.getCharWidth();
05979   unsigned ShortWidth = Context.Target.getShortWidth();
05980 
05981   // Verify that all the values are okay, compute the size of the values, and
05982   // reverse the list.
05983   unsigned NumNegativeBits = 0;
05984   unsigned NumPositiveBits = 0;
05985 
05986   // Keep track of whether all elements have type int.
05987   bool AllElementsInt = true;
05988 
05989   for (unsigned i = 0; i != NumElements; ++i) {
05990     EnumConstantDecl *ECD =
05991       cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
05992     if (!ECD) continue;  // Already issued a diagnostic.
05993 
05994     const llvm::APSInt &InitVal = ECD->getInitVal();
05995 
05996     // Keep track of the size of positive and negative values.
05997     if (InitVal.isUnsigned() || InitVal.isNonNegative())
05998       NumPositiveBits = std::max(NumPositiveBits,
05999                                  (unsigned)InitVal.getActiveBits());
06000     else
06001       NumNegativeBits = std::max(NumNegativeBits,
06002                                  (unsigned)InitVal.getMinSignedBits());
06003 
06004     // Keep track of whether every enum element has type int (very commmon).
06005     if (AllElementsInt)
06006       AllElementsInt = ECD->getType() == Context.IntTy;
06007   }
06008 
06009   // Figure out the type that should be used for this enum.
06010   // FIXME: Support -fshort-enums.
06011   QualType BestType;
06012   unsigned BestWidth;
06013 
06014   // C++0x N3000 [conv.prom]p3:
06015   //   An rvalue of an unscoped enumeration type whose underlying
06016   //   type is not fixed can be converted to an rvalue of the first
06017   //   of the following types that can represent all the values of
06018   //   the enumeration: int, unsigned int, long int, unsigned long
06019   //   int, long long int, or unsigned long long int.
06020   // C99 6.4.4.3p2:
06021   //   An identifier declared as an enumeration constant has type int.
06022   // The C99 rule is modified by a gcc extension 
06023   QualType BestPromotionType;
06024 
06025   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
06026 
06027   if (NumNegativeBits) {
06028     // If there is a negative value, figure out the smallest integer type (of
06029     // int/long/longlong) that fits.
06030     // If it's packed, check also if it fits a char or a short.
06031     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
06032       BestType = Context.SignedCharTy;
06033       BestWidth = CharWidth;
06034     } else if (Packed && NumNegativeBits <= ShortWidth &&
06035                NumPositiveBits < ShortWidth) {
06036       BestType = Context.ShortTy;
06037       BestWidth = ShortWidth;
06038     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
06039       BestType = Context.IntTy;
06040       BestWidth = IntWidth;
06041     } else {
06042       BestWidth = Context.Target.getLongWidth();
06043 
06044       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
06045         BestType = Context.LongTy;
06046       } else {
06047         BestWidth = Context.Target.getLongLongWidth();
06048 
06049         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
06050           Diag(Enum->getLocation(), diag::warn_enum_too_large);
06051         BestType = Context.LongLongTy;
06052       }
06053     }
06054     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
06055   } else {
06056     // If there is no negative value, figure out the smallest type that fits
06057     // all of the enumerator values.
06058     // If it's packed, check also if it fits a char or a short.
06059     if (Packed && NumPositiveBits <= CharWidth) {
06060       BestType = Context.UnsignedCharTy;
06061       BestPromotionType = Context.IntTy;
06062       BestWidth = CharWidth;
06063     } else if (Packed && NumPositiveBits <= ShortWidth) {
06064       BestType = Context.UnsignedShortTy;
06065       BestPromotionType = Context.IntTy;
06066       BestWidth = ShortWidth;
06067     } else if (NumPositiveBits <= IntWidth) {
06068       BestType = Context.UnsignedIntTy;
06069       BestWidth = IntWidth;
06070       BestPromotionType
06071         = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
06072                            ? Context.UnsignedIntTy : Context.IntTy;
06073     } else if (NumPositiveBits <=
06074                (BestWidth = Context.Target.getLongWidth())) {
06075       BestType = Context.UnsignedLongTy;
06076       BestPromotionType
06077         = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
06078                            ? Context.UnsignedLongTy : Context.LongTy;
06079     } else {
06080       BestWidth = Context.Target.getLongLongWidth();
06081       assert(NumPositiveBits <= BestWidth &&
06082              "How could an initializer get larger than ULL?");
06083       BestType = Context.UnsignedLongLongTy;
06084       BestPromotionType
06085         = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
06086                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
06087     }
06088   }
06089 
06090   // Loop over all of the enumerator constants, changing their types to match
06091   // the type of the enum if needed.
06092   for (unsigned i = 0; i != NumElements; ++i) {
06093     EnumConstantDecl *ECD =
06094       cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
06095     if (!ECD) continue;  // Already issued a diagnostic.
06096 
06097     // Standard C says the enumerators have int type, but we allow, as an
06098     // extension, the enumerators to be larger than int size.  If each
06099     // enumerator value fits in an int, type it as an int, otherwise type it the
06100     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
06101     // that X has type 'int', not 'unsigned'.
06102 
06103     // Determine whether the value fits into an int.
06104     llvm::APSInt InitVal = ECD->getInitVal();
06105 
06106     // If it fits into an integer type, force it.  Otherwise force it to match
06107     // the enum decl type.
06108     QualType NewTy;
06109     unsigned NewWidth;
06110     bool NewSign;
06111     if (!getLangOptions().CPlusPlus &&
06112         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
06113       NewTy = Context.IntTy;
06114       NewWidth = IntWidth;
06115       NewSign = true;
06116     } else if (ECD->getType() == BestType) {
06117       // Already the right type!
06118       if (getLangOptions().CPlusPlus)
06119         // C++ [dcl.enum]p4: Following the closing brace of an
06120         // enum-specifier, each enumerator has the type of its
06121         // enumeration.
06122         ECD->setType(EnumType);
06123       continue;
06124     } else {
06125       NewTy = BestType;
06126       NewWidth = BestWidth;
06127       NewSign = BestType->isSignedIntegerType();
06128     }
06129 
06130     // Adjust the APSInt value.
06131     InitVal.extOrTrunc(NewWidth);
06132     InitVal.setIsSigned(NewSign);
06133     ECD->setInitVal(InitVal);
06134 
06135     // Adjust the Expr initializer and type.
06136     if (ECD->getInitExpr())
06137       ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
06138                                                       CastExpr::CK_IntegralCast,
06139                                                       ECD->getInitExpr(),
06140                                                       /*isLvalue=*/false));
06141     if (getLangOptions().CPlusPlus)
06142       // C++ [dcl.enum]p4: Following the closing brace of an
06143       // enum-specifier, each enumerator has the type of its
06144       // enumeration.
06145       ECD->setType(EnumType);
06146     else
06147       ECD->setType(NewTy);
06148   }
06149 
06150   Enum->completeDefinition(BestType, BestPromotionType);
06151 }
06152 
06153 Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
06154                                             ExprArg expr) {
06155   StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
06156 
06157   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
06158                                                    Loc, AsmString);
06159   CurContext->addDecl(New);
06160   return DeclPtrTy::make(New);
06161 }
06162 
06163 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
06164                              SourceLocation PragmaLoc,
06165                              SourceLocation NameLoc) {
06166   Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
06167 
06168   if (PrevDecl) {
06169     PrevDecl->addAttr(::new (Context) WeakAttr());
06170   } else {
06171     (void)WeakUndeclaredIdentifiers.insert(
06172       std::pair<IdentifierInfo*,WeakInfo>
06173         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
06174   }
06175 }
06176 
06177 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
06178                                 IdentifierInfo* AliasName,
06179                                 SourceLocation PragmaLoc,
06180                                 SourceLocation NameLoc,
06181                                 SourceLocation AliasNameLoc) {
06182   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
06183   WeakInfo W = WeakInfo(Name, NameLoc);
06184 
06185   if (PrevDecl) {
06186     if (!PrevDecl->hasAttr<AliasAttr>())
06187       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
06188         DeclApplyPragmaWeak(TUScope, ND, W);
06189   } else {
06190     (void)WeakUndeclaredIdentifiers.insert(
06191       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
06192   }
06193 }