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