clang API Documentation
00001 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ 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 C++ declarations. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "Sema.h" 00015 #include "SemaInit.h" 00016 #include "Lookup.h" 00017 #include "clang/AST/ASTConsumer.h" 00018 #include "clang/AST/ASTContext.h" 00019 #include "clang/AST/RecordLayout.h" 00020 #include "clang/AST/CXXInheritance.h" 00021 #include "clang/AST/DeclVisitor.h" 00022 #include "clang/AST/TypeLoc.h" 00023 #include "clang/AST/TypeOrdering.h" 00024 #include "clang/AST/StmtVisitor.h" 00025 #include "clang/Parse/DeclSpec.h" 00026 #include "clang/Parse/Template.h" 00027 #include "clang/Basic/PartialDiagnostic.h" 00028 #include "clang/Lex/Preprocessor.h" 00029 #include "llvm/ADT/STLExtras.h" 00030 #include <map> 00031 #include <set> 00032 00033 using namespace clang; 00034 00035 //===----------------------------------------------------------------------===// 00036 // CheckDefaultArgumentVisitor 00037 //===----------------------------------------------------------------------===// 00038 00039 namespace { 00040 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 00041 /// the default argument of a parameter to determine whether it 00042 /// contains any ill-formed subexpressions. For example, this will 00043 /// diagnose the use of local variables or parameters within the 00044 /// default argument expression. 00045 class CheckDefaultArgumentVisitor 00046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 00047 Expr *DefaultArg; 00048 Sema *S; 00049 00050 public: 00051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 00052 : DefaultArg(defarg), S(s) {} 00053 00054 bool VisitExpr(Expr *Node); 00055 bool VisitDeclRefExpr(DeclRefExpr *DRE); 00056 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 00057 }; 00058 00059 /// VisitExpr - Visit all of the children of this expression. 00060 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 00061 bool IsInvalid = false; 00062 for (Stmt::child_iterator I = Node->child_begin(), 00063 E = Node->child_end(); I != E; ++I) 00064 IsInvalid |= Visit(*I); 00065 return IsInvalid; 00066 } 00067 00068 /// VisitDeclRefExpr - Visit a reference to a declaration, to 00069 /// determine whether this declaration can be used in the default 00070 /// argument expression. 00071 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 00072 NamedDecl *Decl = DRE->getDecl(); 00073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 00074 // C++ [dcl.fct.default]p9 00075 // Default arguments are evaluated each time the function is 00076 // called. The order of evaluation of function arguments is 00077 // unspecified. Consequently, parameters of a function shall not 00078 // be used in default argument expressions, even if they are not 00079 // evaluated. Parameters of a function declared before a default 00080 // argument expression are in scope and can hide namespace and 00081 // class member names. 00082 return S->Diag(DRE->getSourceRange().getBegin(), 00083 diag::err_param_default_argument_references_param) 00084 << Param->getDeclName() << DefaultArg->getSourceRange(); 00085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 00086 // C++ [dcl.fct.default]p7 00087 // Local variables shall not be used in default argument 00088 // expressions. 00089 if (VDecl->isBlockVarDecl()) 00090 return S->Diag(DRE->getSourceRange().getBegin(), 00091 diag::err_param_default_argument_references_local) 00092 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 00093 } 00094 00095 return false; 00096 } 00097 00098 /// VisitCXXThisExpr - Visit a C++ "this" expression. 00099 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 00100 // C++ [dcl.fct.default]p8: 00101 // The keyword this shall not be used in a default argument of a 00102 // member function. 00103 return S->Diag(ThisE->getSourceRange().getBegin(), 00104 diag::err_param_default_argument_references_this) 00105 << ThisE->getSourceRange(); 00106 } 00107 } 00108 00109 bool 00110 Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 00111 SourceLocation EqualLoc) { 00112 if (RequireCompleteType(Param->getLocation(), Param->getType(), 00113 diag::err_typecheck_decl_incomplete_type)) { 00114 Param->setInvalidDecl(); 00115 return true; 00116 } 00117 00118 Expr *Arg = (Expr *)DefaultArg.get(); 00119 00120 // C++ [dcl.fct.default]p5 00121 // A default argument expression is implicitly converted (clause 00122 // 4) to the parameter type. The default argument expression has 00123 // the same semantic constraints as the initializer expression in 00124 // a declaration of a variable of the parameter type, using the 00125 // copy-initialization semantics (8.5). 00126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 00127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 00128 EqualLoc); 00129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 00130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 00131 MultiExprArg(*this, (void**)&Arg, 1)); 00132 if (Result.isInvalid()) 00133 return true; 00134 Arg = Result.takeAs<Expr>(); 00135 00136 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 00137 00138 // Okay: add the default argument to the parameter 00139 Param->setDefaultArg(Arg); 00140 00141 DefaultArg.release(); 00142 00143 return false; 00144 } 00145 00146 /// ActOnParamDefaultArgument - Check whether the default argument 00147 /// provided for a function parameter is well-formed. If so, attach it 00148 /// to the parameter declaration. 00149 void 00150 Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 00151 ExprArg defarg) { 00152 if (!param || !defarg.get()) 00153 return; 00154 00155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00156 UnparsedDefaultArgLocs.erase(Param); 00157 00158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 00159 00160 // Default arguments are only permitted in C++ 00161 if (!getLangOptions().CPlusPlus) { 00162 Diag(EqualLoc, diag::err_param_default_argument) 00163 << DefaultArg->getSourceRange(); 00164 Param->setInvalidDecl(); 00165 return; 00166 } 00167 00168 // Check that the default argument is well-formed 00169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 00170 if (DefaultArgChecker.Visit(DefaultArg.get())) { 00171 Param->setInvalidDecl(); 00172 return; 00173 } 00174 00175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 00176 } 00177 00178 /// ActOnParamUnparsedDefaultArgument - We've seen a default 00179 /// argument for a function parameter, but we can't parse it yet 00180 /// because we're inside a class definition. Note that this default 00181 /// argument will be parsed later. 00182 void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 00183 SourceLocation EqualLoc, 00184 SourceLocation ArgLoc) { 00185 if (!param) 00186 return; 00187 00188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00189 if (Param) 00190 Param->setUnparsedDefaultArg(); 00191 00192 UnparsedDefaultArgLocs[Param] = ArgLoc; 00193 } 00194 00195 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 00196 /// the default argument for the parameter param failed. 00197 void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 00198 if (!param) 00199 return; 00200 00201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00202 00203 Param->setInvalidDecl(); 00204 00205 UnparsedDefaultArgLocs.erase(Param); 00206 } 00207 00208 /// CheckExtraCXXDefaultArguments - Check for any extra default 00209 /// arguments in the declarator, which is not a function declaration 00210 /// or definition and therefore is not permitted to have default 00211 /// arguments. This routine should be invoked for every declarator 00212 /// that is not a function declaration or definition. 00213 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 00214 // C++ [dcl.fct.default]p3 00215 // A default argument expression shall be specified only in the 00216 // parameter-declaration-clause of a function declaration or in a 00217 // template-parameter (14.1). It shall not be specified for a 00218 // parameter pack. If it is specified in a 00219 // parameter-declaration-clause, it shall not occur within a 00220 // declarator or abstract-declarator of a parameter-declaration. 00221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 00222 DeclaratorChunk &chunk = D.getTypeObject(i); 00223 if (chunk.Kind == DeclaratorChunk::Function) { 00224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 00225 ParmVarDecl *Param = 00226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 00227 if (Param->hasUnparsedDefaultArg()) { 00228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 00229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 00230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 00231 delete Toks; 00232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 00233 } else if (Param->getDefaultArg()) { 00234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 00235 << Param->getDefaultArg()->getSourceRange(); 00236 Param->setDefaultArg(0); 00237 } 00238 } 00239 } 00240 } 00241 } 00242 00243 // MergeCXXFunctionDecl - Merge two declarations of the same C++ 00244 // function, once we already know that they have the same 00245 // type. Subroutine of MergeFunctionDecl. Returns true if there was an 00246 // error, false otherwise. 00247 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 00248 bool Invalid = false; 00249 00250 // C++ [dcl.fct.default]p4: 00251 // For non-template functions, default arguments can be added in 00252 // later declarations of a function in the same 00253 // scope. Declarations in different scopes have completely 00254 // distinct sets of default arguments. That is, declarations in 00255 // inner scopes do not acquire default arguments from 00256 // declarations in outer scopes, and vice versa. In a given 00257 // function declaration, all parameters subsequent to a 00258 // parameter with a default argument shall have default 00259 // arguments supplied in this or previous declarations. A 00260 // default argument shall not be redefined by a later 00261 // declaration (not even to the same value). 00262 // 00263 // C++ [dcl.fct.default]p6: 00264 // Except for member functions of class templates, the default arguments 00265 // in a member function definition that appears outside of the class 00266 // definition are added to the set of default arguments provided by the 00267 // member function declaration in the class definition. 00268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 00269 ParmVarDecl *OldParam = Old->getParamDecl(p); 00270 ParmVarDecl *NewParam = New->getParamDecl(p); 00271 00272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 00273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 00274 // hint here. Alternatively, we could walk the type-source information 00275 // for NewParam to find the last source location in the type... but it 00276 // isn't worth the effort right now. This is the kind of test case that 00277 // is hard to get right: 00278 00279 // int f(int); 00280 // void g(int (*fp)(int) = f); 00281 // void g(int (*fp)(int) = &f); 00282 Diag(NewParam->getLocation(), 00283 diag::err_param_default_argument_redefinition) 00284 << NewParam->getDefaultArgRange(); 00285 00286 // Look for the function declaration where the default argument was 00287 // actually written, which may be a declaration prior to Old. 00288 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 00289 Older; Older = Older->getPreviousDeclaration()) { 00290 if (!Older->getParamDecl(p)->hasDefaultArg()) 00291 break; 00292 00293 OldParam = Older->getParamDecl(p); 00294 } 00295 00296 Diag(OldParam->getLocation(), diag::note_previous_definition) 00297 << OldParam->getDefaultArgRange(); 00298 Invalid = true; 00299 } else if (OldParam->hasDefaultArg()) { 00300 // Merge the old default argument into the new parameter 00301 NewParam->setHasInheritedDefaultArg(); 00302 if (OldParam->hasUninstantiatedDefaultArg()) 00303 NewParam->setUninstantiatedDefaultArg( 00304 OldParam->getUninstantiatedDefaultArg()); 00305 else 00306 NewParam->setDefaultArg(OldParam->getDefaultArg()); 00307 } else if (NewParam->hasDefaultArg()) { 00308 if (New->getDescribedFunctionTemplate()) { 00309 // Paragraph 4, quoted above, only applies to non-template functions. 00310 Diag(NewParam->getLocation(), 00311 diag::err_param_default_argument_template_redecl) 00312 << NewParam->getDefaultArgRange(); 00313 Diag(Old->getLocation(), diag::note_template_prev_declaration) 00314 << false; 00315 } else if (New->getTemplateSpecializationKind() 00316 != TSK_ImplicitInstantiation && 00317 New->getTemplateSpecializationKind() != TSK_Undeclared) { 00318 // C++ [temp.expr.spec]p21: 00319 // Default function arguments shall not be specified in a declaration 00320 // or a definition for one of the following explicit specializations: 00321 // - the explicit specialization of a function template; 00322 // - the explicit specialization of a member function template; 00323 // - the explicit specialization of a member function of a class 00324 // template where the class template specialization to which the 00325 // member function specialization belongs is implicitly 00326 // instantiated. 00327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 00328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 00329 << New->getDeclName() 00330 << NewParam->getDefaultArgRange(); 00331 } else if (New->getDeclContext()->isDependentContext()) { 00332 // C++ [dcl.fct.default]p6 (DR217): 00333 // Default arguments for a member function of a class template shall 00334 // be specified on the initial declaration of the member function 00335 // within the class template. 00336 // 00337 // Reading the tea leaves a bit in DR217 and its reference to DR205 00338 // leads me to the conclusion that one cannot add default function 00339 // arguments for an out-of-line definition of a member function of a 00340 // dependent type. 00341 int WhichKind = 2; 00342 if (CXXRecordDecl *Record 00343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 00344 if (Record->getDescribedClassTemplate()) 00345 WhichKind = 0; 00346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 00347 WhichKind = 1; 00348 else 00349 WhichKind = 2; 00350 } 00351 00352 Diag(NewParam->getLocation(), 00353 diag::err_param_default_argument_member_template_redecl) 00354 << WhichKind 00355 << NewParam->getDefaultArgRange(); 00356 } 00357 } 00358 } 00359 00360 if (CheckEquivalentExceptionSpec(Old, New)) 00361 Invalid = true; 00362 00363 return Invalid; 00364 } 00365 00366 /// CheckCXXDefaultArguments - Verify that the default arguments for a 00367 /// function declaration are well-formed according to C++ 00368 /// [dcl.fct.default]. 00369 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 00370 unsigned NumParams = FD->getNumParams(); 00371 unsigned p; 00372 00373 // Find first parameter with a default argument 00374 for (p = 0; p < NumParams; ++p) { 00375 ParmVarDecl *Param = FD->getParamDecl(p); 00376 if (Param->hasDefaultArg()) 00377 break; 00378 } 00379 00380 // C++ [dcl.fct.default]p4: 00381 // In a given function declaration, all parameters 00382 // subsequent to a parameter with a default argument shall 00383 // have default arguments supplied in this or previous 00384 // declarations. A default argument shall not be redefined 00385 // by a later declaration (not even to the same value). 00386 unsigned LastMissingDefaultArg = 0; 00387 for (; p < NumParams; ++p) { 00388 ParmVarDecl *Param = FD->getParamDecl(p); 00389 if (!Param->hasDefaultArg()) { 00390 if (Param->isInvalidDecl()) 00391 /* We already complained about this parameter. */; 00392 else if (Param->getIdentifier()) 00393 Diag(Param->getLocation(), 00394 diag::err_param_default_argument_missing_name) 00395 << Param->getIdentifier(); 00396 else 00397 Diag(Param->getLocation(), 00398 diag::err_param_default_argument_missing); 00399 00400 LastMissingDefaultArg = p; 00401 } 00402 } 00403 00404 if (LastMissingDefaultArg > 0) { 00405 // Some default arguments were missing. Clear out all of the 00406 // default arguments up to (and including) the last missing 00407 // default argument, so that we leave the function parameters 00408 // in a semantically valid state. 00409 for (p = 0; p <= LastMissingDefaultArg; ++p) { 00410 ParmVarDecl *Param = FD->getParamDecl(p); 00411 if (Param->hasDefaultArg()) { 00412 if (!Param->hasUnparsedDefaultArg()) 00413 Param->getDefaultArg()->Destroy(Context); 00414 Param->setDefaultArg(0); 00415 } 00416 } 00417 } 00418 } 00419 00420 /// isCurrentClassName - Determine whether the identifier II is the 00421 /// name of the class type currently being defined. In the case of 00422 /// nested classes, this will only return true if II is the name of 00423 /// the innermost class. 00424 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 00425 const CXXScopeSpec *SS) { 00426 assert(getLangOptions().CPlusPlus && "No class names in C!"); 00427 00428 CXXRecordDecl *CurDecl; 00429 if (SS && SS->isSet() && !SS->isInvalid()) { 00430 DeclContext *DC = computeDeclContext(*SS, true); 00431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 00432 } else 00433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 00434 00435 if (CurDecl && CurDecl->getIdentifier()) 00436 return &II == CurDecl->getIdentifier(); 00437 else 00438 return false; 00439 } 00440 00441 /// \brief Check the validity of a C++ base class specifier. 00442 /// 00443 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 00444 /// and returns NULL otherwise. 00445 CXXBaseSpecifier * 00446 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 00447 SourceRange SpecifierRange, 00448 bool Virtual, AccessSpecifier Access, 00449 QualType BaseType, 00450 SourceLocation BaseLoc) { 00451 // C++ [class.union]p1: 00452 // A union shall not have base classes. 00453 if (Class->isUnion()) { 00454 Diag(Class->getLocation(), diag::err_base_clause_on_union) 00455 << SpecifierRange; 00456 return 0; 00457 } 00458 00459 if (BaseType->isDependentType()) 00460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 00461 Class->getTagKind() == RecordDecl::TK_class, 00462 Access, BaseType); 00463 00464 // Base specifiers must be record types. 00465 if (!BaseType->isRecordType()) { 00466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 00467 return 0; 00468 } 00469 00470 // C++ [class.union]p1: 00471 // A union shall not be used as a base class. 00472 if (BaseType->isUnionType()) { 00473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 00474 return 0; 00475 } 00476 00477 // C++ [class.derived]p2: 00478 // The class-name in a base-specifier shall not be an incompletely 00479 // defined class. 00480 if (RequireCompleteType(BaseLoc, BaseType, 00481 PDiag(diag::err_incomplete_base_class) 00482 << SpecifierRange)) 00483 return 0; 00484 00485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 00486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 00487 assert(BaseDecl && "Record type has no declaration"); 00488 BaseDecl = BaseDecl->getDefinition(); 00489 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 00490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 00491 assert(CXXBaseDecl && "Base type is not a C++ type"); 00492 00493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 00494 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 00495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 00496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 00497 << BaseType; 00498 return 0; 00499 } 00500 00501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 00502 00503 // Create the base specifier. 00504 // FIXME: Allocate via ASTContext? 00505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 00506 Class->getTagKind() == RecordDecl::TK_class, 00507 Access, BaseType); 00508 } 00509 00510 void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 00511 const CXXRecordDecl *BaseClass, 00512 bool BaseIsVirtual) { 00513 // A class with a non-empty base class is not empty. 00514 // FIXME: Standard ref? 00515 if (!BaseClass->isEmpty()) 00516 Class->setEmpty(false); 00517 00518 // C++ [class.virtual]p1: 00519 // A class that [...] inherits a virtual function is called a polymorphic 00520 // class. 00521 if (BaseClass->isPolymorphic()) 00522 Class->setPolymorphic(true); 00523 00524 // C++ [dcl.init.aggr]p1: 00525 // An aggregate is [...] a class with [...] no base classes [...]. 00526 Class->setAggregate(false); 00527 00528 // C++ [class]p4: 00529 // A POD-struct is an aggregate class... 00530 Class->setPOD(false); 00531 00532 if (BaseIsVirtual) { 00533 // C++ [class.ctor]p5: 00534 // A constructor is trivial if its class has no virtual base classes. 00535 Class->setHasTrivialConstructor(false); 00536 00537 // C++ [class.copy]p6: 00538 // A copy constructor is trivial if its class has no virtual base classes. 00539 Class->setHasTrivialCopyConstructor(false); 00540 00541 // C++ [class.copy]p11: 00542 // A copy assignment operator is trivial if its class has no virtual 00543 // base classes. 00544 Class->setHasTrivialCopyAssignment(false); 00545 00546 // C++0x [meta.unary.prop] is_empty: 00547 // T is a class type, but not a union type, with ... no virtual base 00548 // classes 00549 Class->setEmpty(false); 00550 } else { 00551 // C++ [class.ctor]p5: 00552 // A constructor is trivial if all the direct base classes of its 00553 // class have trivial constructors. 00554 if (!BaseClass->hasTrivialConstructor()) 00555 Class->setHasTrivialConstructor(false); 00556 00557 // C++ [class.copy]p6: 00558 // A copy constructor is trivial if all the direct base classes of its 00559 // class have trivial copy constructors. 00560 if (!BaseClass->hasTrivialCopyConstructor()) 00561 Class->setHasTrivialCopyConstructor(false); 00562 00563 // C++ [class.copy]p11: 00564 // A copy assignment operator is trivial if all the direct base classes 00565 // of its class have trivial copy assignment operators. 00566 if (!BaseClass->hasTrivialCopyAssignment()) 00567 Class->setHasTrivialCopyAssignment(false); 00568 } 00569 00570 // C++ [class.ctor]p3: 00571 // A destructor is trivial if all the direct base classes of its class 00572 // have trivial destructors. 00573 if (!BaseClass->hasTrivialDestructor()) 00574 Class->setHasTrivialDestructor(false); 00575 } 00576 00577 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 00578 /// one entry in the base class list of a class specifier, for 00579 /// example: 00580 /// class foo : public bar, virtual private baz { 00581 /// 'public bar' and 'virtual private baz' are each base-specifiers. 00582 Sema::BaseResult 00583 Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 00584 bool Virtual, AccessSpecifier Access, 00585 TypeTy *basetype, SourceLocation BaseLoc) { 00586 if (!classdecl) 00587 return true; 00588 00589 AdjustDeclIfTemplate(classdecl); 00590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 00591 if (!Class) 00592 return true; 00593 00594 QualType BaseType = GetTypeFromParser(basetype); 00595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 00596 Virtual, Access, 00597 BaseType, BaseLoc)) 00598 return BaseSpec; 00599 00600 return true; 00601 } 00602 00603 /// \brief Performs the actual work of attaching the given base class 00604 /// specifiers to a C++ class. 00605 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 00606 unsigned NumBases) { 00607 if (NumBases == 0) 00608 return false; 00609 00610 // Used to keep track of which base types we have already seen, so 00611 // that we can properly diagnose redundant direct base types. Note 00612 // that the key is always the unqualified canonical type of the base 00613 // class. 00614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 00615 00616 // Copy non-redundant base specifiers into permanent storage. 00617 unsigned NumGoodBases = 0; 00618 bool Invalid = false; 00619 for (unsigned idx = 0; idx < NumBases; ++idx) { 00620 QualType NewBaseType 00621 = Context.getCanonicalType(Bases[idx]->getType()); 00622 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 00623 00624 if (KnownBaseTypes[NewBaseType]) { 00625 // C++ [class.mi]p3: 00626 // A class shall not be specified as a direct base class of a 00627 // derived class more than once. 00628 Diag(Bases[idx]->getSourceRange().getBegin(), 00629 diag::err_duplicate_base_class) 00630 << KnownBaseTypes[NewBaseType]->getType() 00631 << Bases[idx]->getSourceRange(); 00632 00633 // Delete the duplicate base class specifier; we're going to 00634 // overwrite its pointer later. 00635 Context.Deallocate(Bases[idx]); 00636 00637 Invalid = true; 00638 } else { 00639 // Okay, add this new base class. 00640 KnownBaseTypes[NewBaseType] = Bases[idx]; 00641 Bases[NumGoodBases++] = Bases[idx]; 00642 } 00643 } 00644 00645 // Attach the remaining base class specifiers to the derived class. 00646 Class->setBases(Bases, NumGoodBases); 00647 00648 // Delete the remaining (good) base class specifiers, since their 00649 // data has been copied into the CXXRecordDecl. 00650 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 00651 Context.Deallocate(Bases[idx]); 00652 00653 return Invalid; 00654 } 00655 00656 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 00657 /// class, after checking whether there are any duplicate base 00658 /// classes. 00659 void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 00660 unsigned NumBases) { 00661 if (!ClassDecl || !Bases || !NumBases) 00662 return; 00663 00664 AdjustDeclIfTemplate(ClassDecl); 00665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 00666 (CXXBaseSpecifier**)(Bases), NumBases); 00667 } 00668 00669 static CXXRecordDecl *GetClassForType(QualType T) { 00670 if (const RecordType *RT = T->getAs<RecordType>()) 00671 return cast<CXXRecordDecl>(RT->getDecl()); 00672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 00673 return ICT->getDecl(); 00674 else 00675 return 0; 00676 } 00677 00678 /// \brief Determine whether the type \p Derived is a C++ class that is 00679 /// derived from the type \p Base. 00680 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 00681 if (!getLangOptions().CPlusPlus) 00682 return false; 00683 00684 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 00685 if (!DerivedRD) 00686 return false; 00687 00688 CXXRecordDecl *BaseRD = GetClassForType(Base); 00689 if (!BaseRD) 00690 return false; 00691 00692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 00693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 00694 } 00695 00696 /// \brief Determine whether the type \p Derived is a C++ class that is 00697 /// derived from the type \p Base. 00698 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 00699 if (!getLangOptions().CPlusPlus) 00700 return false; 00701 00702 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 00703 if (!DerivedRD) 00704 return false; 00705 00706 CXXRecordDecl *BaseRD = GetClassForType(Base); 00707 if (!BaseRD) 00708 return false; 00709 00710 return DerivedRD->isDerivedFrom(BaseRD, Paths); 00711 } 00712 00713 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 00714 /// conversion (where Derived and Base are class types) is 00715 /// well-formed, meaning that the conversion is unambiguous (and 00716 /// that all of the base classes are accessible). Returns true 00717 /// and emits a diagnostic if the code is ill-formed, returns false 00718 /// otherwise. Loc is the location where this routine should point to 00719 /// if there is an error, and Range is the source range to highlight 00720 /// if there is an error. 00721 bool 00722 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 00723 AccessDiagnosticsKind ADK, 00724 unsigned AmbigiousBaseConvID, 00725 SourceLocation Loc, SourceRange Range, 00726 DeclarationName Name) { 00727 // First, determine whether the path from Derived to Base is 00728 // ambiguous. This is slightly more expensive than checking whether 00729 // the Derived to Base conversion exists, because here we need to 00730 // explore multiple paths to determine if there is an ambiguity. 00731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 00732 /*DetectVirtual=*/false); 00733 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 00734 assert(DerivationOkay && 00735 "Can only be used with a derived-to-base conversion"); 00736 (void)DerivationOkay; 00737 00738 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 00739 if (ADK == ADK_quiet) 00740 return false; 00741 00742 // Check that the base class can be accessed. 00743 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false, 00744 Base, Derived, Paths.front(), 00745 /*force*/ false, 00746 /*unprivileged*/ false, 00747 ADK)) { 00748 case AR_accessible: return false; 00749 case AR_inaccessible: return true; 00750 case AR_dependent: return false; 00751 case AR_delayed: return false; 00752 } 00753 } 00754 00755 // We know that the derived-to-base conversion is ambiguous, and 00756 // we're going to produce a diagnostic. Perform the derived-to-base 00757 // search just one more time to compute all of the possible paths so 00758 // that we can print them out. This is more expensive than any of 00759 // the previous derived-to-base checks we've done, but at this point 00760 // performance isn't as much of an issue. 00761 Paths.clear(); 00762 Paths.setRecordingPaths(true); 00763 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 00764 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 00765 (void)StillOkay; 00766 00767 // Build up a textual representation of the ambiguous paths, e.g., 00768 // D -> B -> A, that will be used to illustrate the ambiguous 00769 // conversions in the diagnostic. We only print one of the paths 00770 // to each base class subobject. 00771 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 00772 00773 Diag(Loc, AmbigiousBaseConvID) 00774 << Derived << Base << PathDisplayStr << Range << Name; 00775 return true; 00776 } 00777 00778 bool 00779 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 00780 SourceLocation Loc, SourceRange Range, 00781 bool IgnoreAccess) { 00782 return CheckDerivedToBaseConversion(Derived, Base, 00783 IgnoreAccess ? ADK_quiet : ADK_normal, 00784 diag::err_ambiguous_derived_to_base_conv, 00785 Loc, Range, DeclarationName()); 00786 } 00787 00788 00789 /// @brief Builds a string representing ambiguous paths from a 00790 /// specific derived class to different subobjects of the same base 00791 /// class. 00792 /// 00793 /// This function builds a string that can be used in error messages 00794 /// to show the different paths that one can take through the 00795 /// inheritance hierarchy to go from the derived class to different 00796 /// subobjects of a base class. The result looks something like this: 00797 /// @code 00798 /// struct D -> struct B -> struct A 00799 /// struct D -> struct C -> struct A 00800 /// @endcode 00801 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 00802 std::string PathDisplayStr; 00803 std::set<unsigned> DisplayedPaths; 00804 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 00805 Path != Paths.end(); ++Path) { 00806 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 00807 // We haven't displayed a path to this particular base 00808 // class subobject yet. 00809 PathDisplayStr += "\n "; 00810 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 00811 for (CXXBasePath::const_iterator Element = Path->begin(); 00812 Element != Path->end(); ++Element) 00813 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 00814 } 00815 } 00816 00817 return PathDisplayStr; 00818 } 00819 00820 //===----------------------------------------------------------------------===// 00821 // C++ class member Handling 00822 //===----------------------------------------------------------------------===// 00823 00824 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 00825 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 00826 /// bitfield width if there is one and 'InitExpr' specifies the initializer if 00827 /// any. 00828 Sema::DeclPtrTy 00829 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 00830 MultiTemplateParamsArg TemplateParameterLists, 00831 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 00832 bool Deleted) { 00833 const DeclSpec &DS = D.getDeclSpec(); 00834 DeclarationName Name = GetNameForDeclarator(D); 00835 Expr *BitWidth = static_cast<Expr*>(BW); 00836 Expr *Init = static_cast<Expr*>(InitExpr); 00837 SourceLocation Loc = D.getIdentifierLoc(); 00838 00839 bool isFunc = D.isFunctionDeclarator(); 00840 00841 assert(!DS.isFriendSpecified()); 00842 00843 // C++ 9.2p6: A member shall not be declared to have automatic storage 00844 // duration (auto, register) or with the extern storage-class-specifier. 00845 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 00846 // data members and cannot be applied to names declared const or static, 00847 // and cannot be applied to reference members. 00848 switch (DS.getStorageClassSpec()) { 00849 case DeclSpec::SCS_unspecified: 00850 case DeclSpec::SCS_typedef: 00851 case DeclSpec::SCS_static: 00852 // FALL THROUGH. 00853 break; 00854 case DeclSpec::SCS_mutable: 00855 if (isFunc) { 00856 if (DS.getStorageClassSpecLoc().isValid()) 00857 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 00858 else 00859 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 00860 00861 // FIXME: It would be nicer if the keyword was ignored only for this 00862 // declarator. Otherwise we could get follow-up errors. 00863 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00864 } else { 00865 QualType T = GetTypeForDeclarator(D, S); 00866 diag::kind err = static_cast<diag::kind>(0); 00867 if (T->isReferenceType()) 00868 err = diag::err_mutable_reference; 00869 else if (T.isConstQualified()) 00870 err = diag::err_mutable_const; 00871 if (err != 0) { 00872 if (DS.getStorageClassSpecLoc().isValid()) 00873 Diag(DS.getStorageClassSpecLoc(), err); 00874 else 00875 Diag(DS.getThreadSpecLoc(), err); 00876 // FIXME: It would be nicer if the keyword was ignored only for this 00877 // declarator. Otherwise we could get follow-up errors. 00878 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00879 } 00880 } 00881 break; 00882 default: 00883 if (DS.getStorageClassSpecLoc().isValid()) 00884 Diag(DS.getStorageClassSpecLoc(), 00885 diag::err_storageclass_invalid_for_member); 00886 else 00887 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 00888 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00889 } 00890 00891 if (!isFunc && 00892 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 00893 D.getNumTypeObjects() == 0) { 00894 // Check also for this case: 00895 // 00896 // typedef int f(); 00897 // f a; 00898 // 00899 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 00900 isFunc = TDType->isFunctionType(); 00901 } 00902 00903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 00904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 00905 !isFunc); 00906 00907 Decl *Member; 00908 if (isInstField) { 00909 // FIXME: Check for template parameters! 00910 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 00911 AS); 00912 assert(Member && "HandleField never returns null"); 00913 } else { 00914 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 00915 .getAs<Decl>(); 00916 if (!Member) { 00917 if (BitWidth) DeleteExpr(BitWidth); 00918 return DeclPtrTy(); 00919 } 00920 00921 // Non-instance-fields can't have a bitfield. 00922 if (BitWidth) { 00923 if (Member->isInvalidDecl()) { 00924 // don't emit another diagnostic. 00925 } else if (isa<VarDecl>(Member)) { 00926 // C++ 9.6p3: A bit-field shall not be a static member. 00927 // "static member 'A' cannot be a bit-field" 00928 Diag(Loc, diag::err_static_not_bitfield) 00929 << Name << BitWidth->getSourceRange(); 00930 } else if (isa<TypedefDecl>(Member)) { 00931 // "typedef member 'x' cannot be a bit-field" 00932 Diag(Loc, diag::err_typedef_not_bitfield) 00933 << Name << BitWidth->getSourceRange(); 00934 } else { 00935 // A function typedef ("typedef int f(); f a;"). 00936 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 00937 Diag(Loc, diag::err_not_integral_type_bitfield) 00938 << Name << cast<ValueDecl>(Member)->getType() 00939 << BitWidth->getSourceRange(); 00940 } 00941 00942 DeleteExpr(BitWidth); 00943 BitWidth = 0; 00944 Member->setInvalidDecl(); 00945 } 00946 00947 Member->setAccess(AS); 00948 00949 // If we have declared a member function template, set the access of the 00950 // templated declaration as well. 00951 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 00952 FunTmpl->getTemplatedDecl()->setAccess(AS); 00953 } 00954 00955 assert((Name || isInstField) && "No identifier for non-field ?"); 00956 00957 if (Init) 00958 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 00959 if (Deleted) // FIXME: Source location is not very good. 00960 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 00961 00962 if (isInstField) { 00963 FieldCollector->Add(cast<FieldDecl>(Member)); 00964 return DeclPtrTy(); 00965 } 00966 return DeclPtrTy::make(Member); 00967 } 00968 00969 /// \brief Find the direct and/or virtual base specifiers that 00970 /// correspond to the given base type, for use in base initialization 00971 /// within a constructor. 00972 static bool FindBaseInitializer(Sema &SemaRef, 00973 CXXRecordDecl *ClassDecl, 00974 QualType BaseType, 00975 const CXXBaseSpecifier *&DirectBaseSpec, 00976 const CXXBaseSpecifier *&VirtualBaseSpec) { 00977 // First, check for a direct base class. 00978 DirectBaseSpec = 0; 00979 for (CXXRecordDecl::base_class_const_iterator Base 00980 = ClassDecl->bases_begin(); 00981 Base != ClassDecl->bases_end(); ++Base) { 00982 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 00983 // We found a direct base of this type. That's what we're 00984 // initializing. 00985 DirectBaseSpec = &*Base; 00986 break; 00987 } 00988 } 00989 00990 // Check for a virtual base class. 00991 // FIXME: We might be able to short-circuit this if we know in advance that 00992 // there are no virtual bases. 00993 VirtualBaseSpec = 0; 00994 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 00995 // We haven't found a base yet; search the class hierarchy for a 00996 // virtual base class. 00997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 00998 /*DetectVirtual=*/false); 00999 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 01000 BaseType, Paths)) { 01001 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 01002 Path != Paths.end(); ++Path) { 01003 if (Path->back().Base->isVirtual()) { 01004 VirtualBaseSpec = Path->back().Base; 01005 break; 01006 } 01007 } 01008 } 01009 } 01010 01011 return DirectBaseSpec || VirtualBaseSpec; 01012 } 01013 01014 /// ActOnMemInitializer - Handle a C++ member initializer. 01015 Sema::MemInitResult 01016 Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 01017 Scope *S, 01018 const CXXScopeSpec &SS, 01019 IdentifierInfo *MemberOrBase, 01020 TypeTy *TemplateTypeTy, 01021 SourceLocation IdLoc, 01022 SourceLocation LParenLoc, 01023 ExprTy **Args, unsigned NumArgs, 01024 SourceLocation *CommaLocs, 01025 SourceLocation RParenLoc) { 01026 if (!ConstructorD) 01027 return true; 01028 01029 AdjustDeclIfTemplate(ConstructorD); 01030 01031 CXXConstructorDecl *Constructor 01032 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 01033 if (!Constructor) { 01034 // The user wrote a constructor initializer on a function that is 01035 // not a C++ constructor. Ignore the error for now, because we may 01036 // have more member initializers coming; we'll diagnose it just 01037 // once in ActOnMemInitializers. 01038 return true; 01039 } 01040 01041 CXXRecordDecl *ClassDecl = Constructor->getParent(); 01042 01043 // C++ [class.base.init]p2: 01044 // Names in a mem-initializer-id are looked up in the scope of the 01045 // constructor’s class and, if not found in that scope, are looked 01046 // up in the scope containing the constructor’s 01047 // definition. [Note: if the constructor’s class contains a member 01048 // with the same name as a direct or virtual base class of the 01049 // class, a mem-initializer-id naming the member or base class and 01050 // composed of a single identifier refers to the class member. A 01051 // mem-initializer-id for the hidden base class may be specified 01052 // using a qualified name. ] 01053 if (!SS.getScopeRep() && !TemplateTypeTy) { 01054 // Look for a member, first. 01055 FieldDecl *Member = 0; 01056 DeclContext::lookup_result Result 01057 = ClassDecl->lookup(MemberOrBase); 01058 if (Result.first != Result.second) 01059 Member = dyn_cast<FieldDecl>(*Result.first); 01060 01061 // FIXME: Handle members of an anonymous union. 01062 01063 if (Member) 01064 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 01065 LParenLoc, RParenLoc); 01066 } 01067 // It didn't name a member, so see if it names a class. 01068 QualType BaseType; 01069 TypeSourceInfo *TInfo = 0; 01070 01071 if (TemplateTypeTy) { 01072 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 01073 } else { 01074 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 01075 LookupParsedName(R, S, &SS); 01076 01077 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 01078 if (!TyD) { 01079 if (R.isAmbiguous()) return true; 01080 01081 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 01082 bool NotUnknownSpecialization = false; 01083 DeclContext *DC = computeDeclContext(SS, false); 01084 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 01085 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 01086 01087 if (!NotUnknownSpecialization) { 01088 // When the scope specifier can refer to a member of an unknown 01089 // specialization, we take it as a type name. 01090 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(), 01091 *MemberOrBase, SS.getRange()); 01092 if (BaseType.isNull()) 01093 return true; 01094 01095 R.clear(); 01096 } 01097 } 01098 01099 // If no results were found, try to correct typos. 01100 if (R.empty() && BaseType.isNull() && 01101 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) { 01102 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 01103 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 01104 // We have found a non-static data member with a similar 01105 // name to what was typed; complain and initialize that 01106 // member. 01107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 01108 << MemberOrBase << true << R.getLookupName() 01109 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 01110 R.getLookupName().getAsString()); 01111 Diag(Member->getLocation(), diag::note_previous_decl) 01112 << Member->getDeclName(); 01113 01114 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 01115 LParenLoc, RParenLoc); 01116 } 01117 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 01118 const CXXBaseSpecifier *DirectBaseSpec; 01119 const CXXBaseSpecifier *VirtualBaseSpec; 01120 if (FindBaseInitializer(*this, ClassDecl, 01121 Context.getTypeDeclType(Type), 01122 DirectBaseSpec, VirtualBaseSpec)) { 01123 // We have found a direct or virtual base class with a 01124 // similar name to what was typed; complain and initialize 01125 // that base class. 01126 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 01127 << MemberOrBase << false << R.getLookupName() 01128 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 01129 R.getLookupName().getAsString()); 01130 01131 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 01132 : VirtualBaseSpec; 01133 Diag(BaseSpec->getSourceRange().getBegin(), 01134 diag::note_base_class_specified_here) 01135 << BaseSpec->getType() 01136 << BaseSpec->getSourceRange(); 01137 01138 TyD = Type; 01139 } 01140 } 01141 } 01142 01143 if (!TyD && BaseType.isNull()) { 01144 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 01145 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 01146 return true; 01147 } 01148 } 01149 01150 if (BaseType.isNull()) { 01151 BaseType = Context.getTypeDeclType(TyD); 01152 if (SS.isSet()) { 01153 NestedNameSpecifier *Qualifier = 01154 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 01155 01156 // FIXME: preserve source range information 01157 BaseType = Context.getQualifiedNameType(Qualifier, BaseType); 01158 } 01159 } 01160 } 01161 01162 if (!TInfo) 01163 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 01164 01165 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 01166 LParenLoc, RParenLoc, ClassDecl); 01167 } 01168 01169 /// Checks an initializer expression for use of uninitialized fields, such as 01170 /// containing the field that is being initialized. Returns true if there is an 01171 /// uninitialized field was used an updates the SourceLocation parameter; false 01172 /// otherwise. 01173 static bool InitExprContainsUninitializedFields(const Stmt* S, 01174 const FieldDecl* LhsField, 01175 SourceLocation* L) { 01176 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 01177 if (ME) { 01178 const NamedDecl* RhsField = ME->getMemberDecl(); 01179 if (RhsField == LhsField) { 01180 // Initializing a field with itself. Throw a warning. 01181 // But wait; there are exceptions! 01182 // Exception #1: The field may not belong to this record. 01183 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 01184 const Expr* base = ME->getBase(); 01185 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 01186 // Even though the field matches, it does not belong to this record. 01187 return false; 01188 } 01189 // None of the exceptions triggered; return true to indicate an 01190 // uninitialized field was used. 01191 *L = ME->getMemberLoc(); 01192 return true; 01193 } 01194 } 01195 bool found = false; 01196 for (Stmt::const_child_iterator it = S->child_begin(); 01197 it != S->child_end() && found == false; 01198 ++it) { 01199 if (isa<CallExpr>(S)) { 01200 // Do not descend into function calls or constructors, as the use 01201 // of an uninitialized field may be valid. One would have to inspect 01202 // the contents of the function/ctor to determine if it is safe or not. 01203 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 01204 // may be safe, depending on what the function/ctor does. 01205 continue; 01206 } 01207 found = InitExprContainsUninitializedFields(*it, LhsField, L); 01208 } 01209 return found; 01210 } 01211 01212 Sema::MemInitResult 01213 Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 01214 unsigned NumArgs, SourceLocation IdLoc, 01215 SourceLocation LParenLoc, 01216 SourceLocation RParenLoc) { 01217 // Diagnose value-uses of fields to initialize themselves, e.g. 01218 // foo(foo) 01219 // where foo is not also a parameter to the constructor. 01220 // TODO: implement -Wuninitialized and fold this into that framework. 01221 for (unsigned i = 0; i < NumArgs; ++i) { 01222 SourceLocation L; 01223 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 01224 // FIXME: Return true in the case when other fields are used before being 01225 // uninitialized. For example, let this field be the i'th field. When 01226 // initializing the i'th field, throw a warning if any of the >= i'th 01227 // fields are used, as they are not yet initialized. 01228 // Right now we are only handling the case where the i'th field uses 01229 // itself in its initializer. 01230 Diag(L, diag::warn_field_is_uninit); 01231 } 01232 } 01233 01234 bool HasDependentArg = false; 01235 for (unsigned i = 0; i < NumArgs; i++) 01236 HasDependentArg |= Args[i]->isTypeDependent(); 01237 01238 QualType FieldType = Member->getType(); 01239 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 01240 FieldType = Array->getElementType(); 01241 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 01242 if (FieldType->isDependentType() || HasDependentArg) { 01243 // Can't check initialization for a member of dependent type or when 01244 // any of the arguments are type-dependent expressions. 01245 OwningExprResult Init 01246 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01247 RParenLoc)); 01248 01249 // Erase any temporaries within this evaluation context; we're not 01250 // going to track them in the AST, since we'll be rebuilding the 01251 // ASTs during template instantiation. 01252 ExprTemporaries.erase( 01253 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 01254 ExprTemporaries.end()); 01255 01256 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01257 LParenLoc, 01258 Init.takeAs<Expr>(), 01259 RParenLoc); 01260 01261 } 01262 01263 if (Member->isInvalidDecl()) 01264 return true; 01265 01266 // Initialize the member. 01267 InitializedEntity MemberEntity = 01268 InitializedEntity::InitializeMember(Member, 0); 01269 InitializationKind Kind = 01270 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 01271 01272 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 01273 01274 OwningExprResult MemberInit = 01275 InitSeq.Perform(*this, MemberEntity, Kind, 01276 MultiExprArg(*this, (void**)Args, NumArgs), 0); 01277 if (MemberInit.isInvalid()) 01278 return true; 01279 01280 // C++0x [class.base.init]p7: 01281 // The initialization of each base and member constitutes a 01282 // full-expression. 01283 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 01284 if (MemberInit.isInvalid()) 01285 return true; 01286 01287 // If we are in a dependent context, template instantiation will 01288 // perform this type-checking again. Just save the arguments that we 01289 // received in a ParenListExpr. 01290 // FIXME: This isn't quite ideal, since our ASTs don't capture all 01291 // of the information that we have about the member 01292 // initializer. However, deconstructing the ASTs is a dicey process, 01293 // and this approach is far more likely to get the corner cases right. 01294 if (CurContext->isDependentContext()) { 01295 // Bump the reference count of all of the arguments. 01296 for (unsigned I = 0; I != NumArgs; ++I) 01297 Args[I]->Retain(); 01298 01299 OwningExprResult Init 01300 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01301 RParenLoc)); 01302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01303 LParenLoc, 01304 Init.takeAs<Expr>(), 01305 RParenLoc); 01306 } 01307 01308 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01309 LParenLoc, 01310 MemberInit.takeAs<Expr>(), 01311 RParenLoc); 01312 } 01313 01314 Sema::MemInitResult 01315 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 01316 Expr **Args, unsigned NumArgs, 01317 SourceLocation LParenLoc, SourceLocation RParenLoc, 01318 CXXRecordDecl *ClassDecl) { 01319 bool HasDependentArg = false; 01320 for (unsigned i = 0; i < NumArgs; i++) 01321 HasDependentArg |= Args[i]->isTypeDependent(); 01322 01323 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin(); 01324 if (BaseType->isDependentType() || HasDependentArg) { 01325 // Can't check initialization for a base of dependent type or when 01326 // any of the arguments are type-dependent expressions. 01327 OwningExprResult BaseInit 01328 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01329 RParenLoc)); 01330 01331 // Erase any temporaries within this evaluation context; we're not 01332 // going to track them in the AST, since we'll be rebuilding the 01333 // ASTs during template instantiation. 01334 ExprTemporaries.erase( 01335 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 01336 ExprTemporaries.end()); 01337 01338 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01339 LParenLoc, 01340 BaseInit.takeAs<Expr>(), 01341 RParenLoc); 01342 } 01343 01344 if (!BaseType->isRecordType()) 01345 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 01346 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 01347 01348 // C++ [class.base.init]p2: 01349 // [...] Unless the mem-initializer-id names a nonstatic data 01350 // member of the constructor’s class or a direct or virtual base 01351 // of that class, the mem-initializer is ill-formed. A 01352 // mem-initializer-list can initialize a base class using any 01353 // name that denotes that base class type. 01354 01355 // Check for direct and virtual base classes. 01356 const CXXBaseSpecifier *DirectBaseSpec = 0; 01357 const CXXBaseSpecifier *VirtualBaseSpec = 0; 01358 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 01359 VirtualBaseSpec); 01360 01361 // C++ [base.class.init]p2: 01362 // If a mem-initializer-id is ambiguous because it designates both 01363 // a direct non-virtual base class and an inherited virtual base 01364 // class, the mem-initializer is ill-formed. 01365 if (DirectBaseSpec && VirtualBaseSpec) 01366 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 01367 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 01368 // C++ [base.class.init]p2: 01369 // Unless the mem-initializer-id names a nonstatic data membeer of the 01370 // constructor's class ot a direst or virtual base of that class, the 01371 // mem-initializer is ill-formed. 01372 if (!DirectBaseSpec && !VirtualBaseSpec) 01373 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 01374 << BaseType << ClassDecl->getNameAsCString() 01375 << BaseTInfo->getTypeLoc().getSourceRange(); 01376 01377 CXXBaseSpecifier *BaseSpec 01378 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 01379 if (!BaseSpec) 01380 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 01381 01382 // Initialize the base. 01383 InitializedEntity BaseEntity = 01384 InitializedEntity::InitializeBase(Context, BaseSpec); 01385 InitializationKind Kind = 01386 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 01387 01388 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 01389 01390 OwningExprResult BaseInit = 01391 InitSeq.Perform(*this, BaseEntity, Kind, 01392 MultiExprArg(*this, (void**)Args, NumArgs), 0); 01393 if (BaseInit.isInvalid()) 01394 return true; 01395 01396 // C++0x [class.base.init]p7: 01397 // The initialization of each base and member constitutes a 01398 // full-expression. 01399 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 01400 if (BaseInit.isInvalid()) 01401 return true; 01402 01403 // If we are in a dependent context, template instantiation will 01404 // perform this type-checking again. Just save the arguments that we 01405 // received in a ParenListExpr. 01406 // FIXME: This isn't quite ideal, since our ASTs don't capture all 01407 // of the information that we have about the base 01408 // initializer. However, deconstructing the ASTs is a dicey process, 01409 // and this approach is far more likely to get the corner cases right. 01410 if (CurContext->isDependentContext()) { 01411 // Bump the reference count of all of the arguments. 01412 for (unsigned I = 0; I != NumArgs; ++I) 01413 Args[I]->Retain(); 01414 01415 OwningExprResult Init 01416 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01417 RParenLoc)); 01418 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01419 LParenLoc, 01420 Init.takeAs<Expr>(), 01421 RParenLoc); 01422 } 01423 01424 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01425 LParenLoc, 01426 BaseInit.takeAs<Expr>(), 01427 RParenLoc); 01428 } 01429 01430 bool 01431 Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 01432 CXXBaseOrMemberInitializer **Initializers, 01433 unsigned NumInitializers, 01434 bool IsImplicitConstructor, 01435 bool AnyErrors) { 01436 // We need to build the initializer AST according to order of construction 01437 // and not what user specified in the Initializers list. 01438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 01439 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 01440 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 01441 bool HasDependentBaseInit = false; 01442 bool HadError = false; 01443 01444 for (unsigned i = 0; i < NumInitializers; i++) { 01445 CXXBaseOrMemberInitializer *Member = Initializers[i]; 01446 if (Member->isBaseInitializer()) { 01447 if (Member->getBaseClass()->isDependentType()) 01448 HasDependentBaseInit = true; 01449 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 01450 } else { 01451 AllBaseFields[Member->getMember()] = Member; 01452 } 01453 } 01454 01455 if (HasDependentBaseInit) { 01456 // FIXME. This does not preserve the ordering of the initializers. 01457 // Try (with -Wreorder) 01458 // template<class X> struct A {}; 01459 // template<class X> struct B : A<X> { 01460 // B() : x1(10), A<X>() {} 01461 // int x1; 01462 // }; 01463 // B<int> x; 01464 // On seeing one dependent type, we should essentially exit this routine 01465 // while preserving user-declared initializer list. When this routine is 01466 // called during instantiatiation process, this routine will rebuild the 01467 // ordered initializer list correctly. 01468 01469 // If we have a dependent base initialization, we can't determine the 01470 // association between initializers and bases; just dump the known 01471 // initializers into the list, and don't try to deal with other bases. 01472 for (unsigned i = 0; i < NumInitializers; i++) { 01473 CXXBaseOrMemberInitializer *Member = Initializers[i]; 01474 if (Member->isBaseInitializer()) 01475 AllToInit.push_back(Member); 01476 } 01477 } else { 01478 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit; 01479 01480 // Push virtual bases before others. 01481 for (CXXRecordDecl::base_class_iterator VBase = 01482 ClassDecl->vbases_begin(), 01483 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 01484 if (VBase->getType()->isDependentType()) 01485 continue; 01486 if (CXXBaseOrMemberInitializer *Value 01487 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 01488 AllToInit.push_back(Value); 01489 } else if (!AnyErrors) { 01490 InitializedEntity InitEntity 01491 = InitializedEntity::InitializeBase(Context, VBase); 01492 InitializationKind InitKind 01493 = InitializationKind::CreateDefault(Constructor->getLocation()); 01494 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 01495 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 01496 MultiExprArg(*this, 0, 0)); 01497 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 01498 if (BaseInit.isInvalid()) { 01499 HadError = true; 01500 continue; 01501 } 01502 01503 // Don't attach synthesized base initializers in a dependent 01504 // context; they'll be checked again at template instantiation 01505 // time. 01506 if (CurContext->isDependentContext()) 01507 continue; 01508 01509 CXXBaseOrMemberInitializer *CXXBaseInit = 01510 new (Context) CXXBaseOrMemberInitializer(Context, 01511 Context.getTrivialTypeSourceInfo(VBase->getType(), 01512 SourceLocation()), 01513 SourceLocation(), 01514 BaseInit.takeAs<Expr>(), 01515 SourceLocation()); 01516 AllToInit.push_back(CXXBaseInit); 01517 } 01518 } 01519 01520 for (CXXRecordDecl::base_class_iterator Base = 01521 ClassDecl->bases_begin(), 01522 E = ClassDecl->bases_end(); Base != E; ++Base) { 01523 // Virtuals are in the virtual base list and already constructed. 01524 if (Base->isVirtual()) 01525 continue; 01526 // Skip dependent types. 01527 if (Base->getType()->isDependentType()) 01528 continue; 01529 if (CXXBaseOrMemberInitializer *Value 01530 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 01531 AllToInit.push_back(Value); 01532 } 01533 else if (!AnyErrors) { 01534 InitializedEntity InitEntity 01535 = InitializedEntity::InitializeBase(Context, Base); 01536 InitializationKind InitKind 01537 = InitializationKind::CreateDefault(Constructor->getLocation()); 01538 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 01539 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 01540 MultiExprArg(*this, 0, 0)); 01541 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 01542 if (BaseInit.isInvalid()) { 01543 HadError = true; 01544 continue; 01545 } 01546 01547 // Don't attach synthesized base initializers in a dependent 01548 // context; they'll be regenerated at template instantiation 01549 // time. 01550 if (CurContext->isDependentContext()) 01551 continue; 01552 01553 CXXBaseOrMemberInitializer *CXXBaseInit = 01554 new (Context) CXXBaseOrMemberInitializer(Context, 01555 Context.getTrivialTypeSourceInfo(Base->getType(), 01556 SourceLocation()), 01557 SourceLocation(), 01558 BaseInit.takeAs<Expr>(), 01559 SourceLocation()); 01560 AllToInit.push_back(CXXBaseInit); 01561 } 01562 } 01563 } 01564 01565 // non-static data members. 01566 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 01567 E = ClassDecl->field_end(); Field != E; ++Field) { 01568 if ((*Field)->isAnonymousStructOrUnion()) { 01569 if (const RecordType *FieldClassType = 01570 Field->getType()->getAs<RecordType>()) { 01571 CXXRecordDecl *FieldClassDecl 01572 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 01573 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 01574 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 01575 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 01576 // 'Member' is the anonymous union field and 'AnonUnionMember' is 01577 // set to the anonymous union data member used in the initializer 01578 // list. 01579 Value->setMember(*Field); 01580 Value->setAnonUnionMember(*FA); 01581 AllToInit.push_back(Value); 01582 break; 01583 } 01584 } 01585 } 01586 continue; 01587 } 01588 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 01589 AllToInit.push_back(Value); 01590 continue; 01591 } 01592 01593 if ((*Field)->getType()->isDependentType() || AnyErrors) 01594 continue; 01595 01596 QualType FT = Context.getBaseElementType((*Field)->getType()); 01597 if (FT->getAs<RecordType>()) { 01598 InitializedEntity InitEntity 01599 = InitializedEntity::InitializeMember(*Field); 01600 InitializationKind InitKind 01601 = InitializationKind::CreateDefault(Constructor->getLocation()); 01602 01603 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 01604 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind, 01605 MultiExprArg(*this, 0, 0)); 01606 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 01607 if (MemberInit.isInvalid()) { 01608 HadError = true; 01609 continue; 01610 } 01611 01612 // Don't attach synthesized member initializers in a dependent 01613 // context; they'll be regenerated a template instantiation 01614 // time. 01615 if (CurContext->isDependentContext()) 01616 continue; 01617 01618 CXXBaseOrMemberInitializer *Member = 01619 new (Context) CXXBaseOrMemberInitializer(Context, 01620 *Field, SourceLocation(), 01621 SourceLocation(), 01622 MemberInit.takeAs<Expr>(), 01623 SourceLocation()); 01624 01625 AllToInit.push_back(Member); 01626 } 01627 else if (FT->isReferenceType()) { 01628 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 01629 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 01630 << 0 << (*Field)->getDeclName(); 01631 Diag((*Field)->getLocation(), diag::note_declared_at); 01632 HadError = true; 01633 } 01634 else if (FT.isConstQualified()) { 01635 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 01636 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 01637 << 1 << (*Field)->getDeclName(); 01638 Diag((*Field)->getLocation(), diag::note_declared_at); 01639 HadError = true; 01640 } 01641 } 01642 01643 NumInitializers = AllToInit.size(); 01644 if (NumInitializers > 0) { 01645 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 01646 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 01647 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 01648 01649 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 01650 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) { 01651 CXXBaseOrMemberInitializer *Member = AllToInit[Idx]; 01652 baseOrMemberInitializers[Idx] = Member; 01653 if (!Member->isBaseInitializer()) 01654 continue; 01655 const Type *BaseType = Member->getBaseClass(); 01656 const RecordType *RT = BaseType->getAs<RecordType>(); 01657 if (!RT) 01658 continue; 01659 CXXRecordDecl *BaseClassDecl = 01660 cast<CXXRecordDecl>(RT->getDecl()); 01661 if (BaseClassDecl->hasTrivialDestructor()) 01662 continue; 01663 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context); 01664 MarkDeclarationReferenced(Constructor->getLocation(), DD); 01665 } 01666 } 01667 01668 return HadError; 01669 } 01670 01671 static void *GetKeyForTopLevelField(FieldDecl *Field) { 01672 // For anonymous unions, use the class declaration as the key. 01673 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 01674 if (RT->getDecl()->isAnonymousStructOrUnion()) 01675 return static_cast<void *>(RT->getDecl()); 01676 } 01677 return static_cast<void *>(Field); 01678 } 01679 01680 static void *GetKeyForBase(QualType BaseType) { 01681 if (const RecordType *RT = BaseType->getAs<RecordType>()) 01682 return (void *)RT; 01683 01684 assert(0 && "Unexpected base type!"); 01685 return 0; 01686 } 01687 01688 static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 01689 bool MemberMaybeAnon = false) { 01690 // For fields injected into the class via declaration of an anonymous union, 01691 // use its anonymous union class declaration as the unique key. 01692 if (Member->isMemberInitializer()) { 01693 FieldDecl *Field = Member->getMember(); 01694 01695 // After SetBaseOrMemberInitializers call, Field is the anonymous union 01696 // data member of the class. Data member used in the initializer list is 01697 // in AnonUnionMember field. 01698 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 01699 Field = Member->getAnonUnionMember(); 01700 if (Field->getDeclContext()->isRecord()) { 01701 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 01702 if (RD->isAnonymousStructOrUnion()) 01703 return static_cast<void *>(RD); 01704 } 01705 return static_cast<void *>(Field); 01706 } 01707 01708 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 01709 } 01710 01711 /// ActOnMemInitializers - Handle the member initializers for a constructor. 01712 void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 01713 SourceLocation ColonLoc, 01714 MemInitTy **MemInits, unsigned NumMemInits, 01715 bool AnyErrors) { 01716 if (!ConstructorDecl) 01717 return; 01718 01719 AdjustDeclIfTemplate(ConstructorDecl); 01720 01721 CXXConstructorDecl *Constructor 01722 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 01723 01724 if (!Constructor) { 01725 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 01726 return; 01727 } 01728 01729 if (!Constructor->isDependentContext()) { 01730 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 01731 bool err = false; 01732 for (unsigned i = 0; i < NumMemInits; i++) { 01733 CXXBaseOrMemberInitializer *Member = 01734 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 01735 void *KeyToMember = GetKeyForMember(Member); 01736 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 01737 if (!PrevMember) { 01738 PrevMember = Member; 01739 continue; 01740 } 01741 if (FieldDecl *Field = Member->getMember()) 01742 Diag(Member->getSourceLocation(), 01743 diag::error_multiple_mem_initialization) 01744 << Field->getNameAsString() 01745 << Member->getSourceRange(); 01746 else { 01747 Type *BaseClass = Member->getBaseClass(); 01748 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 01749 Diag(Member->getSourceLocation(), 01750 diag::error_multiple_base_initialization) 01751 << QualType(BaseClass, 0) 01752 << Member->getSourceRange(); 01753 } 01754 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 01755 << 0; 01756 err = true; 01757 } 01758 01759 if (err) 01760 return; 01761 } 01762 01763 SetBaseOrMemberInitializers(Constructor, 01764 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 01765 NumMemInits, false, AnyErrors); 01766 01767 if (Constructor->isDependentContext()) 01768 return; 01769 01770 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 01771 Diagnostic::Ignored && 01772 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 01773 Diagnostic::Ignored) 01774 return; 01775 01776 // Also issue warning if order of ctor-initializer list does not match order 01777 // of 1) base class declarations and 2) order of non-static data members. 01778 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 01779 01780 CXXRecordDecl *ClassDecl 01781 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 01782 // Push virtual bases before others. 01783 for (CXXRecordDecl::base_class_iterator VBase = 01784 ClassDecl->vbases_begin(), 01785 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 01786 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 01787 01788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 01789 E = ClassDecl->bases_end(); Base != E; ++Base) { 01790 // Virtuals are alread in the virtual base list and are constructed 01791 // first. 01792 if (Base->isVirtual()) 01793 continue; 01794 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 01795 } 01796 01797 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 01798 E = ClassDecl->field_end(); Field != E; ++Field) 01799 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 01800 01801 int Last = AllBaseOrMembers.size(); 01802 int curIndex = 0; 01803 CXXBaseOrMemberInitializer *PrevMember = 0; 01804 for (unsigned i = 0; i < NumMemInits; i++) { 01805 CXXBaseOrMemberInitializer *Member = 01806 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 01807 void *MemberInCtorList = GetKeyForMember(Member, true); 01808 01809 for (; curIndex < Last; curIndex++) 01810 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 01811 break; 01812 if (curIndex == Last) { 01813 assert(PrevMember && "Member not in member list?!"); 01814 // Initializer as specified in ctor-initializer list is out of order. 01815 // Issue a warning diagnostic. 01816 if (PrevMember->isBaseInitializer()) { 01817 // Diagnostics is for an initialized base class. 01818 Type *BaseClass = PrevMember->getBaseClass(); 01819 Diag(PrevMember->getSourceLocation(), 01820 diag::warn_base_initialized) 01821 << QualType(BaseClass, 0); 01822 } else { 01823 FieldDecl *Field = PrevMember->getMember(); 01824 Diag(PrevMember->getSourceLocation(), 01825 diag::warn_field_initialized) 01826 << Field->getNameAsString(); 01827 } 01828 // Also the note! 01829 if (FieldDecl *Field = Member->getMember()) 01830 Diag(Member->getSourceLocation(), 01831 diag::note_fieldorbase_initialized_here) << 0 01832 << Field->getNameAsString(); 01833 else { 01834 Type *BaseClass = Member->getBaseClass(); 01835 Diag(Member->getSourceLocation(), 01836 diag::note_fieldorbase_initialized_here) << 1 01837 << QualType(BaseClass, 0); 01838 } 01839 for (curIndex = 0; curIndex < Last; curIndex++) 01840 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 01841 break; 01842 } 01843 PrevMember = Member; 01844 } 01845 } 01846 01847 void 01848 Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) { 01849 // Ignore dependent destructors. 01850 if (Destructor->isDependentContext()) 01851 return; 01852 01853 CXXRecordDecl *ClassDecl = Destructor->getParent(); 01854 01855 // Non-static data members. 01856 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 01857 E = ClassDecl->field_end(); I != E; ++I) { 01858 FieldDecl *Field = *I; 01859 01860 QualType FieldType = Context.getBaseElementType(Field->getType()); 01861 01862 const RecordType* RT = FieldType->getAs<RecordType>(); 01863 if (!RT) 01864 continue; 01865 01866 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 01867 if (FieldClassDecl->hasTrivialDestructor()) 01868 continue; 01869 01870 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 01871 MarkDeclarationReferenced(Destructor->getLocation(), 01872 const_cast<CXXDestructorDecl*>(Dtor)); 01873 } 01874 01875 // Bases. 01876 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 01877 E = ClassDecl->bases_end(); Base != E; ++Base) { 01878 // Ignore virtual bases. 01879 if (Base->isVirtual()) 01880 continue; 01881 01882 // Ignore trivial destructors. 01883 CXXRecordDecl *BaseClassDecl 01884 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 01885 if (BaseClassDecl->hasTrivialDestructor()) 01886 continue; 01887 01888 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 01889 MarkDeclarationReferenced(Destructor->getLocation(), 01890 const_cast<CXXDestructorDecl*>(Dtor)); 01891 } 01892 01893 // Virtual bases. 01894 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 01895 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 01896 // Ignore trivial destructors. 01897 CXXRecordDecl *BaseClassDecl 01898 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 01899 if (BaseClassDecl->hasTrivialDestructor()) 01900 continue; 01901 01902 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 01903 MarkDeclarationReferenced(Destructor->getLocation(), 01904 const_cast<CXXDestructorDecl*>(Dtor)); 01905 } 01906 } 01907 01908 void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 01909 if (!CDtorDecl) 01910 return; 01911 01912 AdjustDeclIfTemplate(CDtorDecl); 01913 01914 if (CXXConstructorDecl *Constructor 01915 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 01916 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false); 01917 } 01918 01919 namespace { 01920 /// PureVirtualMethodCollector - traverses a class and its superclasses 01921 /// and determines if it has any pure virtual methods. 01922 class PureVirtualMethodCollector { 01923 ASTContext &Context; 01924 01925 public: 01926 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 01927 01928 private: 01929 MethodList Methods; 01930 01931 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 01932 01933 public: 01934 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 01935 : Context(Ctx) { 01936 01937 MethodList List; 01938 Collect(RD, List); 01939 01940 // Copy the temporary list to methods, and make sure to ignore any 01941 // null entries. 01942 for (size_t i = 0, e = List.size(); i != e; ++i) { 01943 if (List[i]) 01944 Methods.push_back(List[i]); 01945 } 01946 } 01947 01948 bool empty() const { return Methods.empty(); } 01949 01950 MethodList::const_iterator methods_begin() { return Methods.begin(); } 01951 MethodList::const_iterator methods_end() { return Methods.end(); } 01952 }; 01953 01954 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 01955 MethodList& Methods) { 01956 // First, collect the pure virtual methods for the base classes. 01957 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 01958 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 01959 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 01960 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 01961 if (BaseDecl && BaseDecl->isAbstract()) 01962 Collect(BaseDecl, Methods); 01963 } 01964 } 01965 01966 // Next, zero out any pure virtual methods that this class overrides. 01967 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 01968 01969 MethodSetTy OverriddenMethods; 01970 size_t MethodsSize = Methods.size(); 01971 01972 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 01973 i != e; ++i) { 01974 // Traverse the record, looking for methods. 01975 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 01976 // If the method is pure virtual, add it to the methods vector. 01977 if (MD->isPure()) 01978 Methods.push_back(MD); 01979 01980 // Record all the overridden methods in our set. 01981 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 01982 E = MD->end_overridden_methods(); I != E; ++I) { 01983 // Keep track of the overridden methods. 01984 OverriddenMethods.insert(*I); 01985 } 01986 } 01987 } 01988 01989 // Now go through the methods and zero out all the ones we know are 01990 // overridden. 01991 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 01992 if (OverriddenMethods.count(Methods[i])) 01993 Methods[i] = 0; 01994 } 01995 01996 } 01997 } 01998 01999 02000 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 02001 unsigned DiagID, AbstractDiagSelID SelID, 02002 const CXXRecordDecl *CurrentRD) { 02003 if (SelID == -1) 02004 return RequireNonAbstractType(Loc, T, 02005 PDiag(DiagID), CurrentRD); 02006 else 02007 return RequireNonAbstractType(Loc, T, 02008 PDiag(DiagID) << SelID, CurrentRD); 02009 } 02010 02011 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 02012 const PartialDiagnostic &PD, 02013 const CXXRecordDecl *CurrentRD) { 02014 if (!getLangOptions().CPlusPlus) 02015 return false; 02016 02017 if (const ArrayType *AT = Context.getAsArrayType(T)) 02018 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 02019 CurrentRD); 02020 02021 if (const PointerType *PT = T->getAs<PointerType>()) { 02022 // Find the innermost pointer type. 02023 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 02024 PT = T; 02025 02026 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 02027 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 02028 } 02029 02030 const RecordType *RT = T->getAs<RecordType>(); 02031 if (!RT) 02032 return false; 02033 02034 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 02035 02036 if (CurrentRD && CurrentRD != RD) 02037 return false; 02038 02039 // FIXME: is this reasonable? It matches current behavior, but.... 02040 if (!RD->getDefinition()) 02041 return false; 02042 02043 if (!RD->isAbstract()) 02044 return false; 02045 02046 Diag(Loc, PD) << RD->getDeclName(); 02047 02048 // Check if we've already emitted the list of pure virtual functions for this 02049 // class. 02050 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 02051 return true; 02052 02053 PureVirtualMethodCollector Collector(Context, RD); 02054 02055 for (PureVirtualMethodCollector::MethodList::const_iterator I = 02056 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 02057 const CXXMethodDecl *MD = *I; 02058 02059 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 02060 MD->getDeclName(); 02061 } 02062 02063 if (!PureVirtualClassDiagSet) 02064 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 02065 PureVirtualClassDiagSet->insert(RD); 02066 02067 return true; 02068 } 02069 02070 namespace { 02071 class AbstractClassUsageDiagnoser 02072 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 02073 Sema &SemaRef; 02074 CXXRecordDecl *AbstractClass; 02075 02076 bool VisitDeclContext(const DeclContext *DC) { 02077 bool Invalid = false; 02078 02079 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 02080 E = DC->decls_end(); I != E; ++I) 02081 Invalid |= Visit(*I); 02082 02083 return Invalid; 02084 } 02085 02086 public: 02087 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 02088 : SemaRef(SemaRef), AbstractClass(ac) { 02089 Visit(SemaRef.Context.getTranslationUnitDecl()); 02090 } 02091 02092 bool VisitFunctionDecl(const FunctionDecl *FD) { 02093 if (FD->isThisDeclarationADefinition()) { 02094 // No need to do the check if we're in a definition, because it requires 02095 // that the return/param types are complete. 02096 // because that requires 02097 return VisitDeclContext(FD); 02098 } 02099 02100 // Check the return type. 02101 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 02102 bool Invalid = 02103 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 02104 diag::err_abstract_type_in_decl, 02105 Sema::AbstractReturnType, 02106 AbstractClass); 02107 02108 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 02109 E = FD->param_end(); I != E; ++I) { 02110 const ParmVarDecl *VD = *I; 02111 Invalid |= 02112 SemaRef.RequireNonAbstractType(VD->getLocation(), 02113 VD->getOriginalType(), 02114 diag::err_abstract_type_in_decl, 02115 Sema::AbstractParamType, 02116 AbstractClass); 02117 } 02118 02119 return Invalid; 02120 } 02121 02122 bool VisitDecl(const Decl* D) { 02123 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 02124 return VisitDeclContext(DC); 02125 02126 return false; 02127 } 02128 }; 02129 } 02130 02131 /// \brief Perform semantic checks on a class definition that has been 02132 /// completing, introducing implicitly-declared members, checking for 02133 /// abstract types, etc. 02134 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 02135 if (!Record || Record->isInvalidDecl()) 02136 return; 02137 02138 if (!Record->isDependentType()) 02139 AddImplicitlyDeclaredMembersToClass(Record); 02140 02141 if (Record->isInvalidDecl()) 02142 return; 02143 02144 // Set access bits correctly on the directly-declared conversions. 02145 UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 02146 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 02147 Convs->setAccess(I, (*I)->getAccess()); 02148 02149 if (!Record->isAbstract()) { 02150 // Collect all the pure virtual methods and see if this is an abstract 02151 // class after all. 02152 PureVirtualMethodCollector Collector(Context, Record); 02153 if (!Collector.empty()) 02154 Record->setAbstract(true); 02155 } 02156 02157 if (Record->isAbstract()) 02158 (void)AbstractClassUsageDiagnoser(*this, Record); 02159 } 02160 02161 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 02162 DeclPtrTy TagDecl, 02163 SourceLocation LBrac, 02164 SourceLocation RBrac) { 02165 if (!TagDecl) 02166 return; 02167 02168 AdjustDeclIfTemplate(TagDecl); 02169 02170 ActOnFields(S, RLoc, TagDecl, 02171 (DeclPtrTy*)FieldCollector->getCurFields(), 02172 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 02173 02174 CheckCompletedCXXClass( 02175 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 02176 } 02177 02178 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 02179 /// special functions, such as the default constructor, copy 02180 /// constructor, or destructor, to the given C++ class (C++ 02181 /// [special]p1). This routine can only be executed just before the 02182 /// definition of the class is complete. 02183 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 02184 CanQualType ClassType 02185 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 02186 02187 // FIXME: Implicit declarations have exception specifications, which are 02188 // the union of the specifications of the implicitly called functions. 02189 02190 if (!ClassDecl->hasUserDeclaredConstructor()) { 02191 // C++ [class.ctor]p5: 02192 // A default constructor for a class X is a constructor of class X 02193 // that can be called without an argument. If there is no 02194 // user-declared constructor for class X, a default constructor is 02195 // implicitly declared. An implicitly-declared default constructor 02196 // is an inline public member of its class. 02197 DeclarationName Name 02198 = Context.DeclarationNames.getCXXConstructorName(ClassType); 02199 CXXConstructorDecl *DefaultCon = 02200 CXXConstructorDecl::Create(Context, ClassDecl, 02201 ClassDecl->getLocation(), Name, 02202 Context.getFunctionType(Context.VoidTy, 02203 0, 0, false, 0, 02204 /*FIXME*/false, false, 02205 0, 0, false, 02206 CC_Default), 02207 /*TInfo=*/0, 02208 /*isExplicit=*/false, 02209 /*isInline=*/true, 02210 /*isImplicitlyDeclared=*/true); 02211 DefaultCon->setAccess(AS_public); 02212 DefaultCon->setImplicit(); 02213 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 02214 ClassDecl->addDecl(DefaultCon); 02215 } 02216 02217 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 02218 // C++ [class.copy]p4: 02219 // If the class definition does not explicitly declare a copy 02220 // constructor, one is declared implicitly. 02221 02222 // C++ [class.copy]p5: 02223 // The implicitly-declared copy constructor for a class X will 02224 // have the form 02225 // 02226 // X::X(const X&) 02227 // 02228 // if 02229 bool HasConstCopyConstructor = true; 02230 02231 // -- each direct or virtual base class B of X has a copy 02232 // constructor whose first parameter is of type const B& or 02233 // const volatile B&, and 02234 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 02235 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 02236 const CXXRecordDecl *BaseClassDecl 02237 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 02238 HasConstCopyConstructor 02239 = BaseClassDecl->hasConstCopyConstructor(Context); 02240 } 02241 02242 // -- for all the nonstatic data members of X that are of a 02243 // class type M (or array thereof), each such class type 02244 // has a copy constructor whose first parameter is of type 02245 // const M& or const volatile M&. 02246 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 02247 HasConstCopyConstructor && Field != ClassDecl->field_end(); 02248 ++Field) { 02249 QualType FieldType = (*Field)->getType(); 02250 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 02251 FieldType = Array->getElementType(); 02252 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 02253 const CXXRecordDecl *FieldClassDecl 02254 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 02255 HasConstCopyConstructor 02256 = FieldClassDecl->hasConstCopyConstructor(Context); 02257 } 02258 } 02259 02260 // Otherwise, the implicitly declared copy constructor will have 02261 // the form 02262 // 02263 // X::X(X&) 02264 QualType ArgType = ClassType; 02265 if (HasConstCopyConstructor) 02266 ArgType = ArgType.withConst(); 02267 ArgType = Context.getLValueReferenceType(ArgType); 02268 02269 // An implicitly-declared copy constructor is an inline public 02270 // member of its class. 02271 DeclarationName Name 02272 = Context.DeclarationNames.getCXXConstructorName(ClassType); 02273 CXXConstructorDecl *CopyConstructor 02274 = CXXConstructorDecl::Create(Context, ClassDecl, 02275 ClassDecl->getLocation(), Name, 02276 Context.getFunctionType(Context.VoidTy, 02277 &ArgType, 1, 02278 false, 0, 02279 /*FIXME:*/false, 02280 false, 0, 0, false, 02281 CC_Default), 02282 /*TInfo=*/0, 02283 /*isExplicit=*/false, 02284 /*isInline=*/true, 02285 /*isImplicitlyDeclared=*/true); 02286 CopyConstructor->setAccess(AS_public); 02287 CopyConstructor->setImplicit(); 02288 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 02289 02290 // Add the parameter to the constructor. 02291 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 02292 ClassDecl->getLocation(), 02293 /*IdentifierInfo=*/0, 02294 ArgType, /*TInfo=*/0, 02295 VarDecl::None, 0); 02296 CopyConstructor->setParams(&FromParam, 1); 02297 ClassDecl->addDecl(CopyConstructor); 02298 } 02299 02300 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 02301 // Note: The following rules are largely analoguous to the copy 02302 // constructor rules. Note that virtual bases are not taken into account 02303 // for determining the argument type of the operator. Note also that 02304 // operators taking an object instead of a reference are allowed. 02305 // 02306 // C++ [class.copy]p10: 02307 // If the class definition does not explicitly declare a copy 02308 // assignment operator, one is declared implicitly. 02309 // The implicitly-defined copy assignment operator for a class X 02310 // will have the form 02311 // 02312 // X& X::operator=(const X&) 02313 // 02314 // if 02315 bool HasConstCopyAssignment = true; 02316 02317 // -- each direct base class B of X has a copy assignment operator 02318 // whose parameter is of type const B&, const volatile B& or B, 02319 // and 02320 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 02321 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 02322 assert(!Base->getType()->isDependentType() && 02323 "Cannot generate implicit members for class with dependent bases."); 02324 const CXXRecordDecl *BaseClassDecl 02325 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 02326 const CXXMethodDecl *MD = 0; 02327 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 02328 MD); 02329 } 02330 02331 // -- for all the nonstatic data members of X that are of a class 02332 // type M (or array thereof), each such class type has a copy 02333 // assignment operator whose parameter is of type const M&, 02334 // const volatile M& or M. 02335 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 02336 HasConstCopyAssignment && Field != ClassDecl->field_end(); 02337 ++Field) { 02338 QualType FieldType = (*Field)->getType(); 02339 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 02340 FieldType = Array->getElementType(); 02341 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 02342 const CXXRecordDecl *FieldClassDecl 02343 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 02344 const CXXMethodDecl *MD = 0; 02345 HasConstCopyAssignment 02346 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 02347 } 02348 } 02349 02350 // Otherwise, the implicitly declared copy assignment operator will 02351 // have the form 02352 // 02353 // X& X::operator=(X&) 02354 QualType ArgType = ClassType; 02355 QualType RetType = Context.getLValueReferenceType(ArgType); 02356 if (HasConstCopyAssignment) 02357 ArgType = ArgType.withConst(); 02358 ArgType = Context.getLValueReferenceType(ArgType); 02359 02360 // An implicitly-declared copy assignment operator is an inline public 02361 // member of its class. 02362 DeclarationName Name = 02363 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 02364 CXXMethodDecl *CopyAssignment = 02365 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 02366 Context.getFunctionType(RetType, &ArgType, 1, 02367 false, 0, 02368 /*FIXME:*/false, 02369 false, 0, 0, false, 02370 CC_Default), 02371 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 02372 CopyAssignment->setAccess(AS_public); 02373 CopyAssignment->setImplicit(); 02374 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 02375 CopyAssignment->setCopyAssignment(true); 02376 02377 // Add the parameter to the operator. 02378 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 02379 ClassDecl->getLocation(), 02380 /*IdentifierInfo=*/0, 02381 ArgType, /*TInfo=*/0, 02382 VarDecl::None, 0); 02383 CopyAssignment->setParams(&FromParam, 1); 02384 02385 // Don't call addedAssignmentOperator. There is no way to distinguish an 02386 // implicit from an explicit assignment operator. 02387 ClassDecl->addDecl(CopyAssignment); 02388 AddOverriddenMethods(ClassDecl, CopyAssignment); 02389 } 02390 02391 if (!ClassDecl->hasUserDeclaredDestructor()) { 02392 // C++ [class.dtor]p2: 02393 // If a class has no user-declared destructor, a destructor is 02394 // declared implicitly. An implicitly-declared destructor is an 02395 // inline public member of its class. 02396 QualType Ty = Context.getFunctionType(Context.VoidTy, 02397 0, 0, false, 0, 02398 /*FIXME:*/false, 02399 false, 0, 0, false, 02400 CC_Default); 02401 02402 DeclarationName Name 02403 = Context.DeclarationNames.getCXXDestructorName(ClassType); 02404 CXXDestructorDecl *Destructor 02405 = CXXDestructorDecl::Create(Context, ClassDecl, 02406 ClassDecl->getLocation(), Name, Ty, 02407 /*isInline=*/true, 02408 /*isImplicitlyDeclared=*/true); 02409 Destructor->setAccess(AS_public); 02410 Destructor->setImplicit(); 02411 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 02412 ClassDecl->addDecl(Destructor); 02413 02414 // This could be uniqued if it ever proves significant. 02415 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 02416 02417 AddOverriddenMethods(ClassDecl, Destructor); 02418 } 02419 } 02420 02421 void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 02422 Decl *D = TemplateD.getAs<Decl>(); 02423 if (!D) 02424 return; 02425 02426 TemplateParameterList *Params = 0; 02427 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 02428 Params = Template->getTemplateParameters(); 02429 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 02430 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 02431 Params = PartialSpec->getTemplateParameters(); 02432 else 02433 return; 02434 02435 for (TemplateParameterList::iterator Param = Params->begin(), 02436 ParamEnd = Params->end(); 02437 Param != ParamEnd; ++Param) { 02438 NamedDecl *Named = cast<NamedDecl>(*Param); 02439 if (Named->getDeclName()) { 02440 S->AddDecl(DeclPtrTy::make(Named)); 02441 IdResolver.AddDecl(Named); 02442 } 02443 } 02444 } 02445 02446 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 02447 if (!RecordD) return; 02448 AdjustDeclIfTemplate(RecordD); 02449 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 02450 PushDeclContext(S, Record); 02451 } 02452 02453 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 02454 if (!RecordD) return; 02455 PopDeclContext(); 02456 } 02457 02458 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 02459 /// parsing a top-level (non-nested) C++ class, and we are now 02460 /// parsing those parts of the given Method declaration that could 02461 /// not be parsed earlier (C++ [class.mem]p2), such as default 02462 /// arguments. This action should enter the scope of the given 02463 /// Method declaration as if we had just parsed the qualified method 02464 /// name. However, it should not bring the parameters into scope; 02465 /// that will be performed by ActOnDelayedCXXMethodParameter. 02466 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 02467 } 02468 02469 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 02470 /// C++ method declaration. We're (re-)introducing the given 02471 /// function parameter into scope for use in parsing later parts of 02472 /// the method declaration. For example, we could see an 02473 /// ActOnParamDefaultArgument event for this parameter. 02474 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 02475 if (!ParamD) 02476 return; 02477 02478 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 02479 02480 // If this parameter has an unparsed default argument, clear it out 02481 // to make way for the parsed default argument. 02482 if (Param->hasUnparsedDefaultArg()) 02483 Param->setDefaultArg(0); 02484 02485 S->AddDecl(DeclPtrTy::make(Param)); 02486 if (Param->getDeclName()) 02487 IdResolver.AddDecl(Param); 02488 } 02489 02490 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 02491 /// processing the delayed method declaration for Method. The method 02492 /// declaration is now considered finished. There may be a separate 02493 /// ActOnStartOfFunctionDef action later (not necessarily 02494 /// immediately!) for this method, if it was also defined inside the 02495 /// class body. 02496 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 02497 if (!MethodD) 02498 return; 02499 02500 AdjustDeclIfTemplate(MethodD); 02501 02502 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 02503 02504 // Now that we have our default arguments, check the constructor 02505 // again. It could produce additional diagnostics or affect whether 02506 // the class has implicitly-declared destructors, among other 02507 // things. 02508 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 02509 CheckConstructor(Constructor); 02510 02511 // Check the default arguments, which we may have added. 02512 if (!Method->isInvalidDecl()) 02513 CheckCXXDefaultArguments(Method); 02514 } 02515 02516 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 02517 /// the well-formedness of the constructor declarator @p D with type @p 02518 /// R. If there are any errors in the declarator, this routine will 02519 /// emit diagnostics and set the invalid bit to true. In any case, the type 02520 /// will be updated to reflect a well-formed type for the constructor and 02521 /// returned. 02522 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 02523 FunctionDecl::StorageClass &SC) { 02524 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 02525 02526 // C++ [class.ctor]p3: 02527 // A constructor shall not be virtual (10.3) or static (9.4). A 02528 // constructor can be invoked for a const, volatile or const 02529 // volatile object. A constructor shall not be declared const, 02530 // volatile, or const volatile (9.3.2). 02531 if (isVirtual) { 02532 if (!D.isInvalidType()) 02533 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 02534 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 02535 << SourceRange(D.getIdentifierLoc()); 02536 D.setInvalidType(); 02537 } 02538 if (SC == FunctionDecl::Static) { 02539 if (!D.isInvalidType()) 02540 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 02541 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 02542 << SourceRange(D.getIdentifierLoc()); 02543 D.setInvalidType(); 02544 SC = FunctionDecl::None; 02545 } 02546 02547 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 02548 if (FTI.TypeQuals != 0) { 02549 if (FTI.TypeQuals & Qualifiers::Const) 02550 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02551 << "const" << SourceRange(D.getIdentifierLoc()); 02552 if (FTI.TypeQuals & Qualifiers::Volatile) 02553 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02554 << "volatile" << SourceRange(D.getIdentifierLoc()); 02555 if (FTI.TypeQuals & Qualifiers::Restrict) 02556 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02557 << "restrict" << SourceRange(D.getIdentifierLoc()); 02558 } 02559 02560 // Rebuild the function type "R" without any type qualifiers (in 02561 // case any of the errors above fired) and with "void" as the 02562 // return type, since constructors don't have return types. We 02563 // *always* have to do this, because GetTypeForDeclarator will 02564 // put in a result type of "int" when none was specified. 02565 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 02566 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 02567 Proto->getNumArgs(), 02568 Proto->isVariadic(), 0, 02569 Proto->hasExceptionSpec(), 02570 Proto->hasAnyExceptionSpec(), 02571 Proto->getNumExceptions(), 02572 Proto->exception_begin(), 02573 Proto->getNoReturnAttr(), 02574 Proto->getCallConv()); 02575 } 02576 02577 /// CheckConstructor - Checks a fully-formed constructor for 02578 /// well-formedness, issuing any diagnostics required. Returns true if 02579 /// the constructor declarator is invalid. 02580 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 02581 CXXRecordDecl *ClassDecl 02582 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 02583 if (!ClassDecl) 02584 return Constructor->setInvalidDecl(); 02585 02586 // C++ [class.copy]p3: 02587 // A declaration of a constructor for a class X is ill-formed if 02588 // its first parameter is of type (optionally cv-qualified) X and 02589 // either there are no other parameters or else all other 02590 // parameters have default arguments. 02591 if (!Constructor->isInvalidDecl() && 02592 ((Constructor->getNumParams() == 1) || 02593 (Constructor->getNumParams() > 1 && 02594 Constructor->getParamDecl(1)->hasDefaultArg())) && 02595 Constructor->getTemplateSpecializationKind() 02596 != TSK_ImplicitInstantiation) { 02597 QualType ParamType = Constructor->getParamDecl(0)->getType(); 02598 QualType ClassTy = Context.getTagDeclType(ClassDecl); 02599 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 02600 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 02601 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 02602 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 02603 02604 // FIXME: Rather that making the constructor invalid, we should endeavor 02605 // to fix the type. 02606 Constructor->setInvalidDecl(); 02607 } 02608 } 02609 02610 // Notify the class that we've added a constructor. 02611 ClassDecl->addedConstructor(Context, Constructor); 02612 } 02613 02614 /// CheckDestructor - Checks a fully-formed destructor for well-formedness, 02615 /// issuing any diagnostics required. Returns true on error. 02616 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 02617 CXXRecordDecl *RD = Destructor->getParent(); 02618 02619 if (Destructor->isVirtual()) { 02620 SourceLocation Loc; 02621 02622 if (!Destructor->isImplicit()) 02623 Loc = Destructor->getLocation(); 02624 else 02625 Loc = RD->getLocation(); 02626 02627 // If we have a virtual destructor, look up the deallocation function 02628 FunctionDecl *OperatorDelete = 0; 02629 DeclarationName Name = 02630 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 02631 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 02632 return true; 02633 02634 Destructor->setOperatorDelete(OperatorDelete); 02635 } 02636 02637 return false; 02638 } 02639 02640 static inline bool 02641 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 02642 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 02643 FTI.ArgInfo[0].Param && 02644 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 02645 } 02646 02647 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 02648 /// the well-formednes of the destructor declarator @p D with type @p 02649 /// R. If there are any errors in the declarator, this routine will 02650 /// emit diagnostics and set the declarator to invalid. Even if this happens, 02651 /// will be updated to reflect a well-formed type for the destructor and 02652 /// returned. 02653 QualType Sema::CheckDestructorDeclarator(Declarator &D, 02654 FunctionDecl::StorageClass& SC) { 02655 // C++ [class.dtor]p1: 02656 // [...] A typedef-name that names a class is a class-name 02657 // (7.1.3); however, a typedef-name that names a class shall not 02658 // be used as the identifier in the declarator for a destructor 02659 // declaration. 02660 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 02661 if (isa<TypedefType>(DeclaratorType)) { 02662 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 02663 << DeclaratorType; 02664 D.setInvalidType(); 02665 } 02666 02667 // C++ [class.dtor]p2: 02668 // A destructor is used to destroy objects of its class type. A 02669 // destructor takes no parameters, and no return type can be 02670 // specified for it (not even void). The address of a destructor 02671 // shall not be taken. A destructor shall not be static. A 02672 // destructor can be invoked for a const, volatile or const 02673 // volatile object. A destructor shall not be declared const, 02674 // volatile or const volatile (9.3.2). 02675 if (SC == FunctionDecl::Static) { 02676 if (!D.isInvalidType()) 02677 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 02678 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 02679 << SourceRange(D.getIdentifierLoc()); 02680 SC = FunctionDecl::None; 02681 D.setInvalidType(); 02682 } 02683 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 02684 // Destructors don't have return types, but the parser will 02685 // happily parse something like: 02686 // 02687 // class X { 02688 // float ~X(); 02689 // }; 02690 // 02691 // The return type will be eliminated later. 02692 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 02693 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 02694 << SourceRange(D.getIdentifierLoc()); 02695 } 02696 02697 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 02698 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 02699 if (FTI.TypeQuals & Qualifiers::Const) 02700 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 02701 << "const" << SourceRange(D.getIdentifierLoc()); 02702 if (FTI.TypeQuals & Qualifiers::Volatile) 02703 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 02704 << "volatile" << SourceRange(D.getIdentifierLoc()); 02705 if (FTI.TypeQuals & Qualifiers::Restrict) 02706 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 02707 << "restrict" << SourceRange(D.getIdentifierLoc()); 02708 D.setInvalidType(); 02709 } 02710 02711 // Make sure we don't have any parameters. 02712 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 02713 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 02714 02715 // Delete the parameters. 02716 FTI.freeArgs(); 02717 D.setInvalidType(); 02718 } 02719 02720 // Make sure the destructor isn't variadic. 02721 if (FTI.isVariadic) { 02722 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 02723 D.setInvalidType(); 02724 } 02725 02726 // Rebuild the function type "R" without any type qualifiers or 02727 // parameters (in case any of the errors above fired) and with 02728 // "void" as the return type, since destructors don't have return 02729 // types. We *always* have to do this, because GetTypeForDeclarator 02730 // will put in a result type of "int" when none was specified. 02731 // FIXME: Exceptions! 02732 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 02733 false, false, 0, 0, false, CC_Default); 02734 } 02735 02736 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 02737 /// well-formednes of the conversion function declarator @p D with 02738 /// type @p R. If there are any errors in the declarator, this routine 02739 /// will emit diagnostics and return true. Otherwise, it will return 02740 /// false. Either way, the type @p R will be updated to reflect a 02741 /// well-formed type for the conversion operator. 02742 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 02743 FunctionDecl::StorageClass& SC) { 02744 // C++ [class.conv.fct]p1: 02745 // Neither parameter types nor return type can be specified. The 02746 // type of a conversion function (8.3.5) is "function taking no 02747 // parameter returning conversion-type-id." 02748 if (SC == FunctionDecl::Static) { 02749 if (!D.isInvalidType()) 02750 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 02751 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 02752 << SourceRange(D.getIdentifierLoc()); 02753 D.setInvalidType(); 02754 SC = FunctionDecl::None; 02755 } 02756 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 02757 // Conversion functions don't have return types, but the parser will 02758 // happily parse something like: 02759 // 02760 // class X { 02761 // float operator bool(); 02762 // }; 02763 // 02764 // The return type will be changed later anyway. 02765 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 02766 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 02767 << SourceRange(D.getIdentifierLoc()); 02768 } 02769 02770 // Make sure we don't have any parameters. 02771 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 02772 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 02773 02774 // Delete the parameters. 02775 D.getTypeObject(0).Fun.freeArgs(); 02776 D.setInvalidType(); 02777 } 02778 02779 // Make sure the conversion function isn't variadic. 02780 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 02781 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 02782 D.setInvalidType(); 02783 } 02784 02785 // C++ [class.conv.fct]p4: 02786 // The conversion-type-id shall not represent a function type nor 02787 // an array type. 02788 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 02789 if (ConvType->isArrayType()) { 02790 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 02791 ConvType = Context.getPointerType(ConvType); 02792 D.setInvalidType(); 02793 } else if (ConvType->isFunctionType()) { 02794 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 02795 ConvType = Context.getPointerType(ConvType); 02796 D.setInvalidType(); 02797 } 02798 02799 // Rebuild the function type "R" without any parameters (in case any 02800 // of the errors above fired) and with the conversion type as the 02801 // return type. 02802 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 02803 R = Context.getFunctionType(ConvType, 0, 0, false, 02804 Proto->getTypeQuals(), 02805 Proto->hasExceptionSpec(), 02806 Proto->hasAnyExceptionSpec(), 02807 Proto->getNumExceptions(), 02808 Proto->exception_begin(), 02809 Proto->getNoReturnAttr(), 02810 Proto->getCallConv()); 02811 02812 // C++0x explicit conversion operators. 02813 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 02814 Diag(D.getDeclSpec().getExplicitSpecLoc(), 02815 diag::warn_explicit_conversion_functions) 02816 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 02817 } 02818 02819 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 02820 /// the declaration of the given C++ conversion function. This routine 02821 /// is responsible for recording the conversion function in the C++ 02822 /// class, if possible. 02823 Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 02824 assert(Conversion && "Expected to receive a conversion function declaration"); 02825 02826 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 02827 02828 // Make sure we aren't redeclaring the conversion function. 02829 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 02830 02831 // C++ [class.conv.fct]p1: 02832 // [...] A conversion function is never used to convert a 02833 // (possibly cv-qualified) object to the (possibly cv-qualified) 02834 // same object type (or a reference to it), to a (possibly 02835 // cv-qualified) base class of that type (or a reference to it), 02836 // or to (possibly cv-qualified) void. 02837 // FIXME: Suppress this warning if the conversion function ends up being a 02838 // virtual function that overrides a virtual function in a base class. 02839 QualType ClassType 02840 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 02841 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 02842 ConvType = ConvTypeRef->getPointeeType(); 02843 if (ConvType->isRecordType()) { 02844 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 02845 if (ConvType == ClassType) 02846 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 02847 << ClassType; 02848 else if (IsDerivedFrom(ClassType, ConvType)) 02849 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 02850 << ClassType << ConvType; 02851 } else if (ConvType->isVoidType()) { 02852 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 02853 << ClassType << ConvType; 02854 } 02855 02856 if (Conversion->getPrimaryTemplate()) { 02857 // ignore specializations 02858 } else if (Conversion->getPreviousDeclaration()) { 02859 if (FunctionTemplateDecl *ConversionTemplate 02860 = Conversion->getDescribedFunctionTemplate()) { 02861 if (ClassDecl->replaceConversion( 02862 ConversionTemplate->getPreviousDeclaration(), 02863 ConversionTemplate)) 02864 return DeclPtrTy::make(ConversionTemplate); 02865 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 02866 Conversion)) 02867 return DeclPtrTy::make(Conversion); 02868 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 02869 } else if (FunctionTemplateDecl *ConversionTemplate 02870 = Conversion->getDescribedFunctionTemplate()) 02871 ClassDecl->addConversionFunction(ConversionTemplate); 02872 else 02873 ClassDecl->addConversionFunction(Conversion); 02874 02875 return DeclPtrTy::make(Conversion); 02876 } 02877 02878 //===----------------------------------------------------------------------===// 02879 // Namespace Handling 02880 //===----------------------------------------------------------------------===// 02881 02882 /// ActOnStartNamespaceDef - This is called at the start of a namespace 02883 /// definition. 02884 Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 02885 SourceLocation IdentLoc, 02886 IdentifierInfo *II, 02887 SourceLocation LBrace, 02888 AttributeList *AttrList) { 02889 NamespaceDecl *Namespc = 02890 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 02891 Namespc->setLBracLoc(LBrace); 02892 02893 Scope *DeclRegionScope = NamespcScope->getParent(); 02894 02895 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 02896 02897 if (II) { 02898 // C++ [namespace.def]p2: 02899 // The identifier in an original-namespace-definition shall not have been 02900 // previously defined in the declarative region in which the 02901 // original-namespace-definition appears. The identifier in an 02902 // original-namespace-definition is the name of the namespace. Subsequently 02903 // in that declarative region, it is treated as an original-namespace-name. 02904 02905 NamedDecl *PrevDecl 02906 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, 02907 ForRedeclaration); 02908 02909 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 02910 // This is an extended namespace definition. 02911 // Attach this namespace decl to the chain of extended namespace 02912 // definitions. 02913 OrigNS->setNextNamespace(Namespc); 02914 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 02915 02916 // Remove the previous declaration from the scope. 02917 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 02918 IdResolver.RemoveDecl(OrigNS); 02919 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 02920 } 02921 } else if (PrevDecl) { 02922 // This is an invalid name redefinition. 02923 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 02924 << Namespc->getDeclName(); 02925 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 02926 Namespc->setInvalidDecl(); 02927 // Continue on to push Namespc as current DeclContext and return it. 02928 } else if (II->isStr("std") && 02929 CurContext->getLookupContext()->isTranslationUnit()) { 02930 // This is the first "real" definition of the namespace "std", so update 02931 // our cache of the "std" namespace to point at this definition. 02932 if (StdNamespace) { 02933 // We had already defined a dummy namespace "std". Link this new 02934 // namespace definition to the dummy namespace "std". 02935 StdNamespace->setNextNamespace(Namespc); 02936 StdNamespace->setLocation(IdentLoc); 02937 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 02938 } 02939 02940 // Make our StdNamespace cache point at the first real definition of the 02941 // "std" namespace. 02942 StdNamespace = Namespc; 02943 } 02944 02945 PushOnScopeChains(Namespc, DeclRegionScope); 02946 } else { 02947 // Anonymous namespaces. 02948 assert(Namespc->isAnonymousNamespace()); 02949 CurContext->addDecl(Namespc); 02950 02951 // Link the anonymous namespace into its parent. 02952 NamespaceDecl *PrevDecl; 02953 DeclContext *Parent = CurContext->getLookupContext(); 02954 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 02955 PrevDecl = TU->getAnonymousNamespace(); 02956 TU->setAnonymousNamespace(Namespc); 02957 } else { 02958 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 02959 PrevDecl = ND->getAnonymousNamespace(); 02960 ND->setAnonymousNamespace(Namespc); 02961 } 02962 02963 // Link the anonymous namespace with its previous declaration. 02964 if (PrevDecl) { 02965 assert(PrevDecl->isAnonymousNamespace()); 02966 assert(!PrevDecl->getNextNamespace()); 02967 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 02968 PrevDecl->setNextNamespace(Namespc); 02969 } 02970 02971 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 02972 // behaves as if it were replaced by 02973 // namespace unique { /* empty body */ } 02974 // using namespace unique; 02975 // namespace unique { namespace-body } 02976 // where all occurrences of 'unique' in a translation unit are 02977 // replaced by the same identifier and this identifier differs 02978 // from all other identifiers in the entire program. 02979 02980 // We just create the namespace with an empty name and then add an 02981 // implicit using declaration, just like the standard suggests. 02982 // 02983 // CodeGen enforces the "universally unique" aspect by giving all 02984 // declarations semantically contained within an anonymous 02985 // namespace internal linkage. 02986 02987 if (!PrevDecl) { 02988 UsingDirectiveDecl* UD 02989 = UsingDirectiveDecl::Create(Context, CurContext, 02990 /* 'using' */ LBrace, 02991 /* 'namespace' */ SourceLocation(), 02992 /* qualifier */ SourceRange(), 02993 /* NNS */ NULL, 02994 /* identifier */ SourceLocation(), 02995 Namespc, 02996 /* Ancestor */ CurContext); 02997 UD->setImplicit(); 02998 CurContext->addDecl(UD); 02999 } 03000 } 03001 03002 // Although we could have an invalid decl (i.e. the namespace name is a 03003 // redefinition), push it as current DeclContext and try to continue parsing. 03004 // FIXME: We should be able to push Namespc here, so that the each DeclContext 03005 // for the namespace has the declarations that showed up in that particular 03006 // namespace definition. 03007 PushDeclContext(NamespcScope, Namespc); 03008 return DeclPtrTy::make(Namespc); 03009 } 03010 03011 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 03012 /// is a namespace alias, returns the namespace it points to. 03013 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 03014 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 03015 return AD->getNamespace(); 03016 return dyn_cast_or_null<NamespaceDecl>(D); 03017 } 03018 03019 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 03020 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 03021 void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 03022 Decl *Dcl = D.getAs<Decl>(); 03023 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 03024 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 03025 Namespc->setRBracLoc(RBrace); 03026 PopDeclContext(); 03027 } 03028 03029 Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 03030 SourceLocation UsingLoc, 03031 SourceLocation NamespcLoc, 03032 const CXXScopeSpec &SS, 03033 SourceLocation IdentLoc, 03034 IdentifierInfo *NamespcName, 03035 AttributeList *AttrList) { 03036 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 03037 assert(NamespcName && "Invalid NamespcName."); 03038 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 03039 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 03040 03041 UsingDirectiveDecl *UDir = 0; 03042 03043 // Lookup namespace name. 03044 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 03045 LookupParsedName(R, S, &SS); 03046 if (R.isAmbiguous()) 03047 return DeclPtrTy(); 03048 03049 if (!R.empty()) { 03050 NamedDecl *Named = R.getFoundDecl(); 03051 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 03052 && "expected namespace decl"); 03053 // C++ [namespace.udir]p1: 03054 // A using-directive specifies that the names in the nominated 03055 // namespace can be used in the scope in which the 03056 // using-directive appears after the using-directive. During 03057 // unqualified name lookup (3.4.1), the names appear as if they 03058 // were declared in the nearest enclosing namespace which 03059 // contains both the using-directive and the nominated 03060 // namespace. [Note: in this context, "contains" means "contains 03061 // directly or indirectly". ] 03062 03063 // Find enclosing context containing both using-directive and 03064 // nominated namespace. 03065 NamespaceDecl *NS = getNamespaceDecl(Named); 03066 DeclContext *CommonAncestor = cast<DeclContext>(NS); 03067 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 03068 CommonAncestor = CommonAncestor->getParent(); 03069 03070 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 03071 SS.getRange(), 03072 (NestedNameSpecifier *)SS.getScopeRep(), 03073 IdentLoc, Named, CommonAncestor); 03074 PushUsingDirective(S, UDir); 03075 } else { 03076 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 03077 } 03078 03079 // FIXME: We ignore attributes for now. 03080 delete AttrList; 03081 return DeclPtrTy::make(UDir); 03082 } 03083 03084 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 03085 // If scope has associated entity, then using directive is at namespace 03086 // or translation unit scope. We add UsingDirectiveDecls, into 03087 // it's lookup structure. 03088 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 03089 Ctx->addDecl(UDir); 03090 else 03091 // Otherwise it is block-sope. using-directives will affect lookup 03092 // only to the end of scope. 03093 S->PushUsingDirective(DeclPtrTy::make(UDir)); 03094 } 03095 03096 03097 Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 03098 AccessSpecifier AS, 03099 bool HasUsingKeyword, 03100 SourceLocation UsingLoc, 03101 const CXXScopeSpec &SS, 03102 UnqualifiedId &Name, 03103 AttributeList *AttrList, 03104 bool IsTypeName, 03105 SourceLocation TypenameLoc) { 03106 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 03107 03108 switch (Name.getKind()) { 03109 case UnqualifiedId::IK_Identifier: 03110 case UnqualifiedId::IK_OperatorFunctionId: 03111 case UnqualifiedId::IK_LiteralOperatorId: 03112 case UnqualifiedId::IK_ConversionFunctionId: 03113 break; 03114 03115 case UnqualifiedId::IK_ConstructorName: 03116 case UnqualifiedId::IK_ConstructorTemplateId: 03117 // C++0x inherited constructors. 03118 if (getLangOptions().CPlusPlus0x) break; 03119 03120 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 03121 << SS.getRange(); 03122 return DeclPtrTy(); 03123 03124 case UnqualifiedId::IK_DestructorName: 03125 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 03126 << SS.getRange(); 03127 return DeclPtrTy(); 03128 03129 case UnqualifiedId::IK_TemplateId: 03130 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 03131 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 03132 return DeclPtrTy(); 03133 } 03134 03135 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 03136 if (!TargetName) 03137 return DeclPtrTy(); 03138 03139 // Warn about using declarations. 03140 // TODO: store that the declaration was written without 'using' and 03141 // talk about access decls instead of using decls in the 03142 // diagnostics. 03143 if (!HasUsingKeyword) { 03144 UsingLoc = Name.getSourceRange().getBegin(); 03145 03146 Diag(UsingLoc, diag::warn_access_decl_deprecated) 03147 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(), 03148 "using "); 03149 } 03150 03151 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 03152 Name.getSourceRange().getBegin(), 03153 TargetName, AttrList, 03154 /* IsInstantiation */ false, 03155 IsTypeName, TypenameLoc); 03156 if (UD) 03157 PushOnScopeChains(UD, S, /*AddToContext*/ false); 03158 03159 return DeclPtrTy::make(UD); 03160 } 03161 03162 /// Determines whether to create a using shadow decl for a particular 03163 /// decl, given the set of decls existing prior to this using lookup. 03164 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 03165 const LookupResult &Previous) { 03166 // Diagnose finding a decl which is not from a base class of the 03167 // current class. We do this now because there are cases where this 03168 // function will silently decide not to build a shadow decl, which 03169 // will pre-empt further diagnostics. 03170 // 03171 // We don't need to do this in C++0x because we do the check once on 03172 // the qualifier. 03173 // 03174 // FIXME: diagnose the following if we care enough: 03175 // struct A { int foo; }; 03176 // struct B : A { using A::foo; }; 03177 // template <class T> struct C : A {}; 03178 // template <class T> struct D : C<T> { using B::foo; } // <--- 03179 // This is invalid (during instantiation) in C++03 because B::foo 03180 // resolves to the using decl in B, which is not a base class of D<T>. 03181 // We can't diagnose it immediately because C<T> is an unknown 03182 // specialization. The UsingShadowDecl in D<T> then points directly 03183 // to A::foo, which will look well-formed when we instantiate. 03184 // The right solution is to not collapse the shadow-decl chain. 03185 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 03186 DeclContext *OrigDC = Orig->getDeclContext(); 03187 03188 // Handle enums and anonymous structs. 03189 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 03190 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 03191 while (OrigRec->isAnonymousStructOrUnion()) 03192 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 03193 03194 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 03195 if (OrigDC == CurContext) { 03196 Diag(Using->getLocation(), 03197 diag::err_using_decl_nested_name_specifier_is_current_class) 03198 << Using->getNestedNameRange(); 03199 Diag(Orig->getLocation(), diag::note_using_decl_target); 03200 return true; 03201 } 03202 03203 Diag(Using->getNestedNameRange().getBegin(), 03204 diag::err_using_decl_nested_name_specifier_is_not_base_class) 03205 << Using->getTargetNestedNameDecl() 03206 << cast<CXXRecordDecl>(CurContext) 03207 << Using->getNestedNameRange(); 03208 Diag(Orig->getLocation(), diag::note_using_decl_target); 03209 return true; 03210 } 03211 } 03212 03213 if (Previous.empty()) return false; 03214 03215 NamedDecl *Target = Orig; 03216 if (isa<UsingShadowDecl>(Target)) 03217 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 03218 03219 // If the target happens to be one of the previous declarations, we 03220 // don't have a conflict. 03221 // 03222 // FIXME: but we might be increasing its access, in which case we 03223 // should redeclare it. 03224 NamedDecl *NonTag = 0, *Tag = 0; 03225 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 03226 I != E; ++I) { 03227 NamedDecl *D = (*I)->getUnderlyingDecl(); 03228 if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 03229 return false; 03230 03231 (isa<TagDecl>(D) ? Tag : NonTag) = D; 03232 } 03233 03234 if (Target->isFunctionOrFunctionTemplate()) { 03235 FunctionDecl *FD; 03236 if (isa<FunctionTemplateDecl>(Target)) 03237 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 03238 else 03239 FD = cast<FunctionDecl>(Target); 03240 03241 NamedDecl *OldDecl = 0; 03242 switch (CheckOverload(FD, Previous, OldDecl)) { 03243 case Ovl_Overload: 03244 return false; 03245 03246 case Ovl_NonFunction: 03247 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03248 break; 03249 03250 // We found a decl with the exact signature. 03251 case Ovl_Match: 03252 if (isa<UsingShadowDecl>(OldDecl)) { 03253 // Silently ignore the possible conflict. 03254 return false; 03255 } 03256 03257 // If we're in a record, we want to hide the target, so we 03258 // return true (without a diagnostic) to tell the caller not to 03259 // build a shadow decl. 03260 if (CurContext->isRecord()) 03261 return true; 03262 03263 // If we're not in a record, this is an error. 03264 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03265 break; 03266 } 03267 03268 Diag(Target->getLocation(), diag::note_using_decl_target); 03269 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 03270 return true; 03271 } 03272 03273 // Target is not a function. 03274 03275 if (isa<TagDecl>(Target)) { 03276 // No conflict between a tag and a non-tag. 03277 if (!Tag) return false; 03278 03279 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03280 Diag(Target->getLocation(), diag::note_using_decl_target); 03281 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 03282 return true; 03283 } 03284 03285 // No conflict between a tag and a non-tag. 03286 if (!NonTag) return false; 03287 03288 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03289 Diag(Target->getLocation(), diag::note_using_decl_target); 03290 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 03291 return true; 03292 } 03293 03294 /// Builds a shadow declaration corresponding to a 'using' declaration. 03295 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 03296 UsingDecl *UD, 03297 NamedDecl *Orig) { 03298 03299 // If we resolved to another shadow declaration, just coalesce them. 03300 NamedDecl *Target = Orig; 03301 if (isa<UsingShadowDecl>(Target)) { 03302 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 03303 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 03304 } 03305 03306 UsingShadowDecl *Shadow 03307 = UsingShadowDecl::Create(Context, CurContext, 03308 UD->getLocation(), UD, Target); 03309 UD->addShadowDecl(Shadow); 03310 03311 if (S) 03312 PushOnScopeChains(Shadow, S); 03313 else 03314 CurContext->addDecl(Shadow); 03315 Shadow->setAccess(UD->getAccess()); 03316 03317 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 03318 Shadow->setInvalidDecl(); 03319 03320 return Shadow; 03321 } 03322 03323 /// Hides a using shadow declaration. This is required by the current 03324 /// using-decl implementation when a resolvable using declaration in a 03325 /// class is followed by a declaration which would hide or override 03326 /// one or more of the using decl's targets; for example: 03327 /// 03328 /// struct Base { void foo(int); }; 03329 /// struct Derived : Base { 03330 /// using Base::foo; 03331 /// void foo(int); 03332 /// }; 03333 /// 03334 /// The governing language is C++03 [namespace.udecl]p12: 03335 /// 03336 /// When a using-declaration brings names from a base class into a 03337 /// derived class scope, member functions in the derived class 03338 /// override and/or hide member functions with the same name and 03339 /// parameter types in a base class (rather than conflicting). 03340 /// 03341 /// There are two ways to implement this: 03342 /// (1) optimistically create shadow decls when they're not hidden 03343 /// by existing declarations, or 03344 /// (2) don't create any shadow decls (or at least don't make them 03345 /// visible) until we've fully parsed/instantiated the class. 03346 /// The problem with (1) is that we might have to retroactively remove 03347 /// a shadow decl, which requires several O(n) operations because the 03348 /// decl structures are (very reasonably) not designed for removal. 03349 /// (2) avoids this but is very fiddly and phase-dependent. 03350 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 03351 // Remove it from the DeclContext... 03352 Shadow->getDeclContext()->removeDecl(Shadow); 03353 03354 // ...and the scope, if applicable... 03355 if (S) { 03356 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 03357 IdResolver.RemoveDecl(Shadow); 03358 } 03359 03360 // ...and the using decl. 03361 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 03362 03363 // TODO: complain somehow if Shadow was used. It shouldn't 03364 // be possible for this to happen, because 03365 } 03366 03367 /// Builds a using declaration. 03368 /// 03369 /// \param IsInstantiation - Whether this call arises from an 03370 /// instantiation of an unresolved using declaration. We treat 03371 /// the lookup differently for these declarations. 03372 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 03373 SourceLocation UsingLoc, 03374 const CXXScopeSpec &SS, 03375 SourceLocation IdentLoc, 03376 DeclarationName Name, 03377 AttributeList *AttrList, 03378 bool IsInstantiation, 03379 bool IsTypeName, 03380 SourceLocation TypenameLoc) { 03381 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 03382 assert(IdentLoc.isValid() && "Invalid TargetName location."); 03383 03384 // FIXME: We ignore attributes for now. 03385 delete AttrList; 03386 03387 if (SS.isEmpty()) { 03388 Diag(IdentLoc, diag::err_using_requires_qualname); 03389 return 0; 03390 } 03391 03392 // Do the redeclaration lookup in the current scope. 03393 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 03394 ForRedeclaration); 03395 Previous.setHideTags(false); 03396 if (S) { 03397 LookupName(Previous, S); 03398 03399 // It is really dumb that we have to do this. 03400 LookupResult::Filter F = Previous.makeFilter(); 03401 while (F.hasNext()) { 03402 NamedDecl *D = F.next(); 03403 if (!isDeclInScope(D, CurContext, S)) 03404 F.erase(); 03405 } 03406 F.done(); 03407 } else { 03408 assert(IsInstantiation && "no scope in non-instantiation"); 03409 assert(CurContext->isRecord() && "scope not record in instantiation"); 03410 LookupQualifiedName(Previous, CurContext); 03411 } 03412 03413 NestedNameSpecifier *NNS = 03414 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 03415 03416 // Check for invalid redeclarations. 03417 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 03418 return 0; 03419 03420 // Check for bad qualifiers. 03421 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 03422 return 0; 03423 03424 DeclContext *LookupContext = computeDeclContext(SS); 03425 NamedDecl *D; 03426 if (!LookupContext) { 03427 if (IsTypeName) { 03428 // FIXME: not all declaration name kinds are legal here 03429 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 03430 UsingLoc, TypenameLoc, 03431 SS.getRange(), NNS, 03432 IdentLoc, Name); 03433 } else { 03434 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 03435 UsingLoc, SS.getRange(), NNS, 03436 IdentLoc, Name); 03437 } 03438 } else { 03439 D = UsingDecl::Create(Context, CurContext, IdentLoc, 03440 SS.getRange(), UsingLoc, NNS, Name, 03441 IsTypeName); 03442 } 03443 D->setAccess(AS); 03444 CurContext->addDecl(D); 03445 03446 if (!LookupContext) return D; 03447 UsingDecl *UD = cast<UsingDecl>(D); 03448 03449 if (RequireCompleteDeclContext(SS)) { 03450 UD->setInvalidDecl(); 03451 return UD; 03452 } 03453 03454 // Look up the target name. 03455 03456 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 03457 03458 // Unlike most lookups, we don't always want to hide tag 03459 // declarations: tag names are visible through the using declaration 03460 // even if hidden by ordinary names, *except* in a dependent context 03461 // where it's important for the sanity of two-phase lookup. 03462 if (!IsInstantiation) 03463 R.setHideTags(false); 03464 03465 LookupQualifiedName(R, LookupContext); 03466 03467 if (R.empty()) { 03468 Diag(IdentLoc, diag::err_no_member) 03469 << Name << LookupContext << SS.getRange(); 03470 UD->setInvalidDecl(); 03471 return UD; 03472 } 03473 03474 if (R.isAmbiguous()) { 03475 UD->setInvalidDecl(); 03476 return UD; 03477 } 03478 03479 if (IsTypeName) { 03480 // If we asked for a typename and got a non-type decl, error out. 03481 if (!R.getAsSingle<TypeDecl>()) { 03482 Diag(IdentLoc, diag::err_using_typename_non_type); 03483 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 03484 Diag((*I)->getUnderlyingDecl()->getLocation(), 03485 diag::note_using_decl_target); 03486 UD->setInvalidDecl(); 03487 return UD; 03488 } 03489 } else { 03490 // If we asked for a non-typename and we got a type, error out, 03491 // but only if this is an instantiation of an unresolved using 03492 // decl. Otherwise just silently find the type name. 03493 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 03494 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 03495 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 03496 UD->setInvalidDecl(); 03497 return UD; 03498 } 03499 } 03500 03501 // C++0x N2914 [namespace.udecl]p6: 03502 // A using-declaration shall not name a namespace. 03503 if (R.getAsSingle<NamespaceDecl>()) { 03504 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 03505 << SS.getRange(); 03506 UD->setInvalidDecl(); 03507 return UD; 03508 } 03509 03510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 03511 if (!CheckUsingShadowDecl(UD, *I, Previous)) 03512 BuildUsingShadowDecl(S, UD, *I); 03513 } 03514 03515 return UD; 03516 } 03517 03518 /// Checks that the given using declaration is not an invalid 03519 /// redeclaration. Note that this is checking only for the using decl 03520 /// itself, not for any ill-formedness among the UsingShadowDecls. 03521 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 03522 bool isTypeName, 03523 const CXXScopeSpec &SS, 03524 SourceLocation NameLoc, 03525 const LookupResult &Prev) { 03526 // C++03 [namespace.udecl]p8: 03527 // C++0x [namespace.udecl]p10: 03528 // A using-declaration is a declaration and can therefore be used 03529 // repeatedly where (and only where) multiple declarations are 03530 // allowed. 03531 // That's only in file contexts. 03532 if (CurContext->getLookupContext()->isFileContext()) 03533 return false; 03534 03535 NestedNameSpecifier *Qual 03536 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 03537 03538 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 03539 NamedDecl *D = *I; 03540 03541 bool DTypename; 03542 NestedNameSpecifier *DQual; 03543 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 03544 DTypename = UD->isTypeName(); 03545 DQual = UD->getTargetNestedNameDecl(); 03546 } else if (UnresolvedUsingValueDecl *UD 03547 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 03548 DTypename = false; 03549 DQual = UD->getTargetNestedNameSpecifier(); 03550 } else if (UnresolvedUsingTypenameDecl *UD 03551 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 03552 DTypename = true; 03553 DQual = UD->getTargetNestedNameSpecifier(); 03554 } else continue; 03555 03556 // using decls differ if one says 'typename' and the other doesn't. 03557 // FIXME: non-dependent using decls? 03558 if (isTypeName != DTypename) continue; 03559 03560 // using decls differ if they name different scopes (but note that 03561 // template instantiation can cause this check to trigger when it 03562 // didn't before instantiation). 03563 if (Context.getCanonicalNestedNameSpecifier(Qual) != 03564 Context.getCanonicalNestedNameSpecifier(DQual)) 03565 continue; 03566 03567 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 03568 Diag(D->getLocation(), diag::note_using_decl) << 1; 03569 return true; 03570 } 03571 03572 return false; 03573 } 03574 03575 03576 /// Checks that the given nested-name qualifier used in a using decl 03577 /// in the current context is appropriately related to the current 03578 /// scope. If an error is found, diagnoses it and returns true. 03579 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 03580 const CXXScopeSpec &SS, 03581 SourceLocation NameLoc) { 03582 DeclContext *NamedContext = computeDeclContext(SS); 03583 03584 if (!CurContext->isRecord()) { 03585 // C++03 [namespace.udecl]p3: 03586 // C++0x [namespace.udecl]p8: 03587 // A using-declaration for a class member shall be a member-declaration. 03588 03589 // If we weren't able to compute a valid scope, it must be a 03590 // dependent class scope. 03591 if (!NamedContext || NamedContext->isRecord()) { 03592 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 03593 << SS.getRange(); 03594 return true; 03595 } 03596 03597 // Otherwise, everything is known to be fine. 03598 return false; 03599 } 03600 03601 // The current scope is a record. 03602 03603 // If the named context is dependent, we can't decide much. 03604 if (!NamedContext) { 03605 // FIXME: in C++0x, we can diagnose if we can prove that the 03606 // nested-name-specifier does not refer to a base class, which is 03607 // still possible in some cases. 03608 03609 // Otherwise we have to conservatively report that things might be 03610 // okay. 03611 return false; 03612 } 03613 03614 if (!NamedContext->isRecord()) { 03615 // Ideally this would point at the last name in the specifier, 03616 // but we don't have that level of source info. 03617 Diag(SS.getRange().getBegin(), 03618 diag::err_using_decl_nested_name_specifier_is_not_class) 03619 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 03620 return true; 03621 } 03622 03623 if (getLangOptions().CPlusPlus0x) { 03624 // C++0x [namespace.udecl]p3: 03625 // In a using-declaration used as a member-declaration, the 03626 // nested-name-specifier shall name a base class of the class 03627 // being defined. 03628 03629 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 03630 cast<CXXRecordDecl>(NamedContext))) { 03631 if (CurContext == NamedContext) { 03632 Diag(NameLoc, 03633 diag::err_using_decl_nested_name_specifier_is_current_class) 03634 << SS.getRange(); 03635 return true; 03636 } 03637 03638 Diag(SS.getRange().getBegin(), 03639 diag::err_using_decl_nested_name_specifier_is_not_base_class) 03640 << (NestedNameSpecifier*) SS.getScopeRep() 03641 << cast<CXXRecordDecl>(CurContext) 03642 << SS.getRange(); 03643 return true; 03644 } 03645 03646 return false; 03647 } 03648 03649 // C++03 [namespace.udecl]p4: 03650 // A using-declaration used as a member-declaration shall refer 03651 // to a member of a base class of the class being defined [etc.]. 03652 03653 // Salient point: SS doesn't have to name a base class as long as 03654 // lookup only finds members from base classes. Therefore we can 03655 // diagnose here only if we can prove that that can't happen, 03656 // i.e. if the class hierarchies provably don't intersect. 03657 03658 // TODO: it would be nice if "definitely valid" results were cached 03659 // in the UsingDecl and UsingShadowDecl so that these checks didn't 03660 // need to be repeated. 03661 03662 struct UserData { 03663 llvm::DenseSet<const CXXRecordDecl*> Bases; 03664 03665 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 03666 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 03667 Data->Bases.insert(Base); 03668 return true; 03669 } 03670 03671 bool hasDependentBases(const CXXRecordDecl *Class) { 03672 return !Class->forallBases(collect, this); 03673 } 03674 03675 /// Returns true if the base is dependent or is one of the 03676 /// accumulated base classes. 03677 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 03678 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 03679 return !Data->Bases.count(Base); 03680 } 03681 03682 bool mightShareBases(const CXXRecordDecl *Class) { 03683 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 03684 } 03685 }; 03686 03687 UserData Data; 03688 03689 // Returns false if we find a dependent base. 03690 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 03691 return false; 03692 03693 // Returns false if the class has a dependent base or if it or one 03694 // of its bases is present in the base set of the current context. 03695 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 03696 return false; 03697 03698 Diag(SS.getRange().getBegin(), 03699 diag::err_using_decl_nested_name_specifier_is_not_base_class) 03700 << (NestedNameSpecifier*) SS.getScopeRep() 03701 << cast<CXXRecordDecl>(CurContext) 03702 << SS.getRange(); 03703 03704 return true; 03705 } 03706 03707 Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 03708 SourceLocation NamespaceLoc, 03709 SourceLocation AliasLoc, 03710 IdentifierInfo *Alias, 03711 const CXXScopeSpec &SS, 03712 SourceLocation IdentLoc, 03713 IdentifierInfo *Ident) { 03714 03715 // Lookup the namespace name. 03716 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 03717 LookupParsedName(R, S, &SS); 03718 03719 // Check if we have a previous declaration with the same name. 03720 if (NamedDecl *PrevDecl 03721 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) { 03722 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 03723 // We already have an alias with the same name that points to the same 03724 // namespace, so don't create a new one. 03725 if (!R.isAmbiguous() && !R.empty() && 03726 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl())) 03727 return DeclPtrTy(); 03728 } 03729 03730 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 03731 diag::err_redefinition_different_kind; 03732 Diag(AliasLoc, DiagID) << Alias; 03733 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 03734 return DeclPtrTy(); 03735 } 03736 03737 if (R.isAmbiguous()) 03738 return DeclPtrTy(); 03739 03740 if (R.empty()) { 03741 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 03742 return DeclPtrTy(); 03743 } 03744 03745 NamespaceAliasDecl *AliasDecl = 03746 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 03747 Alias, SS.getRange(), 03748 (NestedNameSpecifier *)SS.getScopeRep(), 03749 IdentLoc, R.getFoundDecl()); 03750 03751 PushOnScopeChains(AliasDecl, S); 03752 return DeclPtrTy::make(AliasDecl); 03753 } 03754 03755 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 03756 CXXConstructorDecl *Constructor) { 03757 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 03758 !Constructor->isUsed()) && 03759 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 03760 03761 CXXRecordDecl *ClassDecl 03762 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 03763 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 03764 03765 DeclContext *PreviousContext = CurContext; 03766 CurContext = Constructor; 03767 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) { 03768 Diag(CurrentLocation, diag::note_member_synthesized_at) 03769 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 03770 Constructor->setInvalidDecl(); 03771 } else { 03772 Constructor->setUsed(); 03773 } 03774 CurContext = PreviousContext; 03775 } 03776 03777 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 03778 CXXDestructorDecl *Destructor) { 03779 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 03780 "DefineImplicitDestructor - call it for implicit default dtor"); 03781 CXXRecordDecl *ClassDecl = Destructor->getParent(); 03782 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 03783 03784 DeclContext *PreviousContext = CurContext; 03785 CurContext = Destructor; 03786 03787 // C++ [class.dtor] p5 03788 // Before the implicitly-declared default destructor for a class is 03789 // implicitly defined, all the implicitly-declared default destructors 03790 // for its base class and its non-static data members shall have been 03791 // implicitly defined. 03792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 03793 E = ClassDecl->bases_end(); Base != E; ++Base) { 03794 CXXRecordDecl *BaseClassDecl 03795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 03796 if (!BaseClassDecl->hasTrivialDestructor()) { 03797 if (CXXDestructorDecl *BaseDtor = 03798 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 03799 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 03800 else 03801 assert(false && 03802 "DefineImplicitDestructor - missing dtor in a base class"); 03803 } 03804 } 03805 03806 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 03807 E = ClassDecl->field_end(); Field != E; ++Field) { 03808 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 03809 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 03810 FieldType = Array->getElementType(); 03811 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 03812 CXXRecordDecl *FieldClassDecl 03813 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 03814 if (!FieldClassDecl->hasTrivialDestructor()) { 03815 if (CXXDestructorDecl *FieldDtor = 03816 const_cast<CXXDestructorDecl*>( 03817 FieldClassDecl->getDestructor(Context))) 03818 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 03819 else 03820 assert(false && 03821 "DefineImplicitDestructor - missing dtor in class of a data member"); 03822 } 03823 } 03824 } 03825 03826 // FIXME: If CheckDestructor fails, we should emit a note about where the 03827 // implicit destructor was needed. 03828 if (CheckDestructor(Destructor)) { 03829 Diag(CurrentLocation, diag::note_member_synthesized_at) 03830 << CXXDestructor << Context.getTagDeclType(ClassDecl); 03831 03832 Destructor->setInvalidDecl(); 03833 CurContext = PreviousContext; 03834 03835 return; 03836 } 03837 CurContext = PreviousContext; 03838 03839 Destructor->setUsed(); 03840 } 03841 03842 void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 03843 CXXMethodDecl *MethodDecl) { 03844 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 03845 MethodDecl->getOverloadedOperator() == OO_Equal && 03846 !MethodDecl->isUsed()) && 03847 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 03848 03849 CXXRecordDecl *ClassDecl 03850 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 03851 03852 DeclContext *PreviousContext = CurContext; 03853 CurContext = MethodDecl; 03854 03855 // C++[class.copy] p12 03856 // Before the implicitly-declared copy assignment operator for a class is 03857 // implicitly defined, all implicitly-declared copy assignment operators 03858 // for its direct base classes and its nonstatic data members shall have 03859 // been implicitly defined. 03860 bool err = false; 03861 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 03862 E = ClassDecl->bases_end(); Base != E; ++Base) { 03863 CXXRecordDecl *BaseClassDecl 03864 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 03865 if (CXXMethodDecl *BaseAssignOpMethod = 03866 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 03867 BaseClassDecl)) 03868 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 03869 } 03870 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 03871 E = ClassDecl->field_end(); Field != E; ++Field) { 03872 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 03873 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 03874 FieldType = Array->getElementType(); 03875 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 03876 CXXRecordDecl *FieldClassDecl 03877 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 03878 if (CXXMethodDecl *FieldAssignOpMethod = 03879 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 03880 FieldClassDecl)) 03881 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 03882 } else if (FieldType->isReferenceType()) { 03883 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 03884 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 03885 Diag(Field->getLocation(), diag::note_declared_at); 03886 Diag(CurrentLocation, diag::note_first_required_here); 03887 err = true; 03888 } else if (FieldType.isConstQualified()) { 03889 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 03890 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 03891 Diag(Field->getLocation(), diag::note_declared_at); 03892 Diag(CurrentLocation, diag::note_first_required_here); 03893 err = true; 03894 } 03895 } 03896 if (!err) 03897 MethodDecl->setUsed(); 03898 03899 CurContext = PreviousContext; 03900 } 03901 03902 CXXMethodDecl * 03903 Sema::getAssignOperatorMethod(SourceLocation CurrentLocation, 03904 ParmVarDecl *ParmDecl, 03905 CXXRecordDecl *ClassDecl) { 03906 QualType LHSType = Context.getTypeDeclType(ClassDecl); 03907 QualType RHSType(LHSType); 03908 // If class's assignment operator argument is const/volatile qualified, 03909 // look for operator = (const/volatile B&). Otherwise, look for 03910 // operator = (B&). 03911 RHSType = Context.getCVRQualifiedType(RHSType, 03912 ParmDecl->getType().getCVRQualifiers()); 03913 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 03914 LHSType, 03915 SourceLocation())); 03916 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 03917 RHSType, 03918 CurrentLocation)); 03919 Expr *Args[2] = { &*LHS, &*RHS }; 03920 OverloadCandidateSet CandidateSet(CurrentLocation); 03921 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 03922 CandidateSet); 03923 OverloadCandidateSet::iterator Best; 03924 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success) 03925 return cast<CXXMethodDecl>(Best->Function); 03926 assert(false && 03927 "getAssignOperatorMethod - copy assignment operator method not found"); 03928 return 0; 03929 } 03930 03931 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 03932 CXXConstructorDecl *CopyConstructor, 03933 unsigned TypeQuals) { 03934 assert((CopyConstructor->isImplicit() && 03935 CopyConstructor->isCopyConstructor(TypeQuals) && 03936 !CopyConstructor->isUsed()) && 03937 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 03938 03939 CXXRecordDecl *ClassDecl 03940 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 03941 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 03942 03943 DeclContext *PreviousContext = CurContext; 03944 CurContext = CopyConstructor; 03945 03946 // C++ [class.copy] p209 03947 // Before the implicitly-declared copy constructor for a class is 03948 // implicitly defined, all the implicitly-declared copy constructors 03949 // for its base class and its non-static data members shall have been 03950 // implicitly defined. 03951 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 03952 Base != ClassDecl->bases_end(); ++Base) { 03953 CXXRecordDecl *BaseClassDecl 03954 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 03955 if (CXXConstructorDecl *BaseCopyCtor = 03956 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 03957 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 03958 } 03959 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 03960 FieldEnd = ClassDecl->field_end(); 03961 Field != FieldEnd; ++Field) { 03962 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 03963 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 03964 FieldType = Array->getElementType(); 03965 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 03966 CXXRecordDecl *FieldClassDecl 03967 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 03968 if (CXXConstructorDecl *FieldCopyCtor = 03969 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 03970 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 03971 } 03972 } 03973 CopyConstructor->setUsed(); 03974 03975 CurContext = PreviousContext; 03976 } 03977 03978 Sema::OwningExprResult 03979 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 03980 CXXConstructorDecl *Constructor, 03981 MultiExprArg ExprArgs, 03982 bool RequiresZeroInit, 03983 bool BaseInitialization) { 03984 bool Elidable = false; 03985 03986 // C++ [class.copy]p15: 03987 // Whenever a temporary class object is copied using a copy constructor, and 03988 // this object and the copy have the same cv-unqualified type, an 03989 // implementation is permitted to treat the original and the copy as two 03990 // different ways of referring to the same object and not perform a copy at 03991 // all, even if the class copy constructor or destructor have side effects. 03992 03993 // FIXME: Is this enough? 03994 if (Constructor->isCopyConstructor()) { 03995 Expr *E = ((Expr **)ExprArgs.get())[0]; 03996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 03997 if (ICE->getCastKind() == CastExpr::CK_NoOp) 03998 E = ICE->getSubExpr(); 03999 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E)) 04000 E = FCE->getSubExpr(); 04001 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 04002 E = BE->getSubExpr(); 04003 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 04004 if (ICE->getCastKind() == CastExpr::CK_NoOp) 04005 E = ICE->getSubExpr(); 04006 04007 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 04008 Elidable = !CE->getCallReturnType()->isReferenceType(); 04009 else if (isa<CXXTemporaryObjectExpr>(E)) 04010 Elidable = true; 04011 else if (isa<CXXConstructExpr>(E)) 04012 Elidable = true; 04013 } 04014 04015 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 04016 Elidable, move(ExprArgs), RequiresZeroInit, 04017 BaseInitialization); 04018 } 04019 04020 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 04021 /// including handling of its default argument expressions. 04022 Sema::OwningExprResult 04023 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 04024 CXXConstructorDecl *Constructor, bool Elidable, 04025 MultiExprArg ExprArgs, 04026 bool RequiresZeroInit, 04027 bool BaseInitialization) { 04028 unsigned NumExprs = ExprArgs.size(); 04029 Expr **Exprs = (Expr **)ExprArgs.release(); 04030 04031 MarkDeclarationReferenced(ConstructLoc, Constructor); 04032 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 04033 Constructor, Elidable, Exprs, NumExprs, 04034 RequiresZeroInit, BaseInitialization)); 04035 } 04036 04037 bool Sema::InitializeVarWithConstructor(VarDecl *VD, 04038 CXXConstructorDecl *Constructor, 04039 MultiExprArg Exprs) { 04040 OwningExprResult TempResult = 04041 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 04042 move(Exprs)); 04043 if (TempResult.isInvalid()) 04044 return true; 04045 04046 Expr *Temp = TempResult.takeAs<Expr>(); 04047 MarkDeclarationReferenced(VD->getLocation(), Constructor); 04048 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 04049 VD->setInit(Temp); 04050 04051 return false; 04052 } 04053 04054 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 04055 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 04056 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 04057 !ClassDecl->hasTrivialDestructor()) { 04058 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context); 04059 MarkDeclarationReferenced(VD->getLocation(), Destructor); 04060 CheckDestructorAccess(VD->getLocation(), Record); 04061 } 04062 } 04063 04064 /// AddCXXDirectInitializerToDecl - This action is called immediately after 04065 /// ActOnDeclarator, when a C++ direct initializer is present. 04066 /// e.g: "int x(1);" 04067 void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 04068 SourceLocation LParenLoc, 04069 MultiExprArg Exprs, 04070 SourceLocation *CommaLocs, 04071 SourceLocation RParenLoc) { 04072 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 04073 Decl *RealDecl = Dcl.getAs<Decl>(); 04074 04075 // If there is no declaration, there was an error parsing it. Just ignore 04076 // the initializer. 04077 if (RealDecl == 0) 04078 return; 04079 04080 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 04081 if (!VDecl) { 04082 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 04083 RealDecl->setInvalidDecl(); 04084 return; 04085 } 04086 04087 // We will represent direct-initialization similarly to copy-initialization: 04088 // int x(1); -as-> int x = 1; 04089 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 04090 // 04091 // Clients that want to distinguish between the two forms, can check for 04092 // direct initializer using VarDecl::hasCXXDirectInitializer(). 04093 // A major benefit is that clients that don't particularly care about which 04094 // exactly form was it (like the CodeGen) can handle both cases without 04095 // special case code. 04096 04097 // C++ 8.5p11: 04098 // The form of initialization (using parentheses or '=') is generally 04099 // insignificant, but does matter when the entity being initialized has a 04100 // class type. 04101 QualType DeclInitType = VDecl->getType(); 04102 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 04103 DeclInitType = Context.getBaseElementType(Array); 04104 04105 if (!VDecl->getType()->isDependentType() && 04106 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 04107 diag::err_typecheck_decl_incomplete_type)) { 04108 VDecl->setInvalidDecl(); 04109 return; 04110 } 04111 04112 // The variable can not have an abstract class type. 04113 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 04114 diag::err_abstract_type_in_decl, 04115 AbstractVariableType)) 04116 VDecl->setInvalidDecl(); 04117 04118 const VarDecl *Def; 04119 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 04120 Diag(VDecl->getLocation(), diag::err_redefinition) 04121 << VDecl->getDeclName(); 04122 Diag(Def->getLocation(), diag::note_previous_definition); 04123 VDecl->setInvalidDecl(); 04124 return; 04125 } 04126 04127 // If either the declaration has a dependent type or if any of the 04128 // expressions is type-dependent, we represent the initialization 04129 // via a ParenListExpr for later use during template instantiation. 04130 if (VDecl->getType()->isDependentType() || 04131 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 04132 // Let clients know that initialization was done with a direct initializer. 04133 VDecl->setCXXDirectInitializer(true); 04134 04135 // Store the initialization expressions as a ParenListExpr. 04136 unsigned NumExprs = Exprs.size(); 04137 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 04138 (Expr **)Exprs.release(), 04139 NumExprs, RParenLoc)); 04140 return; 04141 } 04142 04143 // Capture the variable that is being initialized and the style of 04144 // initialization. 04145 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 04146 04147 // FIXME: Poor source location information. 04148 InitializationKind Kind 04149 = InitializationKind::CreateDirect(VDecl->getLocation(), 04150 LParenLoc, RParenLoc); 04151 04152 InitializationSequence InitSeq(*this, Entity, Kind, 04153 (Expr**)Exprs.get(), Exprs.size()); 04154 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 04155 if (Result.isInvalid()) { 04156 VDecl->setInvalidDecl(); 04157 return; 04158 } 04159 04160 Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 04161 VDecl->setInit(Result.takeAs<Expr>()); 04162 VDecl->setCXXDirectInitializer(true); 04163 04164 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 04165 FinalizeVarWithDestructor(VDecl, Record); 04166 } 04167 04168 /// \brief Add the applicable constructor candidates for an initialization 04169 /// by constructor. 04170 static void AddConstructorInitializationCandidates(Sema &SemaRef, 04171 QualType ClassType, 04172 Expr **Args, 04173 unsigned NumArgs, 04174 InitializationKind Kind, 04175 OverloadCandidateSet &CandidateSet) { 04176 // C++ [dcl.init]p14: 04177 // If the initialization is direct-initialization, or if it is 04178 // copy-initialization where the cv-unqualified version of the 04179 // source type is the same class as, or a derived class of, the 04180 // class of the destination, constructors are considered. The 04181 // applicable constructors are enumerated (13.3.1.3), and the 04182 // best one is chosen through overload resolution (13.3). The 04183 // constructor so selected is called to initialize the object, 04184 // with the initializer expression(s) as its argument(s). If no 04185 // constructor applies, or the overload resolution is ambiguous, 04186 // the initialization is ill-formed. 04187 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 04188 assert(ClassRec && "Can only initialize a class type here"); 04189 04190 // FIXME: When we decide not to synthesize the implicitly-declared 04191 // constructors, we'll need to make them appear here. 04192 04193 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 04194 DeclarationName ConstructorName 04195 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 04196 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType()); 04197 DeclContext::lookup_const_iterator Con, ConEnd; 04198 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 04199 Con != ConEnd; ++Con) { 04200 // Find the constructor (which may be a template). 04201 CXXConstructorDecl *Constructor = 0; 04202 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 04203 if (ConstructorTmpl) 04204 Constructor 04205 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 04206 else 04207 Constructor = cast<CXXConstructorDecl>(*Con); 04208 04209 if ((Kind.getKind() == InitializationKind::IK_Direct) || 04210 (Kind.getKind() == InitializationKind::IK_Value) || 04211 (Kind.getKind() == InitializationKind::IK_Copy && 04212 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 04213 ((Kind.getKind() == InitializationKind::IK_Default) && 04214 Constructor->isDefaultConstructor())) { 04215 if (ConstructorTmpl) 04216 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, 04217 ConstructorTmpl->getAccess(), 04218 /*ExplicitArgs*/ 0, 04219 Args, NumArgs, CandidateSet); 04220 else 04221 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(), 04222 Args, NumArgs, CandidateSet); 04223 } 04224 } 04225 } 04226 04227 /// \brief Attempt to perform initialization by constructor 04228 /// (C++ [dcl.init]p14), which may occur as part of direct-initialization or 04229 /// copy-initialization. 04230 /// 04231 /// This routine determines whether initialization by constructor is possible, 04232 /// but it does not emit any diagnostics in the case where the initialization 04233 /// is ill-formed. 04234 /// 04235 /// \param ClassType the type of the object being initialized, which must have 04236 /// class type. 04237 /// 04238 /// \param Args the arguments provided to initialize the object 04239 /// 04240 /// \param NumArgs the number of arguments provided to initialize the object 04241 /// 04242 /// \param Kind the type of initialization being performed 04243 /// 04244 /// \returns the constructor used to initialize the object, if successful. 04245 /// Otherwise, emits a diagnostic and returns NULL. 04246 CXXConstructorDecl * 04247 Sema::TryInitializationByConstructor(QualType ClassType, 04248 Expr **Args, unsigned NumArgs, 04249 SourceLocation Loc, 04250 InitializationKind Kind) { 04251 // Build the overload candidate set 04252 OverloadCandidateSet CandidateSet(Loc); 04253 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 04254 CandidateSet); 04255 04256 // Determine whether we found a constructor we can use. 04257 OverloadCandidateSet::iterator Best; 04258 switch (BestViableFunction(CandidateSet, Loc, Best)) { 04259 case OR_Success: 04260 case OR_Deleted: 04261 // We found a constructor. Return it. 04262 return cast<CXXConstructorDecl>(Best->Function); 04263 04264 case OR_No_Viable_Function: 04265 case OR_Ambiguous: 04266 // Overload resolution failed. Return nothing. 04267 return 0; 04268 } 04269 04270 // Silence GCC warning 04271 return 0; 04272 } 04273 04274 /// \brief Given a constructor and the set of arguments provided for the 04275 /// constructor, convert the arguments and add any required default arguments 04276 /// to form a proper call to this constructor. 04277 /// 04278 /// \returns true if an error occurred, false otherwise. 04279 bool 04280 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 04281 MultiExprArg ArgsPtr, 04282 SourceLocation Loc, 04283 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 04284 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 04285 unsigned NumArgs = ArgsPtr.size(); 04286 Expr **Args = (Expr **)ArgsPtr.get(); 04287 04288 const FunctionProtoType *Proto 04289 = Constructor->getType()->getAs<FunctionProtoType>(); 04290 assert(Proto && "Constructor without a prototype?"); 04291 unsigned NumArgsInProto = Proto->getNumArgs(); 04292 04293 // If too few arguments are available, we'll fill in the rest with defaults. 04294 if (NumArgs < NumArgsInProto) 04295 ConvertedArgs.reserve(NumArgsInProto); 04296 else 04297 ConvertedArgs.reserve(NumArgs); 04298 04299 VariadicCallType CallType = 04300 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 04301 llvm::SmallVector<Expr *, 8> AllArgs; 04302 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 04303 Proto, 0, Args, NumArgs, AllArgs, 04304 CallType); 04305 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 04306 ConvertedArgs.push_back(AllArgs[i]); 04307 return Invalid; 04308 } 04309 04310 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 04311 /// determine whether they are reference-related, 04312 /// reference-compatible, reference-compatible with added 04313 /// qualification, or incompatible, for use in C++ initialization by 04314 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 04315 /// type, and the first type (T1) is the pointee type of the reference 04316 /// type being initialized. 04317 Sema::ReferenceCompareResult 04318 Sema::CompareReferenceRelationship(SourceLocation Loc, 04319 QualType OrigT1, QualType OrigT2, 04320 bool& DerivedToBase) { 04321 assert(!OrigT1->isReferenceType() && 04322 "T1 must be the pointee type of the reference type"); 04323 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 04324 04325 QualType T1 = Context.getCanonicalType(OrigT1); 04326 QualType T2 = Context.getCanonicalType(OrigT2); 04327 Qualifiers T1Quals, T2Quals; 04328 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 04329 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 04330 04331 // C++ [dcl.init.ref]p4: 04332 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 04333 // reference-related to "cv2 T2" if T1 is the same type as T2, or 04334 // T1 is a base class of T2. 04335 if (UnqualT1 == UnqualT2) 04336 DerivedToBase = false; 04337 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) && 04338 !RequireCompleteType(Loc, OrigT2, PDiag()) && 04339 IsDerivedFrom(UnqualT2, UnqualT1)) 04340 DerivedToBase = true; 04341 else 04342 return Ref_Incompatible; 04343 04344 // At this point, we know that T1 and T2 are reference-related (at 04345 // least). 04346 04347 // If the type is an array type, promote the element qualifiers to the type 04348 // for comparison. 04349 if (isa<ArrayType>(T1) && T1Quals) 04350 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 04351 if (isa<ArrayType>(T2) && T2Quals) 04352 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 04353 04354 // C++ [dcl.init.ref]p4: 04355 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 04356 // reference-related to T2 and cv1 is the same cv-qualification 04357 // as, or greater cv-qualification than, cv2. For purposes of 04358 // overload resolution, cases for which cv1 is greater 04359 // cv-qualification than cv2 are identified as 04360 // reference-compatible with added qualification (see 13.3.3.2). 04361 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers()) 04362 return Ref_Compatible; 04363 else if (T1.isMoreQualifiedThan(T2)) 04364 return Ref_Compatible_With_Added_Qualification; 04365 else 04366 return Ref_Related; 04367 } 04368 04369 /// CheckReferenceInit - Check the initialization of a reference 04370 /// variable with the given initializer (C++ [dcl.init.ref]). Init is 04371 /// the initializer (either a simple initializer or an initializer 04372 /// list), and DeclType is the type of the declaration. When ICS is 04373 /// non-null, this routine will compute the implicit conversion 04374 /// sequence according to C++ [over.ics.ref] and will not produce any 04375 /// diagnostics; when ICS is null, it will emit diagnostics when any 04376 /// errors are found. Either way, a return value of true indicates 04377 /// that there was a failure, a return value of false indicates that 04378 /// the reference initialization succeeded. 04379 /// 04380 /// When @p SuppressUserConversions, user-defined conversions are 04381 /// suppressed. 04382 /// When @p AllowExplicit, we also permit explicit user-defined 04383 /// conversion functions. 04384 /// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 04385 /// When @p IgnoreBaseAccess, we don't do access control on to-base conversion. 04386 /// This is used when this is called from a C-style cast. 04387 bool 04388 Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 04389 SourceLocation DeclLoc, 04390 bool SuppressUserConversions, 04391 bool AllowExplicit, bool ForceRValue, 04392 ImplicitConversionSequence *ICS, 04393 bool IgnoreBaseAccess) { 04394 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 04395 04396 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 04397 QualType T2 = Init->getType(); 04398 04399 // If the initializer is the address of an overloaded function, try 04400 // to resolve the overloaded function. If all goes well, T2 is the 04401 // type of the resulting function. 04402 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 04403 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 04404 ICS != 0); 04405 if (Fn) { 04406 // Since we're performing this reference-initialization for 04407 // real, update the initializer with the resulting function. 04408 if (!ICS) { 04409 if (DiagnoseUseOfDecl(Fn, DeclLoc)) 04410 return true; 04411 04412 Init = FixOverloadedFunctionReference(Init, Fn); 04413 } 04414 04415 T2 = Fn->getType(); 04416 } 04417 } 04418 04419 // Compute some basic properties of the types and the initializer. 04420 bool isRValRef = DeclType->isRValueReferenceType(); 04421 bool DerivedToBase = false; 04422 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 04423 Init->isLvalue(Context); 04424 ReferenceCompareResult RefRelationship 04425 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase); 04426 04427 // Most paths end in a failed conversion. 04428 if (ICS) { 04429 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType); 04430 } 04431 04432 // C++ [dcl.init.ref]p5: 04433 // A reference to type "cv1 T1" is initialized by an expression 04434 // of type "cv2 T2" as follows: 04435 04436 // -- If the initializer expression 04437 04438 // Rvalue references cannot bind to lvalues (N2812). 04439 // There is absolutely no situation where they can. In particular, note that 04440 // this is ill-formed, even if B has a user-defined conversion to A&&: 04441 // B b; 04442 // A&& r = b; 04443 if (isRValRef && InitLvalue == Expr::LV_Valid) { 04444 if (!ICS) 04445 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 04446 << Init->getSourceRange(); 04447 return true; 04448 } 04449 04450 bool BindsDirectly = false; 04451 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 04452 // reference-compatible with "cv2 T2," or 04453 // 04454 // Note that the bit-field check is skipped if we are just computing 04455 // the implicit conversion sequence (C++ [over.best.ics]p2). 04456 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 04457 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 04458 BindsDirectly = true; 04459 04460 if (ICS) { 04461 // C++ [over.ics.ref]p1: 04462 // When a parameter of reference type binds directly (8.5.3) 04463 // to an argument expression, the implicit conversion sequence 04464 // is the identity conversion, unless the argument expression 04465 // has a type that is a derived class of the parameter type, 04466 // in which case the implicit conversion sequence is a 04467 // derived-to-base Conversion (13.3.3.1). 04468 ICS->setStandard(); 04469 ICS->Standard.First = ICK_Identity; 04470 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 04471 ICS->Standard.Third = ICK_Identity; 04472 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 04473 ICS->Standard.setToType(0, T2); 04474 ICS->Standard.setToType(1, T1); 04475 ICS->Standard.setToType(2, T1); 04476 ICS->Standard.ReferenceBinding = true; 04477 ICS->Standard.DirectBinding = true; 04478 ICS->Standard.RRefBinding = false; 04479 ICS->Standard.CopyConstructor = 0; 04480 04481 // Nothing more to do: the inaccessibility/ambiguity check for 04482 // derived-to-base conversions is suppressed when we're 04483 // computing the implicit conversion sequence (C++ 04484 // [over.best.ics]p2). 04485 return false; 04486 } else { 04487 // Perform the conversion. 04488 CastExpr::CastKind CK = CastExpr::CK_NoOp; 04489 if (DerivedToBase) 04490 CK = CastExpr::CK_DerivedToBase; 04491 else if(CheckExceptionSpecCompatibility(Init, T1)) 04492 return true; 04493 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 04494 } 04495 } 04496 04497 // -- has a class type (i.e., T2 is a class type) and can be 04498 // implicitly converted to an lvalue of type "cv3 T3," 04499 // where "cv1 T1" is reference-compatible with "cv3 T3" 04500 // 92) (this conversion is selected by enumerating the 04501 // applicable conversion functions (13.3.1.6) and choosing 04502 // the best one through overload resolution (13.3)), 04503 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 04504 !RequireCompleteType(DeclLoc, T2, 0)) { 04505 CXXRecordDecl *T2RecordDecl 04506 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 04507 04508 OverloadCandidateSet CandidateSet(DeclLoc); 04509 const UnresolvedSetImpl *Conversions 04510 = T2RecordDecl->getVisibleConversionFunctions(); 04511 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 04512 E = Conversions->end(); I != E; ++I) { 04513 NamedDecl *D = *I; 04514 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 04515 if (isa<UsingShadowDecl>(D)) 04516 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 04517 04518 FunctionTemplateDecl *ConvTemplate 04519 = dyn_cast<FunctionTemplateDecl>(D); 04520 CXXConversionDecl *Conv; 04521 if (ConvTemplate) 04522 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 04523 else 04524 Conv = cast<CXXConversionDecl>(D); 04525 04526 // If the conversion function doesn't return a reference type, 04527 // it can't be considered for this conversion. 04528 if (Conv->getConversionType()->isLValueReferenceType() && 04529 (AllowExplicit || !Conv->isExplicit())) { 04530 if (ConvTemplate) 04531 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC, 04532 Init, DeclType, CandidateSet); 04533 else 04534 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init, 04535 DeclType, CandidateSet); 04536 } 04537 } 04538 04539 OverloadCandidateSet::iterator Best; 04540 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) { 04541 case OR_Success: 04542 // C++ [over.ics.ref]p1: 04543 // 04544 // [...] If the parameter binds directly to the result of 04545 // applying a conversion function to the argument 04546 // expression, the implicit conversion sequence is a 04547 // user-defined conversion sequence (13.3.3.1.2), with the 04548 // second standard conversion sequence either an identity 04549 // conversion or, if the conversion function returns an 04550 // entity of a type that is a derived class of the parameter 04551 // type, a derived-to-base Conversion. 04552 if (!Best->FinalConversion.DirectBinding) 04553 break; 04554 04555 // This is a direct binding. 04556 BindsDirectly = true; 04557 04558 if (ICS) { 04559 ICS->setUserDefined(); 04560 ICS->UserDefined.Before = Best->Conversions[0].Standard; 04561 ICS->UserDefined.After = Best->FinalConversion; 04562 ICS->UserDefined.ConversionFunction = Best->Function; 04563 ICS->UserDefined.EllipsisConversion = false; 04564 assert(ICS->UserDefined.After.ReferenceBinding && 04565 ICS->UserDefined.After.DirectBinding && 04566 "Expected a direct reference binding!"); 04567 return false; 04568 } else { 04569 OwningExprResult InitConversion = 04570 BuildCXXCastArgument(DeclLoc, QualType(), 04571 CastExpr::CK_UserDefinedConversion, 04572 cast<CXXMethodDecl>(Best->Function), 04573 Owned(Init)); 04574 Init = InitConversion.takeAs<Expr>(); 04575 04576 if (CheckExceptionSpecCompatibility(Init, T1)) 04577 return true; 04578 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion, 04579 /*isLvalue=*/true); 04580 } 04581 break; 04582 04583 case OR_Ambiguous: 04584 if (ICS) { 04585 ICS->setAmbiguous(); 04586 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 04587 Cand != CandidateSet.end(); ++Cand) 04588 if (Cand->Viable) 04589 ICS->Ambiguous.addConversion(Cand->Function); 04590 break; 04591 } 04592 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType() 04593 << Init->getSourceRange(); 04594 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1); 04595 return true; 04596 04597 case OR_No_Viable_Function: 04598 case OR_Deleted: 04599 // There was no suitable conversion, or we found a deleted 04600 // conversion; continue with other checks. 04601 break; 04602 } 04603 } 04604 04605 if (BindsDirectly) { 04606 // C++ [dcl.init.ref]p4: 04607 // [...] In all cases where the reference-related or 04608 // reference-compatible relationship of two types is used to 04609 // establish the validity of a reference binding, and T1 is a 04610 // base class of T2, a program that necessitates such a binding 04611 // is ill-formed if T1 is an inaccessible (clause 11) or 04612 // ambiguous (10.2) base class of T2. 04613 // 04614 // Note that we only check this condition when we're allowed to 04615 // complain about errors, because we should not be checking for 04616 // ambiguity (or inaccessibility) unless the reference binding 04617 // actually happens. 04618 if (DerivedToBase) 04619 return CheckDerivedToBaseConversion(T2, T1, DeclLoc, 04620 Init->getSourceRange(), 04621 IgnoreBaseAccess); 04622 else 04623 return false; 04624 } 04625 04626 // -- Otherwise, the reference shall be to a non-volatile const 04627 // type (i.e., cv1 shall be const), or the reference shall be an 04628 // rvalue reference and the initializer expression shall be an rvalue. 04629 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) { 04630 if (!ICS) 04631 Diag(DeclLoc, diag::err_not_reference_to_const_init) 04632 << T1.isVolatileQualified() 04633 << T1 << int(InitLvalue != Expr::LV_Valid) 04634 << T2 << Init->getSourceRange(); 04635 return true; 04636 } 04637 04638 // -- If the initializer expression is an rvalue, with T2 a 04639 // class type, and "cv1 T1" is reference-compatible with 04640 // "cv2 T2," the reference is bound in one of the 04641 // following ways (the choice is implementation-defined): 04642 // 04643 // -- The reference is bound to the object represented by 04644 // the rvalue (see 3.10) or to a sub-object within that 04645 // object. 04646 // 04647 // -- A temporary of type "cv1 T2" [sic] is created, and 04648 // a constructor is called to copy the entire rvalue 04649 // object into the temporary. The reference is bound to 04650 // the temporary or to a sub-object within the 04651 // temporary. 04652 // 04653 // The constructor that would be used to make the copy 04654 // shall be callable whether or not the copy is actually 04655 // done. 04656 // 04657 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 04658 // freedom, so we will always take the first option and never build 04659 // a temporary in this case. FIXME: We will, however, have to check 04660 // for the presence of a copy constructor in C++98/03 mode. 04661 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 04662 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 04663 if (ICS) { 04664 ICS->setStandard(); 04665 ICS->Standard.First = ICK_Identity; 04666 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 04667 ICS->Standard.Third = ICK_Identity; 04668 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 04669 ICS->Standard.setToType(0, T2); 04670 ICS->Standard.setToType(1, T1); 04671 ICS->Standard.setToType(2, T1); 04672 ICS->Standard.ReferenceBinding = true; 04673 ICS->Standard.DirectBinding = false; 04674 ICS->Standard.RRefBinding = isRValRef; 04675 ICS->Standard.CopyConstructor = 0; 04676 } else { 04677 CastExpr::CastKind CK = CastExpr::CK_NoOp; 04678 if (DerivedToBase) 04679 CK = CastExpr::CK_DerivedToBase; 04680 else if(CheckExceptionSpecCompatibility(Init, T1)) 04681 return true; 04682 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 04683 } 04684 return false; 04685 } 04686 04687 // -- Otherwise, a temporary of type "cv1 T1" is created and 04688 // initialized from the initializer expression using the 04689 // rules for a non-reference copy initialization (8.5). The 04690 // reference is then bound to the temporary. If T1 is 04691 // reference-related to T2, cv1 must be the same 04692 // cv-qualification as, or greater cv-qualification than, 04693 // cv2; otherwise, the program is ill-formed. 04694 if (RefRelationship == Ref_Related) { 04695 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 04696 // we would be reference-compatible or reference-compatible with 04697 // added qualification. But that wasn't the case, so the reference 04698 // initialization fails. 04699 if (!ICS) 04700 Diag(DeclLoc, diag::err_reference_init_drops_quals) 04701 << T1 << int(InitLvalue != Expr::LV_Valid) 04702 << T2 << Init->getSourceRange(); 04703 return true; 04704 } 04705 04706 // If at least one of the types is a class type, the types are not 04707 // related, and we aren't allowed any user conversions, the 04708 // reference binding fails. This case is important for breaking 04709 // recursion, since TryImplicitConversion below will attempt to 04710 // create a temporary through the use of a copy constructor. 04711 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 04712 (T1->isRecordType() || T2->isRecordType())) { 04713 if (!ICS) 04714 Diag(DeclLoc, diag::err_typecheck_convert_incompatible) 04715 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange(); 04716 return true; 04717 } 04718 04719 // Actually try to convert the initializer to T1. 04720 if (ICS) { 04721 // C++ [over.ics.ref]p2: 04722 // 04723 // When a parameter of reference type is not bound directly to 04724 // an argument expression, the conversion sequence is the one 04725 // required to convert the argument expression to the 04726 // underlying type of the reference according to 04727 // 13.3.3.1. Conceptually, this conversion sequence corresponds 04728 // to copy-initializing a temporary of the underlying type with 04729 // the argument expression. Any difference in top-level 04730 // cv-qualification is subsumed by the initialization itself 04731 // and does not constitute a conversion. 04732 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 04733 /*AllowExplicit=*/false, 04734 /*ForceRValue=*/false, 04735 /*InOverloadResolution=*/false); 04736 04737 // Of course, that's still a reference binding. 04738 if (ICS->isStandard()) { 04739 ICS->Standard.ReferenceBinding = true; 04740 ICS->Standard.RRefBinding = isRValRef; 04741 } else if (ICS->isUserDefined()) { 04742 ICS->UserDefined.After.ReferenceBinding = true; 04743 ICS->UserDefined.After.RRefBinding = isRValRef; 04744 } 04745 return ICS->isBad(); 04746 } else { 04747 ImplicitConversionSequence Conversions; 04748 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing, 04749 false, false, 04750 Conversions); 04751 if (badConversion) { 04752 if (Conversions.isAmbiguous()) { 04753 Diag(DeclLoc, 04754 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 04755 for (int j = Conversions.Ambiguous.conversions().size()-1; 04756 j >= 0; j--) { 04757 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j]; 04758 NoteOverloadCandidate(Func); 04759 } 04760 } 04761 else { 04762 if (isRValRef) 04763 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 04764 << Init->getSourceRange(); 04765 else 04766 Diag(DeclLoc, diag::err_invalid_initialization) 04767 << DeclType << Init->getType() << Init->getSourceRange(); 04768 } 04769 } 04770 return badConversion; 04771 } 04772 } 04773 04774 static inline bool 04775 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 04776 const FunctionDecl *FnDecl) { 04777 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 04778 if (isa<NamespaceDecl>(DC)) { 04779 return SemaRef.Diag(FnDecl->getLocation(), 04780 diag::err_operator_new_delete_declared_in_namespace) 04781 << FnDecl->getDeclName(); 04782 } 04783 04784 if (isa<TranslationUnitDecl>(DC) && 04785 FnDecl->getStorageClass() == FunctionDecl::Static) { 04786 return SemaRef.Diag(FnDecl->getLocation(), 04787 diag::err_operator_new_delete_declared_static) 04788 << FnDecl->getDeclName(); 04789 } 04790 04791 return false; 04792 } 04793 04794 static inline bool 04795 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 04796 CanQualType ExpectedResultType, 04797 CanQualType ExpectedFirstParamType, 04798 unsigned DependentParamTypeDiag, 04799 unsigned InvalidParamTypeDiag) { 04800 QualType ResultType = 04801 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 04802 04803 // Check that the result type is not dependent. 04804 if (ResultType->isDependentType()) 04805 return SemaRef.Diag(FnDecl->getLocation(), 04806 diag::err_operator_new_delete_dependent_result_type) 04807 << FnDecl->getDeclName() << ExpectedResultType; 04808 04809 // Check that the result type is what we expect. 04810 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 04811 return SemaRef.Diag(FnDecl->getLocation(), 04812 diag::err_operator_new_delete_invalid_result_type) 04813 << FnDecl->getDeclName() << ExpectedResultType; 04814 04815 // A function template must have at least 2 parameters. 04816 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 04817 return SemaRef.Diag(FnDecl->getLocation(), 04818 diag::err_operator_new_delete_template_too_few_parameters) 04819 << FnDecl->getDeclName(); 04820 04821 // The function decl must have at least 1 parameter. 04822 if (FnDecl->getNumParams() == 0) 04823 return SemaRef.Diag(FnDecl->getLocation(), 04824 diag::err_operator_new_delete_too_few_parameters) 04825 << FnDecl->getDeclName(); 04826 04827 // Check the the first parameter type is not dependent. 04828 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 04829 if (FirstParamType->isDependentType()) 04830 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 04831 << FnDecl->getDeclName() << ExpectedFirstParamType; 04832 04833 // Check that the first parameter type is what we expect. 04834 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 04835 ExpectedFirstParamType) 04836 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 04837 << FnDecl->getDeclName() << ExpectedFirstParamType; 04838 04839 return false; 04840 } 04841 04842 static bool 04843 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 04844 // C++ [basic.stc.dynamic.allocation]p1: 04845 // A program is ill-formed if an allocation function is declared in a 04846 // namespace scope other than global scope or declared static in global 04847 // scope. 04848 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 04849 return true; 04850 04851 CanQualType SizeTy = 04852 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 04853 04854 // C++ [basic.stc.dynamic.allocation]p1: 04855 // The return type shall be void*. The first parameter shall have type 04856 // std::size_t. 04857 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 04858 SizeTy, 04859 diag::err_operator_new_dependent_param_type, 04860 diag::err_operator_new_param_type)) 04861 return true; 04862 04863 // C++ [basic.stc.dynamic.allocation]p1: 04864 // The first parameter shall not have an associated default argument. 04865 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 04866 return SemaRef.Diag(FnDecl->getLocation(), 04867 diag::err_operator_new_default_arg) 04868 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 04869 04870 return false; 04871 } 04872 04873 static bool 04874 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 04875 // C++ [basic.stc.dynamic.deallocation]p1: 04876 // A program is ill-formed if deallocation functions are declared in a 04877 // namespace scope other than global scope or declared static in global 04878 // scope. 04879 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 04880 return true; 04881 04882 // C++ [basic.stc.dynamic.deallocation]p2: 04883 // Each deallocation function shall return void and its first parameter 04884 // shall be void*. 04885 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 04886 SemaRef.Context.VoidPtrTy, 04887 diag::err_operator_delete_dependent_param_type, 04888 diag::err_operator_delete_param_type)) 04889 return true; 04890 04891 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 04892 if (FirstParamType->isDependentType()) 04893 return SemaRef.Diag(FnDecl->getLocation(), 04894 diag::err_operator_delete_dependent_param_type) 04895 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 04896 04897 if (SemaRef.Context.getCanonicalType(FirstParamType) != 04898 SemaRef.Context.VoidPtrTy) 04899 return SemaRef.Diag(FnDecl->getLocation(), 04900 diag::err_operator_delete_param_type) 04901 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 04902 04903 return false; 04904 } 04905 04906 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 04907 /// of this overloaded operator is well-formed. If so, returns false; 04908 /// otherwise, emits appropriate diagnostics and returns true. 04909 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 04910 assert(FnDecl && FnDecl->isOverloadedOperator() && 04911 "Expected an overloaded operator declaration"); 04912 04913 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 04914 04915 // C++ [over.oper]p5: 04916 // The allocation and deallocation functions, operator new, 04917 // operator new[], operator delete and operator delete[], are 04918 // described completely in 3.7.3. The attributes and restrictions 04919 // found in the rest of this subclause do not apply to them unless 04920 // explicitly stated in 3.7.3. 04921 if (Op == OO_Delete || Op == OO_Array_Delete) 04922 return CheckOperatorDeleteDeclaration(*this, FnDecl); 04923 04924 if (Op == OO_New || Op == OO_Array_New) 04925 return CheckOperatorNewDeclaration(*this, FnDecl); 04926 04927 // C++ [over.oper]p6: 04928 // An operator function shall either be a non-static member 04929 // function or be a non-member function and have at least one 04930 // parameter whose type is a class, a reference to a class, an 04931 // enumeration, or a reference to an enumeration. 04932 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 04933 if (MethodDecl->isStatic()) 04934 return Diag(FnDecl->getLocation(), 04935 diag::err_operator_overload_static) << FnDecl->getDeclName(); 04936 } else { 04937 bool ClassOrEnumParam = false; 04938 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 04939 ParamEnd = FnDecl->param_end(); 04940 Param != ParamEnd; ++Param) { 04941 QualType ParamType = (*Param)->getType().getNonReferenceType(); 04942 if (ParamType->isDependentType() || ParamType->isRecordType() || 04943 ParamType->isEnumeralType()) { 04944 ClassOrEnumParam = true; 04945 break; 04946 } 04947 } 04948 04949 if (!ClassOrEnumParam) 04950 return Diag(FnDecl->getLocation(), 04951 diag::err_operator_overload_needs_class_or_enum) 04952 << FnDecl->getDeclName(); 04953 } 04954 04955 // C++ [over.oper]p8: 04956 // An operator function cannot have default arguments (8.3.6), 04957 // except where explicitly stated below. 04958 // 04959 // Only the function-call operator allows default arguments 04960 // (C++ [over.call]p1). 04961 if (Op != OO_Call) { 04962 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 04963 Param != FnDecl->param_end(); ++Param) { 04964 if ((*Param)->hasDefaultArg()) 04965 return Diag((*Param)->getLocation(), 04966 diag::err_operator_overload_default_arg) 04967 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 04968 } 04969 } 04970 04971 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 04972 { false, false, false } 04973 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 04974 , { Unary, Binary, MemberOnly } 04975 #include "clang/Basic/OperatorKinds.def" 04976 }; 04977 04978 bool CanBeUnaryOperator = OperatorUses[Op][0]; 04979 bool CanBeBinaryOperator = OperatorUses[Op][1]; 04980 bool MustBeMemberOperator = OperatorUses[Op][2]; 04981 04982 // C++ [over.oper]p8: 04983 // [...] Operator functions cannot have more or fewer parameters 04984 // than the number required for the corresponding operator, as 04985 // described in the rest of this subclause. 04986 unsigned NumParams = FnDecl->getNumParams() 04987 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 04988 if (Op != OO_Call && 04989 ((NumParams == 1 && !CanBeUnaryOperator) || 04990 (NumParams == 2 && !CanBeBinaryOperator) || 04991 (NumParams < 1) || (NumParams > 2))) { 04992 // We have the wrong number of parameters. 04993 unsigned ErrorKind; 04994 if (CanBeUnaryOperator && CanBeBinaryOperator) { 04995 ErrorKind = 2; // 2 -> unary or binary. 04996 } else if (CanBeUnaryOperator) { 04997 ErrorKind = 0; // 0 -> unary 04998 } else { 04999 assert(CanBeBinaryOperator && 05000 "All non-call overloaded operators are unary or binary!"); 05001 ErrorKind = 1; // 1 -> binary 05002 } 05003 05004 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 05005 << FnDecl->getDeclName() << NumParams << ErrorKind; 05006 } 05007 05008 // Overloaded operators other than operator() cannot be variadic. 05009 if (Op != OO_Call && 05010 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 05011 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 05012 << FnDecl->getDeclName(); 05013 } 05014 05015 // Some operators must be non-static member functions. 05016 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 05017 return Diag(FnDecl->getLocation(), 05018 diag::err_operator_overload_must_be_member) 05019 << FnDecl->getDeclName(); 05020 } 05021 05022 // C++ [over.inc]p1: 05023 // The user-defined function called operator++ implements the 05024 // prefix and postfix ++ operator. If this function is a member 05025 // function with no parameters, or a non-member function with one 05026 // parameter of class or enumeration type, it defines the prefix 05027 // increment operator ++ for objects of that type. If the function 05028 // is a member function with one parameter (which shall be of type 05029 // int) or a non-member function with two parameters (the second 05030 // of which shall be of type int), it defines the postfix 05031 // increment operator ++ for objects of that type. 05032 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 05033 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 05034 bool ParamIsInt = false; 05035 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 05036 ParamIsInt = BT->getKind() == BuiltinType::Int; 05037 05038 if (!ParamIsInt) 05039 return Diag(LastParam->getLocation(), 05040 diag::err_operator_overload_post_incdec_must_be_int) 05041 << LastParam->getType() << (Op == OO_MinusMinus); 05042 } 05043 05044 // Notify the class if it got an assignment operator. 05045 if (Op == OO_Equal) { 05046 // Would have returned earlier otherwise. 05047 assert(isa<CXXMethodDecl>(FnDecl) && 05048 "Overloaded = not member, but not filtered."); 05049 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 05050 Method->getParent()->addedAssignmentOperator(Context, Method); 05051 } 05052 05053 return false; 05054 } 05055 05056 /// CheckLiteralOperatorDeclaration - Check whether the declaration 05057 /// of this literal operator function is well-formed. If so, returns 05058 /// false; otherwise, emits appropriate diagnostics and returns true. 05059 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 05060 DeclContext *DC = FnDecl->getDeclContext(); 05061 Decl::Kind Kind = DC->getDeclKind(); 05062 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 05063 Kind != Decl::LinkageSpec) { 05064 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 05065 << FnDecl->getDeclName(); 05066 return true; 05067 } 05068 05069 bool Valid = false; 05070 05071 // FIXME: Check for the one valid template signature 05072 // template <char...> type operator "" name(); 05073 05074 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) { 05075 // Check the first parameter 05076 QualType T = (*Param)->getType(); 05077 05078 // unsigned long long int and long double are allowed, but only 05079 // alone. 05080 // We also allow any character type; their omission seems to be a bug 05081 // in n3000 05082 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 05083 Context.hasSameType(T, Context.LongDoubleTy) || 05084 Context.hasSameType(T, Context.CharTy) || 05085 Context.hasSameType(T, Context.WCharTy) || 05086 Context.hasSameType(T, Context.Char16Ty) || 05087 Context.hasSameType(T, Context.Char32Ty)) { 05088 if (++Param == FnDecl->param_end()) 05089 Valid = true; 05090 goto FinishedParams; 05091 } 05092 05093 // Otherwise it must be a pointer to const; let's strip those. 05094 const PointerType *PT = T->getAs<PointerType>(); 05095 if (!PT) 05096 goto FinishedParams; 05097 T = PT->getPointeeType(); 05098 if (!T.isConstQualified()) 05099 goto FinishedParams; 05100 T = T.getUnqualifiedType(); 05101 05102 // Move on to the second parameter; 05103 ++Param; 05104 05105 // If there is no second parameter, the first must be a const char * 05106 if (Param == FnDecl->param_end()) { 05107 if (Context.hasSameType(T, Context.CharTy)) 05108 Valid = true; 05109 goto FinishedParams; 05110 } 05111 05112 // const char *, const wchar_t*, const char16_t*, and const char32_t* 05113 // are allowed as the first parameter to a two-parameter function 05114 if (!(Context.hasSameType(T, Context.CharTy) || 05115 Context.hasSameType(T, Context.WCharTy) || 05116 Context.hasSameType(T, Context.Char16Ty) || 05117 Context.hasSameType(T, Context.Char32Ty))) 05118 goto FinishedParams; 05119 05120 // The second and final parameter must be an std::size_t 05121 T = (*Param)->getType().getUnqualifiedType(); 05122 if (Context.hasSameType(T, Context.getSizeType()) && 05123 ++Param == FnDecl->param_end()) 05124 Valid = true; 05125 } 05126 05127 // FIXME: This diagnostic is absolutely terrible. 05128 FinishedParams: 05129 if (!Valid) { 05130 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 05131 << FnDecl->getDeclName(); 05132 return true; 05133 } 05134 05135 return false; 05136 } 05137 05138 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 05139 /// linkage specification, including the language and (if present) 05140 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is 05141 /// the location of the language string literal, which is provided 05142 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of 05143 /// the '{' brace. Otherwise, this linkage specification does not 05144 /// have any braces. 05145 Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 05146 SourceLocation ExternLoc, 05147 SourceLocation LangLoc, 05148 const char *Lang, 05149 unsigned StrSize, 05150 SourceLocation LBraceLoc) { 05151 LinkageSpecDecl::LanguageIDs Language; 05152 if (strncmp(Lang, "\"C\"", StrSize) == 0) 05153 Language = LinkageSpecDecl::lang_c; 05154 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 05155 Language = LinkageSpecDecl::lang_cxx; 05156 else { 05157 Diag(LangLoc, diag::err_bad_language); 05158 return DeclPtrTy(); 05159 } 05160 05161 // FIXME: Add all the various semantics of linkage specifications 05162 05163 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 05164 LangLoc, Language, 05165 LBraceLoc.isValid()); 05166 CurContext->addDecl(D); 05167 PushDeclContext(S, D); 05168 return DeclPtrTy::make(D); 05169 } 05170 05171 /// ActOnFinishLinkageSpecification - Completely the definition of 05172 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 05173 /// valid, it's the position of the closing '}' brace in a linkage 05174 /// specification that uses braces. 05175 Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 05176 DeclPtrTy LinkageSpec, 05177 SourceLocation RBraceLoc) { 05178 if (LinkageSpec) 05179 PopDeclContext(); 05180 return LinkageSpec; 05181 } 05182 05183 /// \brief Perform semantic analysis for the variable declaration that 05184 /// occurs within a C++ catch clause, returning the newly-created 05185 /// variable. 05186 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 05187 TypeSourceInfo *TInfo, 05188 IdentifierInfo *Name, 05189 SourceLocation Loc, 05190 SourceRange Range) { 05191 bool Invalid = false; 05192 05193 // Arrays and functions decay. 05194 if (ExDeclType->isArrayType()) 05195 ExDeclType = Context.getArrayDecayedType(ExDeclType); 05196 else if (ExDeclType->isFunctionType()) 05197 ExDeclType = Context.getPointerType(ExDeclType); 05198 05199 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 05200 // The exception-declaration shall not denote a pointer or reference to an 05201 // incomplete type, other than [cv] void*. 05202 // N2844 forbids rvalue references. 05203 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 05204 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 05205 Invalid = true; 05206 } 05207 05208 // GCC allows catching pointers and references to incomplete types 05209 // as an extension; so do we, but we warn by default. 05210 05211 QualType BaseType = ExDeclType; 05212 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 05213 unsigned DK = diag::err_catch_incomplete; 05214 bool IncompleteCatchIsInvalid = true; 05215 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 05216 BaseType = Ptr->getPointeeType(); 05217 Mode = 1; 05218 DK = diag::ext_catch_incomplete_ptr; 05219 IncompleteCatchIsInvalid = false; 05220 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 05221 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 05222 BaseType = Ref->getPointeeType(); 05223 Mode = 2; 05224 DK = diag::ext_catch_incomplete_ref; 05225 IncompleteCatchIsInvalid = false; 05226 } 05227 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 05228 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 05229 IncompleteCatchIsInvalid) 05230 Invalid = true; 05231 05232 if (!Invalid && !ExDeclType->isDependentType() && 05233 RequireNonAbstractType(Loc, ExDeclType, 05234 diag::err_abstract_type_in_decl, 05235 AbstractVariableType)) 05236 Invalid = true; 05237 05238 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 05239 Name, ExDeclType, TInfo, VarDecl::None); 05240 05241 if (!Invalid) { 05242 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 05243 // C++ [except.handle]p16: 05244 // The object declared in an exception-declaration or, if the 05245 // exception-declaration does not specify a name, a temporary (12.2) is 05246 // copy-initialized (8.5) from the exception object. [...] 05247 // The object is destroyed when the handler exits, after the destruction 05248 // of any automatic objects initialized within the handler. 05249 // 05250 // We just pretend to initialize the object with itself, then make sure 05251 // it can be destroyed later. 05252 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 05253 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 05254 Loc, ExDeclType, 0); 05255 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 05256 SourceLocation()); 05257 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 05258 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 05259 MultiExprArg(*this, (void**)&ExDeclRef, 1)); 05260 if (Result.isInvalid()) 05261 Invalid = true; 05262 else 05263 FinalizeVarWithDestructor(ExDecl, RecordTy); 05264 } 05265 } 05266 05267 if (Invalid) 05268 ExDecl->setInvalidDecl(); 05269 05270 return ExDecl; 05271 } 05272 05273 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 05274 /// handler. 05275 Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 05276 TypeSourceInfo *TInfo = 0; 05277 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 05278 05279 bool Invalid = D.isInvalidType(); 05280 IdentifierInfo *II = D.getIdentifier(); 05281 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) { 05282 // The scope should be freshly made just for us. There is just no way 05283 // it contains any previous declaration. 05284 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 05285 if (PrevDecl->isTemplateParameter()) { 05286 // Maybe we will complain about the shadowed template parameter. 05287 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 05288 } 05289 } 05290 05291 if (D.getCXXScopeSpec().isSet() && !Invalid) { 05292 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 05293 << D.getCXXScopeSpec().getRange(); 05294 Invalid = true; 05295 } 05296 05297 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 05298 D.getIdentifier(), 05299 D.getIdentifierLoc(), 05300 D.getDeclSpec().getSourceRange()); 05301 05302 if (Invalid) 05303 ExDecl->setInvalidDecl(); 05304 05305 // Add the exception declaration into this scope. 05306 if (II) 05307 PushOnScopeChains(ExDecl, S); 05308 else 05309 CurContext->addDecl(ExDecl); 05310 05311 ProcessDeclAttributes(S, ExDecl, D); 05312 return DeclPtrTy::make(ExDecl); 05313 } 05314 05315 Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 05316 ExprArg assertexpr, 05317 ExprArg assertmessageexpr) { 05318 Expr *AssertExpr = (Expr *)assertexpr.get(); 05319 StringLiteral *AssertMessage = 05320 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 05321 05322 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 05323 llvm::APSInt Value(32); 05324 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 05325 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 05326 AssertExpr->getSourceRange(); 05327 return DeclPtrTy(); 05328 } 05329 05330 if (Value == 0) { 05331 Diag(AssertLoc, diag::err_static_assert_failed) 05332 << AssertMessage->getString() << AssertExpr->getSourceRange(); 05333 } 05334 } 05335 05336 assertexpr.release(); 05337 assertmessageexpr.release(); 05338 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 05339 AssertExpr, AssertMessage); 05340 05341 CurContext->addDecl(Decl); 05342 return DeclPtrTy::make(Decl); 05343 } 05344 05345 /// Handle a friend type declaration. This works in tandem with 05346 /// ActOnTag. 05347 /// 05348 /// Notes on friend class templates: 05349 /// 05350 /// We generally treat friend class declarations as if they were 05351 /// declaring a class. So, for example, the elaborated type specifier 05352 /// in a friend declaration is required to obey the restrictions of a 05353 /// class-head (i.e. no typedefs in the scope chain), template 05354 /// parameters are required to match up with simple template-ids, &c. 05355 /// However, unlike when declaring a template specialization, it's 05356 /// okay to refer to a template specialization without an empty 05357 /// template parameter declaration, e.g. 05358 /// friend class A<T>::B<unsigned>; 05359 /// We permit this as a special case; if there are any template 05360 /// parameters present at all, require proper matching, i.e. 05361 /// template <> template <class T> friend class A<int>::B; 05362 Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 05363 MultiTemplateParamsArg TempParams) { 05364 SourceLocation Loc = DS.getSourceRange().getBegin(); 05365 05366 assert(DS.isFriendSpecified()); 05367 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 05368 05369 // Try to convert the decl specifier to a type. This works for 05370 // friend templates because ActOnTag never produces a ClassTemplateDecl 05371 // for a TUK_Friend. 05372 Declarator TheDeclarator(DS, Declarator::MemberContext); 05373 QualType T = GetTypeForDeclarator(TheDeclarator, S); 05374 if (TheDeclarator.isInvalidType()) 05375 return DeclPtrTy(); 05376 05377 // This is definitely an error in C++98. It's probably meant to 05378 // be forbidden in C++0x, too, but the specification is just 05379 // poorly written. 05380 // 05381 // The problem is with declarations like the following: 05382 // template <T> friend A<T>::foo; 05383 // where deciding whether a class C is a friend or not now hinges 05384 // on whether there exists an instantiation of A that causes 05385 // 'foo' to equal C. There are restrictions on class-heads 05386 // (which we declare (by fiat) elaborated friend declarations to 05387 // be) that makes this tractable. 05388 // 05389 // FIXME: handle "template <> friend class A<T>;", which 05390 // is possibly well-formed? Who even knows? 05391 if (TempParams.size() && !isa<ElaboratedType>(T)) { 05392 Diag(Loc, diag::err_tagless_friend_type_template) 05393 << DS.getSourceRange(); 05394 return DeclPtrTy(); 05395 } 05396 05397 // C++ [class.friend]p2: 05398 // An elaborated-type-specifier shall be used in a friend declaration 05399 // for a class.* 05400 // * The class-key of the elaborated-type-specifier is required. 05401 // This is one of the rare places in Clang where it's legitimate to 05402 // ask about the "spelling" of the type. 05403 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 05404 // If we evaluated the type to a record type, suggest putting 05405 // a tag in front. 05406 if (const RecordType *RT = T->getAs<RecordType>()) { 05407 RecordDecl *RD = RT->getDecl(); 05408 05409 std::string InsertionText = std::string(" ") + RD->getKindName(); 05410 05411 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type) 05412 << (unsigned) RD->getTagKind() 05413 << T 05414 << SourceRange(DS.getFriendSpecLoc()) 05415 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 05416 InsertionText); 05417 return DeclPtrTy(); 05418 }else { 05419 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 05420 << DS.getSourceRange(); 05421 return DeclPtrTy(); 05422 } 05423 } 05424 05425 // Enum types cannot be friends. 05426 if (T->getAs<EnumType>()) { 05427 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend) 05428 << SourceRange(DS.getFriendSpecLoc()); 05429 return DeclPtrTy(); 05430 } 05431 05432 // C++98 [class.friend]p1: A friend of a class is a function 05433 // or class that is not a member of the class . . . 05434 // This is fixed in DR77, which just barely didn't make the C++03 05435 // deadline. It's also a very silly restriction that seriously 05436 // affects inner classes and which nobody else seems to implement; 05437 // thus we never diagnose it, not even in -pedantic. 05438 05439 Decl *D; 05440 if (TempParams.size()) 05441 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 05442 TempParams.size(), 05443 (TemplateParameterList**) TempParams.release(), 05444 T.getTypePtr(), 05445 DS.getFriendSpecLoc()); 05446 else 05447 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(), 05448 DS.getFriendSpecLoc()); 05449 D->setAccess(AS_public); 05450 CurContext->addDecl(D); 05451 05452 return DeclPtrTy::make(D); 05453 } 05454 05455 Sema::DeclPtrTy 05456 Sema::ActOnFriendFunctionDecl(Scope *S, 05457 Declarator &D, 05458 bool IsDefinition, 05459 MultiTemplateParamsArg TemplateParams) { 05460 const DeclSpec &DS = D.getDeclSpec(); 05461 05462 assert(DS.isFriendSpecified()); 05463 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 05464 05465 SourceLocation Loc = D.getIdentifierLoc(); 05466 TypeSourceInfo *TInfo = 0; 05467 QualType T = GetTypeForDeclarator(D, S, &TInfo); 05468 05469 // C++ [class.friend]p1 05470 // A friend of a class is a function or class.... 05471 // Note that this sees through typedefs, which is intended. 05472 // It *doesn't* see through dependent types, which is correct 05473 // according to [temp.arg.type]p3: 05474 // If a declaration acquires a function type through a 05475 // type dependent on a template-parameter and this causes 05476 // a declaration that does not use the syntactic form of a 05477 // function declarator to have a function type, the program 05478 // is ill-formed. 05479 if (!T->isFunctionType()) { 05480 Diag(Loc, diag::err_unexpected_friend); 05481 05482 // It might be worthwhile to try to recover by creating an 05483 // appropriate declaration. 05484 return DeclPtrTy(); 05485 } 05486 05487 // C++ [namespace.memdef]p3 05488 // - If a friend declaration in a non-local class first declares a 05489 // class or function, the friend class or function is a member 05490 // of the innermost enclosing namespace. 05491 // - The name of the friend is not found by simple name lookup 05492 // until a matching declaration is provided in that namespace 05493 // scope (either before or after the class declaration granting 05494 // friendship). 05495 // - If a friend function is called, its name may be found by the 05496 // name lookup that considers functions from namespaces and 05497 // classes associated with the types of the function arguments. 05498 // - When looking for a prior declaration of a class or a function 05499 // declared as a friend, scopes outside the innermost enclosing 05500 // namespace scope are not considered. 05501 05502 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 05503 DeclarationName Name = GetNameForDeclarator(D); 05504 assert(Name); 05505 05506 // The context we found the declaration in, or in which we should 05507 // create the declaration. 05508 DeclContext *DC; 05509 05510 // FIXME: handle local classes 05511 05512 // Recover from invalid scope qualifiers as if they just weren't there. 05513 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 05514 ForRedeclaration); 05515 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 05516 // FIXME: RequireCompleteDeclContext 05517 DC = computeDeclContext(ScopeQual); 05518 05519 // FIXME: handle dependent contexts 05520 if (!DC) return DeclPtrTy(); 05521 05522 LookupQualifiedName(Previous, DC); 05523 05524 // If searching in that context implicitly found a declaration in 05525 // a different context, treat it like it wasn't found at all. 05526 // TODO: better diagnostics for this case. Suggesting the right 05527 // qualified scope would be nice... 05528 // FIXME: getRepresentativeDecl() is not right here at all 05529 if (Previous.empty() || 05530 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 05531 D.setInvalidType(); 05532 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 05533 return DeclPtrTy(); 05534 } 05535 05536 // C++ [class.friend]p1: A friend of a class is a function or 05537 // class that is not a member of the class . . . 05538 if (DC->Equals(CurContext)) 05539 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 05540 05541 // Otherwise walk out to the nearest namespace scope looking for matches. 05542 } else { 05543 // TODO: handle local class contexts. 05544 05545 DC = CurContext; 05546 while (true) { 05547 // Skip class contexts. If someone can cite chapter and verse 05548 // for this behavior, that would be nice --- it's what GCC and 05549 // EDG do, and it seems like a reasonable intent, but the spec 05550 // really only says that checks for unqualified existing 05551 // declarations should stop at the nearest enclosing namespace, 05552 // not that they should only consider the nearest enclosing 05553 // namespace. 05554 while (DC->isRecord()) 05555 DC = DC->getParent(); 05556 05557 LookupQualifiedName(Previous, DC); 05558 05559 // TODO: decide what we think about using declarations. 05560 if (!Previous.empty()) 05561 break; 05562 05563 if (DC->isFileContext()) break; 05564 DC = DC->getParent(); 05565 } 05566 05567 // C++ [class.friend]p1: A friend of a class is a function or 05568 // class that is not a member of the class . . . 05569 // C++0x changes this for both friend types and functions. 05570 // Most C++ 98 compilers do seem to give an error here, so 05571 // we do, too. 05572 if (!Previous.empty() && DC->Equals(CurContext) 05573 && !getLangOptions().CPlusPlus0x) 05574 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 05575 } 05576 05577 if (DC->isFileContext()) { 05578 // This implies that it has to be an operator or function. 05579 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 05580 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 05581 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 05582 Diag(Loc, diag::err_introducing_special_friend) << 05583 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 05584 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 05585 return DeclPtrTy(); 05586 } 05587 } 05588 05589 bool Redeclaration = false; 05590 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 05591 move(TemplateParams), 05592 IsDefinition, 05593 Redeclaration); 05594 if (!ND) return DeclPtrTy(); 05595 05596 assert(ND->getDeclContext() == DC); 05597 assert(ND->getLexicalDeclContext() == CurContext); 05598 05599 // Add the function declaration to the appropriate lookup tables, 05600 // adjusting the redeclarations list as necessary. We don't 05601 // want to do this yet if the friending class is dependent. 05602 // 05603 // Also update the scope-based lookup if the target context's 05604 // lookup context is in lexical scope. 05605 if (!CurContext->isDependentContext()) { 05606 DC = DC->getLookupContext(); 05607 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 05608 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 05609 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 05610 } 05611 05612 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 05613 D.getIdentifierLoc(), ND, 05614 DS.getFriendSpecLoc()); 05615 FrD->setAccess(AS_public); 05616 CurContext->addDecl(FrD); 05617 05618 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) 05619 FrD->setSpecialization(true); 05620 05621 return DeclPtrTy::make(ND); 05622 } 05623 05624 void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 05625 AdjustDeclIfTemplate(dcl); 05626 05627 Decl *Dcl = dcl.getAs<Decl>(); 05628 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 05629 if (!Fn) { 05630 Diag(DelLoc, diag::err_deleted_non_function); 05631 return; 05632 } 05633 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 05634 Diag(DelLoc, diag::err_deleted_decl_not_first); 05635 Diag(Prev->getLocation(), diag::note_previous_declaration); 05636 // If the declaration wasn't the first, we delete the function anyway for 05637 // recovery. 05638 } 05639 Fn->setDeleted(); 05640 } 05641 05642 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 05643 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 05644 ++CI) { 05645 Stmt *SubStmt = *CI; 05646 if (!SubStmt) 05647 continue; 05648 if (isa<ReturnStmt>(SubStmt)) 05649 Self.Diag(SubStmt->getSourceRange().getBegin(), 05650 diag::err_return_in_constructor_handler); 05651 if (!isa<Expr>(SubStmt)) 05652 SearchForReturnInStmt(Self, SubStmt); 05653 } 05654 } 05655 05656 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 05657 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 05658 CXXCatchStmt *Handler = TryBlock->getHandler(I); 05659 SearchForReturnInStmt(*this, Handler); 05660 } 05661 } 05662 05663 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 05664 const CXXMethodDecl *Old) { 05665 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 05666 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 05667 05668 if (Context.hasSameType(NewTy, OldTy) || 05669 NewTy->isDependentType() || OldTy->isDependentType()) 05670 return false; 05671 05672 // Check if the return types are covariant 05673 QualType NewClassTy, OldClassTy; 05674 05675 /// Both types must be pointers or references to classes. 05676 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 05677 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 05678 NewClassTy = NewPT->getPointeeType(); 05679 OldClassTy = OldPT->getPointeeType(); 05680 } 05681 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 05682 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 05683 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 05684 NewClassTy = NewRT->getPointeeType(); 05685 OldClassTy = OldRT->getPointeeType(); 05686 } 05687 } 05688 } 05689 05690 // The return types aren't either both pointers or references to a class type. 05691 if (NewClassTy.isNull()) { 05692 Diag(New->getLocation(), 05693 diag::err_different_return_type_for_overriding_virtual_function) 05694 << New->getDeclName() << NewTy << OldTy; 05695 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05696 05697 return true; 05698 } 05699 05700 // C++ [class.virtual]p6: 05701 // If the return type of D::f differs from the return type of B::f, the 05702 // class type in the return type of D::f shall be complete at the point of 05703 // declaration of D::f or shall be the class type D. 05704 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 05705 if (!RT->isBeingDefined() && 05706 RequireCompleteType(New->getLocation(), NewClassTy, 05707 PDiag(diag::err_covariant_return_incomplete) 05708 << New->getDeclName())) 05709 return true; 05710 } 05711 05712 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 05713 // Check if the new class derives from the old class. 05714 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 05715 Diag(New->getLocation(), 05716 diag::err_covariant_return_not_derived) 05717 << New->getDeclName() << NewTy << OldTy; 05718 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05719 return true; 05720 } 05721 05722 // Check if we the conversion from derived to base is valid. 05723 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance, 05724 diag::err_covariant_return_ambiguous_derived_to_base_conv, 05725 // FIXME: Should this point to the return type? 05726 New->getLocation(), SourceRange(), New->getDeclName())) { 05727 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05728 return true; 05729 } 05730 } 05731 05732 // The qualifiers of the return types must be the same. 05733 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 05734 Diag(New->getLocation(), 05735 diag::err_covariant_return_type_different_qualifications) 05736 << New->getDeclName() << NewTy << OldTy; 05737 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05738 return true; 05739 }; 05740 05741 05742 // The new class type must have the same or less qualifiers as the old type. 05743 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 05744 Diag(New->getLocation(), 05745 diag::err_covariant_return_type_class_type_more_qualified) 05746 << New->getDeclName() << NewTy << OldTy; 05747 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05748 return true; 05749 }; 05750 05751 return false; 05752 } 05753 05754 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 05755 const CXXMethodDecl *Old) 05756 { 05757 if (Old->hasAttr<FinalAttr>()) { 05758 Diag(New->getLocation(), diag::err_final_function_overridden) 05759 << New->getDeclName(); 05760 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05761 return true; 05762 } 05763 05764 return false; 05765 } 05766 05767 /// \brief Mark the given method pure. 05768 /// 05769 /// \param Method the method to be marked pure. 05770 /// 05771 /// \param InitRange the source range that covers the "0" initializer. 05772 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 05773 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 05774 Method->setPure(); 05775 05776 // A class is abstract if at least one function is pure virtual. 05777 Method->getParent()->setAbstract(true); 05778 return false; 05779 } 05780 05781 if (!Method->isInvalidDecl()) 05782 Diag(Method->getLocation(), diag::err_non_virtual_pure) 05783 << Method->getDeclName() << InitRange; 05784 return true; 05785 } 05786 05787 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 05788 /// an initializer for the out-of-line declaration 'Dcl'. The scope 05789 /// is a fresh scope pushed for just this purpose. 05790 /// 05791 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 05792 /// static data member of class X, names should be looked up in the scope of 05793 /// class X. 05794 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 05795 // If there is no declaration, there was an error parsing it. 05796 Decl *D = Dcl.getAs<Decl>(); 05797 if (D == 0) return; 05798 05799 // We should only get called for declarations with scope specifiers, like: 05800 // int foo::bar; 05801 assert(D->isOutOfLine()); 05802 EnterDeclaratorContext(S, D->getDeclContext()); 05803 } 05804 05805 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 05806 /// initializer for the out-of-line declaration 'Dcl'. 05807 void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 05808 // If there is no declaration, there was an error parsing it. 05809 Decl *D = Dcl.getAs<Decl>(); 05810 if (D == 0) return; 05811 05812 assert(D->isOutOfLine()); 05813 ExitDeclaratorContext(S); 05814 } 05815 05816 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 05817 /// C++ if/switch/while/for statement. 05818 /// e.g: "if (int x = f()) {...}" 05819 Action::DeclResult 05820 Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 05821 // C++ 6.4p2: 05822 // The declarator shall not specify a function or an array. 05823 // The type-specifier-seq shall not contain typedef and shall not declare a 05824 // new class or enumeration. 05825 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 05826 "Parser allowed 'typedef' as storage class of condition decl."); 05827 05828 TypeSourceInfo *TInfo = 0; 05829 TagDecl *OwnedTag = 0; 05830 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 05831 05832 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 05833 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 05834 // would be created and CXXConditionDeclExpr wants a VarDecl. 05835 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 05836 << D.getSourceRange(); 05837 return DeclResult(); 05838 } else if (OwnedTag && OwnedTag->isDefinition()) { 05839 // The type-specifier-seq shall not declare a new class or enumeration. 05840 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 05841 } 05842 05843 DeclPtrTy Dcl = ActOnDeclarator(S, D); 05844 if (!Dcl) 05845 return DeclResult(); 05846 05847 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 05848 VD->setDeclaredInCondition(true); 05849 return Dcl; 05850 } 05851 05852 static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) { 05853 // Ignore dependent types. 05854 if (MD->isDependentContext()) 05855 return false; 05856 05857 // Ignore declarations that are not definitions. 05858 if (!MD->isThisDeclarationADefinition()) 05859 return false; 05860 05861 CXXRecordDecl *RD = MD->getParent(); 05862 05863 // Ignore classes without a vtable. 05864 if (!RD->isDynamicClass()) 05865 return false; 05866 05867 switch (MD->getParent()->getTemplateSpecializationKind()) { 05868 case TSK_Undeclared: 05869 case TSK_ExplicitSpecialization: 05870 // Classes that aren't instantiations of templates don't need their 05871 // virtual methods marked until we see the definition of the key 05872 // function. 05873 break; 05874 05875 case TSK_ImplicitInstantiation: 05876 // This is a constructor of a class template; mark all of the virtual 05877 // members as referenced to ensure that they get instantiatied. 05878 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) 05879 return true; 05880 break; 05881 05882 case TSK_ExplicitInstantiationDeclaration: 05883 return true; //FIXME: This looks wrong. 05884 05885 case TSK_ExplicitInstantiationDefinition: 05886 // This is method of a explicit instantiation; mark all of the virtual 05887 // members as referenced to ensure that they get instantiatied. 05888 return true; 05889 } 05890 05891 // Consider only out-of-line definitions of member functions. When we see 05892 // an inline definition, it's too early to compute the key function. 05893 if (!MD->isOutOfLine()) 05894 return false; 05895 05896 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD); 05897 05898 // If there is no key function, we will need a copy of the vtable. 05899 if (!KeyFunction) 05900 return true; 05901 05902 // If this is the key function, we need to mark virtual members. 05903 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 05904 return true; 05905 05906 return false; 05907 } 05908 05909 void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc, 05910 CXXMethodDecl *MD) { 05911 CXXRecordDecl *RD = MD->getParent(); 05912 05913 // We will need to mark all of the virtual members as referenced to build the 05914 // vtable. 05915 if (!needsVtable(MD, Context)) 05916 return; 05917 05918 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind(); 05919 if (kind == TSK_ImplicitInstantiation) 05920 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc)); 05921 else 05922 MarkVirtualMembersReferenced(Loc, RD); 05923 } 05924 05925 bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() { 05926 if (ClassesWithUnmarkedVirtualMembers.empty()) 05927 return false; 05928 05929 while (!ClassesWithUnmarkedVirtualMembers.empty()) { 05930 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first; 05931 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second; 05932 ClassesWithUnmarkedVirtualMembers.pop_back(); 05933 MarkVirtualMembersReferenced(Loc, RD); 05934 } 05935 05936 return true; 05937 } 05938 05939 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) { 05940 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 05941 e = RD->method_end(); i != e; ++i) { 05942 CXXMethodDecl *MD = *i; 05943 05944 // C++ [basic.def.odr]p2: 05945 // [...] A virtual member function is used if it is not pure. [...] 05946 if (MD->isVirtual() && !MD->isPure()) 05947 MarkDeclarationReferenced(Loc, MD); 05948 } 05949 }