SemaDeclCXX.cpp revision 9351c173cd538f7f7c28af1494ac7e68b815b0e8
1e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// 3e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// The LLVM Compiler Infrastructure 4e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// 5e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// This file is distributed under the University of Illinois Open Source 6e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// License. See LICENSE.TXT for details. 7e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// 8e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian//===----------------------------------------------------------------------===// 9e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// 10e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// This file implements semantic analysis for C++ declarations. 11e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// 12e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian//===----------------------------------------------------------------------===// 13e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 14e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian#include "Sema.h" 15e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian#include "SemaInherit.h" 16e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian#include "clang/AST/ASTConsumer.h" 17bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/AST/ASTContext.h" 18bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/AST/DeclVisitor.h" 19bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/AST/TypeOrdering.h" 20bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/AST/StmtVisitor.h" 21bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/Lex/Preprocessor.h" 22bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "clang/Parse/DeclSpec.h" 23bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "llvm/ADT/STLExtras.h" 24bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine#include "llvm/Support/Compiler.h" 25e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian#include <algorithm> // for std::equal 26e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian#include <map> 27e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 28e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopianusing namespace clang; 29e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 30e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian//===----------------------------------------------------------------------===// 31e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian// CheckDefaultArgumentVisitor 32e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian//===----------------------------------------------------------------------===// 33e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 34e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopiannamespace { 35e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 36bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine /// the default argument of a parameter to determine whether it 37bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine /// contains any ill-formed subexpressions. For example, this will 38bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine /// diagnose the use of local variables or parameters within the 39bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine /// default argument expression. 40e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 41e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 42bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine Expr *DefaultArg; 43bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine Sema *S; 44bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine 45e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian public: 46bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 47e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian : DefaultArg(defarg), S(s) {} 48e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 49e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool VisitExpr(Expr *Node); 50e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool VisitDeclRefExpr(DeclRefExpr *DRE); 51e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool VisitCXXThisExpr(CXXThisExpr *ThisE); 52bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine }; 53e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 54e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian /// VisitExpr - Visit all of the children of this expression. 55e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 56e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool IsInvalid = false; 57e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian for (Stmt::child_iterator I = Node->child_begin(), 58bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine E = Node->child_end(); I != E; ++I) 59e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian IsInvalid |= Visit(*I); 60e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return IsInvalid; 61e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian } 62e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 63e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian /// VisitDeclRefExpr - Visit a reference to a declaration, to 64e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian /// determine whether this declaration can be used in the default 65bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine /// argument expression. 66e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 67e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian NamedDecl *Decl = DRE->getDecl(); 68e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 69e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // C++ [dcl.fct.default]p9 70e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // Default arguments are evaluated each time the function is 71bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // called. The order of evaluation of function arguments is 72e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // unspecified. Consequently, parameters of a function shall not 73e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // be used in default argument expressions, even if they are not 74e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // evaluated. Parameters of a function declared before a default 75e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // argument expression are in scope and can hide namespace and 76e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // class member names. 77e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return S->Diag(DRE->getSourceRange().getBegin(), 78bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine diag::err_param_default_argument_references_param) 79e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian << Param->getDeclName() << DefaultArg->getSourceRange(); 80e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 81e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // C++ [dcl.fct.default]p7 82e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // Local variables shall not be used in default argument 83e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // expressions. 84e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian if (VDecl->isBlockVarDecl()) 85bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine return S->Diag(DRE->getSourceRange().getBegin(), 86e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian diag::err_param_default_argument_references_local) 87e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian << VDecl->getDeclName() << DefaultArg->getSourceRange(); 88e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian } 89e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 90e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return false; 91bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine } 92e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 93e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian /// VisitCXXThisExpr - Visit a C++ "this" expression. 94e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 95e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // C++ [dcl.fct.default]p8: 96e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // The keyword this shall not be used in a default argument of a 97e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // member function. 98e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return S->Diag(ThisE->getSourceRange().getBegin(), 99e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian diag::err_param_default_argument_references_this) 100e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian << ThisE->getSourceRange(); 101e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian } 102e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian} 103e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 104e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopianbool 105e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias AgopianSema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 106e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian SourceLocation EqualLoc) 107e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian{ 108e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian QualType ParamType = Param->getType(); 109e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 110e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian Expr *Arg = (Expr *)DefaultArg.get(); 111e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 112bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // C++ [dcl.fct.default]p5 113bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // A default argument expression is implicitly converted (clause 114bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // 4) to the parameter type. The default argument expression has 115bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // the same semantic constraints as the initializer expression in 116bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // a declaration of a variable of the parameter type, using the 117bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine // copy-initialization semantics (8.5). 118bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 119bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine Param->getDeclName(), /*DirectInit=*/false)) 120bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine return true; 121bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine 122e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 123e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 124e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // Okay: add the default argument to the parameter 125e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian Param->setDefaultArg(Arg); 126e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 127e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian DefaultArg.release(); 128e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 129e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return false; 130e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian} 131e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 132e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian/// ActOnParamDefaultArgument - Check whether the default argument 133e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian/// provided for a function parameter is well-formed. If so, attach it 134e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian/// to the parameter declaration. 135e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopianvoid 136e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias AgopianSema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 137e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian ExprArg defarg) { 138e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian if (!param || !defarg.get()) 139e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return; 140e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 141e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 142e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian UnparsedDefaultArgLocs.erase(Param); 143e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 144e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 145e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian QualType ParamType = Param->getType(); 146e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian 147e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian // Default arguments are only permitted in C++ 148e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian if (!getLangOptions().CPlusPlus) { 149e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian Diag(EqualLoc, diag::err_param_default_argument) 150e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian << DefaultArg->getSourceRange(); 151e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian Param->setInvalidDecl(); 152e1c61d3cc8458ce9a15d8109f728e60f5248939dMathias Agopian return; 153bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine } 154bf6d5e012cd9b15568c2351831f3349cf564bf18Johan Euphrosine 155 // Check that the default argument is well-formed 156 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 157 if (DefaultArgChecker.Visit(DefaultArg.get())) { 158 Param->setInvalidDecl(); 159 return; 160 } 161 162 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 163} 164 165/// ActOnParamUnparsedDefaultArgument - We've seen a default 166/// argument for a function parameter, but we can't parse it yet 167/// because we're inside a class definition. Note that this default 168/// argument will be parsed later. 169void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 170 SourceLocation EqualLoc, 171 SourceLocation ArgLoc) { 172 if (!param) 173 return; 174 175 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 176 if (Param) 177 Param->setUnparsedDefaultArg(); 178 179 UnparsedDefaultArgLocs[Param] = ArgLoc; 180} 181 182/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 183/// the default argument for the parameter param failed. 184void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 185 if (!param) 186 return; 187 188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 189 190 Param->setInvalidDecl(); 191 192 UnparsedDefaultArgLocs.erase(Param); 193} 194 195/// CheckExtraCXXDefaultArguments - Check for any extra default 196/// arguments in the declarator, which is not a function declaration 197/// or definition and therefore is not permitted to have default 198/// arguments. This routine should be invoked for every declarator 199/// that is not a function declaration or definition. 200void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 201 // C++ [dcl.fct.default]p3 202 // A default argument expression shall be specified only in the 203 // parameter-declaration-clause of a function declaration or in a 204 // template-parameter (14.1). It shall not be specified for a 205 // parameter pack. If it is specified in a 206 // parameter-declaration-clause, it shall not occur within a 207 // declarator or abstract-declarator of a parameter-declaration. 208 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 209 DeclaratorChunk &chunk = D.getTypeObject(i); 210 if (chunk.Kind == DeclaratorChunk::Function) { 211 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 212 ParmVarDecl *Param = 213 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 214 if (Param->hasUnparsedDefaultArg()) { 215 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 216 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 217 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 218 delete Toks; 219 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 220 } else if (Param->getDefaultArg()) { 221 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 222 << Param->getDefaultArg()->getSourceRange(); 223 Param->setDefaultArg(0); 224 } 225 } 226 } 227 } 228} 229 230// MergeCXXFunctionDecl - Merge two declarations of the same C++ 231// function, once we already know that they have the same 232// type. Subroutine of MergeFunctionDecl. Returns true if there was an 233// error, false otherwise. 234bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 235 bool Invalid = false; 236 237 // C++ [dcl.fct.default]p4: 238 // 239 // For non-template functions, default arguments can be added in 240 // later declarations of a function in the same 241 // scope. Declarations in different scopes have completely 242 // distinct sets of default arguments. That is, declarations in 243 // inner scopes do not acquire default arguments from 244 // declarations in outer scopes, and vice versa. In a given 245 // function declaration, all parameters subsequent to a 246 // parameter with a default argument shall have default 247 // arguments supplied in this or previous declarations. A 248 // default argument shall not be redefined by a later 249 // declaration (not even to the same value). 250 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 251 ParmVarDecl *OldParam = Old->getParamDecl(p); 252 ParmVarDecl *NewParam = New->getParamDecl(p); 253 254 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 255 Diag(NewParam->getLocation(), 256 diag::err_param_default_argument_redefinition) 257 << NewParam->getDefaultArg()->getSourceRange(); 258 Diag(OldParam->getLocation(), diag::note_previous_definition); 259 Invalid = true; 260 } else if (OldParam->getDefaultArg()) { 261 // Merge the old default argument into the new parameter 262 NewParam->setDefaultArg(OldParam->getDefaultArg()); 263 } 264 } 265 266 if (CheckEquivalentExceptionSpec( 267 Old->getType()->getAsFunctionProtoType(), Old->getLocation(), 268 New->getType()->getAsFunctionProtoType(), New->getLocation())) { 269 Invalid = true; 270 } 271 272 return Invalid; 273} 274 275/// CheckCXXDefaultArguments - Verify that the default arguments for a 276/// function declaration are well-formed according to C++ 277/// [dcl.fct.default]. 278void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 279 unsigned NumParams = FD->getNumParams(); 280 unsigned p; 281 282 // Find first parameter with a default argument 283 for (p = 0; p < NumParams; ++p) { 284 ParmVarDecl *Param = FD->getParamDecl(p); 285 if (Param->hasDefaultArg()) 286 break; 287 } 288 289 // C++ [dcl.fct.default]p4: 290 // In a given function declaration, all parameters 291 // subsequent to a parameter with a default argument shall 292 // have default arguments supplied in this or previous 293 // declarations. A default argument shall not be redefined 294 // by a later declaration (not even to the same value). 295 unsigned LastMissingDefaultArg = 0; 296 for(; p < NumParams; ++p) { 297 ParmVarDecl *Param = FD->getParamDecl(p); 298 if (!Param->hasDefaultArg()) { 299 if (Param->isInvalidDecl()) 300 /* We already complained about this parameter. */; 301 else if (Param->getIdentifier()) 302 Diag(Param->getLocation(), 303 diag::err_param_default_argument_missing_name) 304 << Param->getIdentifier(); 305 else 306 Diag(Param->getLocation(), 307 diag::err_param_default_argument_missing); 308 309 LastMissingDefaultArg = p; 310 } 311 } 312 313 if (LastMissingDefaultArg > 0) { 314 // Some default arguments were missing. Clear out all of the 315 // default arguments up to (and including) the last missing 316 // default argument, so that we leave the function parameters 317 // in a semantically valid state. 318 for (p = 0; p <= LastMissingDefaultArg; ++p) { 319 ParmVarDecl *Param = FD->getParamDecl(p); 320 if (Param->hasDefaultArg()) { 321 if (!Param->hasUnparsedDefaultArg()) 322 Param->getDefaultArg()->Destroy(Context); 323 Param->setDefaultArg(0); 324 } 325 } 326 } 327} 328 329/// isCurrentClassName - Determine whether the identifier II is the 330/// name of the class type currently being defined. In the case of 331/// nested classes, this will only return true if II is the name of 332/// the innermost class. 333bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 334 const CXXScopeSpec *SS) { 335 CXXRecordDecl *CurDecl; 336 if (SS && SS->isSet() && !SS->isInvalid()) { 337 DeclContext *DC = computeDeclContext(*SS, true); 338 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 339 } else 340 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 341 342 if (CurDecl) 343 return &II == CurDecl->getIdentifier(); 344 else 345 return false; 346} 347 348/// \brief Check the validity of a C++ base class specifier. 349/// 350/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 351/// and returns NULL otherwise. 352CXXBaseSpecifier * 353Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 354 SourceRange SpecifierRange, 355 bool Virtual, AccessSpecifier Access, 356 QualType BaseType, 357 SourceLocation BaseLoc) { 358 // C++ [class.union]p1: 359 // A union shall not have base classes. 360 if (Class->isUnion()) { 361 Diag(Class->getLocation(), diag::err_base_clause_on_union) 362 << SpecifierRange; 363 return 0; 364 } 365 366 if (BaseType->isDependentType()) 367 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 368 Class->getTagKind() == RecordDecl::TK_class, 369 Access, BaseType); 370 371 // Base specifiers must be record types. 372 if (!BaseType->isRecordType()) { 373 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 374 return 0; 375 } 376 377 // C++ [class.union]p1: 378 // A union shall not be used as a base class. 379 if (BaseType->isUnionType()) { 380 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 381 return 0; 382 } 383 384 // C++ [class.derived]p2: 385 // The class-name in a base-specifier shall not be an incompletely 386 // defined class. 387 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class, 388 SpecifierRange)) 389 return 0; 390 391 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 392 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 393 assert(BaseDecl && "Record type has no declaration"); 394 BaseDecl = BaseDecl->getDefinition(Context); 395 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 396 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 397 assert(CXXBaseDecl && "Base type is not a C++ type"); 398 if (!CXXBaseDecl->isEmpty()) 399 Class->setEmpty(false); 400 if (CXXBaseDecl->isPolymorphic()) 401 Class->setPolymorphic(true); 402 403 // C++ [dcl.init.aggr]p1: 404 // An aggregate is [...] a class with [...] no base classes [...]. 405 Class->setAggregate(false); 406 Class->setPOD(false); 407 408 if (Virtual) { 409 // C++ [class.ctor]p5: 410 // A constructor is trivial if its class has no virtual base classes. 411 Class->setHasTrivialConstructor(false); 412 413 // C++ [class.copy]p6: 414 // A copy constructor is trivial if its class has no virtual base classes. 415 Class->setHasTrivialCopyConstructor(false); 416 417 // C++ [class.copy]p11: 418 // A copy assignment operator is trivial if its class has no virtual 419 // base classes. 420 Class->setHasTrivialCopyAssignment(false); 421 422 // C++0x [meta.unary.prop] is_empty: 423 // T is a class type, but not a union type, with ... no virtual base 424 // classes 425 Class->setEmpty(false); 426 } else { 427 // C++ [class.ctor]p5: 428 // A constructor is trivial if all the direct base classes of its 429 // class have trivial constructors. 430 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 431 Class->setHasTrivialConstructor(false); 432 433 // C++ [class.copy]p6: 434 // A copy constructor is trivial if all the direct base classes of its 435 // class have trivial copy constructors. 436 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 437 Class->setHasTrivialCopyConstructor(false); 438 439 // C++ [class.copy]p11: 440 // A copy assignment operator is trivial if all the direct base classes 441 // of its class have trivial copy assignment operators. 442 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 443 Class->setHasTrivialCopyAssignment(false); 444 } 445 446 // C++ [class.ctor]p3: 447 // A destructor is trivial if all the direct base classes of its class 448 // have trivial destructors. 449 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 450 Class->setHasTrivialDestructor(false); 451 452 // Create the base specifier. 453 // FIXME: Allocate via ASTContext? 454 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 455 Class->getTagKind() == RecordDecl::TK_class, 456 Access, BaseType); 457} 458 459/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 460/// one entry in the base class list of a class specifier, for 461/// example: 462/// class foo : public bar, virtual private baz { 463/// 'public bar' and 'virtual private baz' are each base-specifiers. 464Sema::BaseResult 465Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 466 bool Virtual, AccessSpecifier Access, 467 TypeTy *basetype, SourceLocation BaseLoc) { 468 if (!classdecl) 469 return true; 470 471 AdjustDeclIfTemplate(classdecl); 472 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 473 QualType BaseType = GetTypeFromParser(basetype); 474 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 475 Virtual, Access, 476 BaseType, BaseLoc)) 477 return BaseSpec; 478 479 return true; 480} 481 482/// \brief Performs the actual work of attaching the given base class 483/// specifiers to a C++ class. 484bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 485 unsigned NumBases) { 486 if (NumBases == 0) 487 return false; 488 489 // Used to keep track of which base types we have already seen, so 490 // that we can properly diagnose redundant direct base types. Note 491 // that the key is always the unqualified canonical type of the base 492 // class. 493 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 494 495 // Copy non-redundant base specifiers into permanent storage. 496 unsigned NumGoodBases = 0; 497 bool Invalid = false; 498 for (unsigned idx = 0; idx < NumBases; ++idx) { 499 QualType NewBaseType 500 = Context.getCanonicalType(Bases[idx]->getType()); 501 NewBaseType = NewBaseType.getUnqualifiedType(); 502 503 if (KnownBaseTypes[NewBaseType]) { 504 // C++ [class.mi]p3: 505 // A class shall not be specified as a direct base class of a 506 // derived class more than once. 507 Diag(Bases[idx]->getSourceRange().getBegin(), 508 diag::err_duplicate_base_class) 509 << KnownBaseTypes[NewBaseType]->getType() 510 << Bases[idx]->getSourceRange(); 511 512 // Delete the duplicate base class specifier; we're going to 513 // overwrite its pointer later. 514 Context.Deallocate(Bases[idx]); 515 516 Invalid = true; 517 } else { 518 // Okay, add this new base class. 519 KnownBaseTypes[NewBaseType] = Bases[idx]; 520 Bases[NumGoodBases++] = Bases[idx]; 521 } 522 } 523 524 // Attach the remaining base class specifiers to the derived class. 525 Class->setBases(Context, Bases, NumGoodBases); 526 527 // Delete the remaining (good) base class specifiers, since their 528 // data has been copied into the CXXRecordDecl. 529 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 530 Context.Deallocate(Bases[idx]); 531 532 return Invalid; 533} 534 535/// ActOnBaseSpecifiers - Attach the given base specifiers to the 536/// class, after checking whether there are any duplicate base 537/// classes. 538void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 539 unsigned NumBases) { 540 if (!ClassDecl || !Bases || !NumBases) 541 return; 542 543 AdjustDeclIfTemplate(ClassDecl); 544 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 545 (CXXBaseSpecifier**)(Bases), NumBases); 546} 547 548//===----------------------------------------------------------------------===// 549// C++ class member Handling 550//===----------------------------------------------------------------------===// 551 552/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 553/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 554/// bitfield width if there is one and 'InitExpr' specifies the initializer if 555/// any. 556Sema::DeclPtrTy 557Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 558 MultiTemplateParamsArg TemplateParameterLists, 559 ExprTy *BW, ExprTy *InitExpr, bool Deleted) { 560 const DeclSpec &DS = D.getDeclSpec(); 561 DeclarationName Name = GetNameForDeclarator(D); 562 Expr *BitWidth = static_cast<Expr*>(BW); 563 Expr *Init = static_cast<Expr*>(InitExpr); 564 SourceLocation Loc = D.getIdentifierLoc(); 565 566 bool isFunc = D.isFunctionDeclarator(); 567 568 assert(!DS.isFriendSpecified()); 569 570 // C++ 9.2p6: A member shall not be declared to have automatic storage 571 // duration (auto, register) or with the extern storage-class-specifier. 572 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 573 // data members and cannot be applied to names declared const or static, 574 // and cannot be applied to reference members. 575 switch (DS.getStorageClassSpec()) { 576 case DeclSpec::SCS_unspecified: 577 case DeclSpec::SCS_typedef: 578 case DeclSpec::SCS_static: 579 // FALL THROUGH. 580 break; 581 case DeclSpec::SCS_mutable: 582 if (isFunc) { 583 if (DS.getStorageClassSpecLoc().isValid()) 584 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 585 else 586 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 587 588 // FIXME: It would be nicer if the keyword was ignored only for this 589 // declarator. Otherwise we could get follow-up errors. 590 D.getMutableDeclSpec().ClearStorageClassSpecs(); 591 } else { 592 QualType T = GetTypeForDeclarator(D, S); 593 diag::kind err = static_cast<diag::kind>(0); 594 if (T->isReferenceType()) 595 err = diag::err_mutable_reference; 596 else if (T.isConstQualified()) 597 err = diag::err_mutable_const; 598 if (err != 0) { 599 if (DS.getStorageClassSpecLoc().isValid()) 600 Diag(DS.getStorageClassSpecLoc(), err); 601 else 602 Diag(DS.getThreadSpecLoc(), err); 603 // FIXME: It would be nicer if the keyword was ignored only for this 604 // declarator. Otherwise we could get follow-up errors. 605 D.getMutableDeclSpec().ClearStorageClassSpecs(); 606 } 607 } 608 break; 609 default: 610 if (DS.getStorageClassSpecLoc().isValid()) 611 Diag(DS.getStorageClassSpecLoc(), 612 diag::err_storageclass_invalid_for_member); 613 else 614 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 615 D.getMutableDeclSpec().ClearStorageClassSpecs(); 616 } 617 618 if (!isFunc && 619 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 620 D.getNumTypeObjects() == 0) { 621 // Check also for this case: 622 // 623 // typedef int f(); 624 // f a; 625 // 626 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 627 isFunc = TDType->isFunctionType(); 628 } 629 630 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 631 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 632 !isFunc); 633 634 Decl *Member; 635 if (isInstField) { 636 // FIXME: Check for template parameters! 637 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 638 AS); 639 assert(Member && "HandleField never returns null"); 640 } else { 641 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false) 642 .getAs<Decl>(); 643 if (!Member) { 644 if (BitWidth) DeleteExpr(BitWidth); 645 return DeclPtrTy(); 646 } 647 648 // Non-instance-fields can't have a bitfield. 649 if (BitWidth) { 650 if (Member->isInvalidDecl()) { 651 // don't emit another diagnostic. 652 } else if (isa<VarDecl>(Member)) { 653 // C++ 9.6p3: A bit-field shall not be a static member. 654 // "static member 'A' cannot be a bit-field" 655 Diag(Loc, diag::err_static_not_bitfield) 656 << Name << BitWidth->getSourceRange(); 657 } else if (isa<TypedefDecl>(Member)) { 658 // "typedef member 'x' cannot be a bit-field" 659 Diag(Loc, diag::err_typedef_not_bitfield) 660 << Name << BitWidth->getSourceRange(); 661 } else { 662 // A function typedef ("typedef int f(); f a;"). 663 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 664 Diag(Loc, diag::err_not_integral_type_bitfield) 665 << Name << cast<ValueDecl>(Member)->getType() 666 << BitWidth->getSourceRange(); 667 } 668 669 DeleteExpr(BitWidth); 670 BitWidth = 0; 671 Member->setInvalidDecl(); 672 } 673 674 Member->setAccess(AS); 675 676 // If we have declared a member function template, set the access of the 677 // templated declaration as well. 678 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 679 FunTmpl->getTemplatedDecl()->setAccess(AS); 680 } 681 682 assert((Name || isInstField) && "No identifier for non-field ?"); 683 684 if (Init) 685 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 686 if (Deleted) // FIXME: Source location is not very good. 687 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 688 689 if (isInstField) { 690 FieldCollector->Add(cast<FieldDecl>(Member)); 691 return DeclPtrTy(); 692 } 693 return DeclPtrTy::make(Member); 694} 695 696/// ActOnMemInitializer - Handle a C++ member initializer. 697Sema::MemInitResult 698Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 699 Scope *S, 700 const CXXScopeSpec &SS, 701 IdentifierInfo *MemberOrBase, 702 TypeTy *TemplateTypeTy, 703 SourceLocation IdLoc, 704 SourceLocation LParenLoc, 705 ExprTy **Args, unsigned NumArgs, 706 SourceLocation *CommaLocs, 707 SourceLocation RParenLoc) { 708 if (!ConstructorD) 709 return true; 710 711 AdjustDeclIfTemplate(ConstructorD); 712 713 CXXConstructorDecl *Constructor 714 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 715 if (!Constructor) { 716 // The user wrote a constructor initializer on a function that is 717 // not a C++ constructor. Ignore the error for now, because we may 718 // have more member initializers coming; we'll diagnose it just 719 // once in ActOnMemInitializers. 720 return true; 721 } 722 723 CXXRecordDecl *ClassDecl = Constructor->getParent(); 724 725 // C++ [class.base.init]p2: 726 // Names in a mem-initializer-id are looked up in the scope of the 727 // constructor’s class and, if not found in that scope, are looked 728 // up in the scope containing the constructor’s 729 // definition. [Note: if the constructor’s class contains a member 730 // with the same name as a direct or virtual base class of the 731 // class, a mem-initializer-id naming the member or base class and 732 // composed of a single identifier refers to the class member. A 733 // mem-initializer-id for the hidden base class may be specified 734 // using a qualified name. ] 735 if (!SS.getScopeRep() && !TemplateTypeTy) { 736 // Look for a member, first. 737 FieldDecl *Member = 0; 738 DeclContext::lookup_result Result 739 = ClassDecl->lookup(MemberOrBase); 740 if (Result.first != Result.second) 741 Member = dyn_cast<FieldDecl>(*Result.first); 742 743 // FIXME: Handle members of an anonymous union. 744 745 if (Member) 746 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 747 RParenLoc); 748 } 749 // It didn't name a member, so see if it names a class. 750 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 751 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 752 if (!BaseTy) 753 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 754 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 755 756 QualType BaseType = GetTypeFromParser(BaseTy); 757 758 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 759 RParenLoc, ClassDecl); 760} 761 762Sema::MemInitResult 763Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 764 unsigned NumArgs, SourceLocation IdLoc, 765 SourceLocation RParenLoc) { 766 bool HasDependentArg = false; 767 for (unsigned i = 0; i < NumArgs; i++) 768 HasDependentArg |= Args[i]->isTypeDependent(); 769 770 CXXConstructorDecl *C = 0; 771 QualType FieldType = Member->getType(); 772 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 773 FieldType = Array->getElementType(); 774 if (FieldType->isDependentType()) { 775 // Can't check init for dependent type. 776 } else if (FieldType->getAs<RecordType>()) { 777 if (!HasDependentArg) 778 C = PerformInitializationByConstructor( 779 FieldType, (Expr **)Args, NumArgs, IdLoc, 780 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct); 781 } else if (NumArgs != 1) { 782 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 783 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 784 } else if (!HasDependentArg) { 785 Expr *NewExp = (Expr*)Args[0]; 786 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 787 return true; 788 Args[0] = NewExp; 789 } 790 // FIXME: Perform direct initialization of the member. 791 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 792 NumArgs, C, IdLoc); 793} 794 795Sema::MemInitResult 796Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 797 unsigned NumArgs, SourceLocation IdLoc, 798 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 799 bool HasDependentArg = false; 800 for (unsigned i = 0; i < NumArgs; i++) 801 HasDependentArg |= Args[i]->isTypeDependent(); 802 803 if (!BaseType->isDependentType()) { 804 if (!BaseType->isRecordType()) 805 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 806 << BaseType << SourceRange(IdLoc, RParenLoc); 807 808 // C++ [class.base.init]p2: 809 // [...] Unless the mem-initializer-id names a nonstatic data 810 // member of the constructor’s class or a direct or virtual base 811 // of that class, the mem-initializer is ill-formed. A 812 // mem-initializer-list can initialize a base class using any 813 // name that denotes that base class type. 814 815 // First, check for a direct base class. 816 const CXXBaseSpecifier *DirectBaseSpec = 0; 817 for (CXXRecordDecl::base_class_const_iterator Base = 818 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 819 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 820 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 821 // We found a direct base of this type. That's what we're 822 // initializing. 823 DirectBaseSpec = &*Base; 824 break; 825 } 826 } 827 828 // Check for a virtual base class. 829 // FIXME: We might be able to short-circuit this if we know in advance that 830 // there are no virtual bases. 831 const CXXBaseSpecifier *VirtualBaseSpec = 0; 832 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 833 // We haven't found a base yet; search the class hierarchy for a 834 // virtual base class. 835 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 836 /*DetectVirtual=*/false); 837 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 838 for (BasePaths::paths_iterator Path = Paths.begin(); 839 Path != Paths.end(); ++Path) { 840 if (Path->back().Base->isVirtual()) { 841 VirtualBaseSpec = Path->back().Base; 842 break; 843 } 844 } 845 } 846 } 847 848 // C++ [base.class.init]p2: 849 // If a mem-initializer-id is ambiguous because it designates both 850 // a direct non-virtual base class and an inherited virtual base 851 // class, the mem-initializer is ill-formed. 852 if (DirectBaseSpec && VirtualBaseSpec) 853 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 854 << BaseType << SourceRange(IdLoc, RParenLoc); 855 // C++ [base.class.init]p2: 856 // Unless the mem-initializer-id names a nonstatic data membeer of the 857 // constructor's class ot a direst or virtual base of that class, the 858 // mem-initializer is ill-formed. 859 if (!DirectBaseSpec && !VirtualBaseSpec) 860 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 861 << BaseType << ClassDecl->getNameAsCString() 862 << SourceRange(IdLoc, RParenLoc); 863 } 864 865 CXXConstructorDecl *C = 0; 866 if (!BaseType->isDependentType() && !HasDependentArg) { 867 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 868 Context.getCanonicalType(BaseType)); 869 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs, 870 IdLoc, SourceRange(IdLoc, RParenLoc), 871 Name, IK_Direct); 872 } 873 874 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 875 NumArgs, C, IdLoc); 876} 877 878void 879Sema::BuildBaseOrMemberInitializers(ASTContext &C, 880 CXXConstructorDecl *Constructor, 881 CXXBaseOrMemberInitializer **Initializers, 882 unsigned NumInitializers 883 ) { 884 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases; 885 llvm::SmallVector<FieldDecl *, 4>Members; 886 887 Constructor->setBaseOrMemberInitializers(C, 888 Initializers, NumInitializers, 889 Bases, Members); 890 for (unsigned int i = 0; i < Bases.size(); i++) 891 Diag(Bases[i]->getSourceRange().getBegin(), 892 diag::err_missing_default_constructor) << 0 << Bases[i]->getType(); 893 for (unsigned int i = 0; i < Members.size(); i++) 894 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor) 895 << 1 << Members[i]->getType(); 896} 897 898static void *GetKeyForTopLevelField(FieldDecl *Field) { 899 // For anonymous unions, use the class declaration as the key. 900 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 901 if (RT->getDecl()->isAnonymousStructOrUnion()) 902 return static_cast<void *>(RT->getDecl()); 903 } 904 return static_cast<void *>(Field); 905} 906 907static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 908 bool MemberMaybeAnon=false) { 909 // For fields injected into the class via declaration of an anonymous union, 910 // use its anonymous union class declaration as the unique key. 911 if (FieldDecl *Field = Member->getMember()) { 912 // After BuildBaseOrMemberInitializers call, Field is the anonymous union 913 // data member of the class. Data member used in the initializer list is 914 // in AnonUnionMember field. 915 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 916 Field = Member->getAnonUnionMember(); 917 if (Field->getDeclContext()->isRecord()) { 918 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 919 if (RD->isAnonymousStructOrUnion()) 920 return static_cast<void *>(RD); 921 } 922 return static_cast<void *>(Field); 923 } 924 return static_cast<RecordType *>(Member->getBaseClass()); 925} 926 927void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 928 SourceLocation ColonLoc, 929 MemInitTy **MemInits, unsigned NumMemInits) { 930 if (!ConstructorDecl) 931 return; 932 933 AdjustDeclIfTemplate(ConstructorDecl); 934 935 CXXConstructorDecl *Constructor 936 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 937 938 if (!Constructor) { 939 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 940 return; 941 } 942 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 943 bool err = false; 944 for (unsigned i = 0; i < NumMemInits; i++) { 945 CXXBaseOrMemberInitializer *Member = 946 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 947 void *KeyToMember = GetKeyForMember(Member); 948 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 949 if (!PrevMember) { 950 PrevMember = Member; 951 continue; 952 } 953 if (FieldDecl *Field = Member->getMember()) 954 Diag(Member->getSourceLocation(), 955 diag::error_multiple_mem_initialization) 956 << Field->getNameAsString(); 957 else { 958 Type *BaseClass = Member->getBaseClass(); 959 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 960 Diag(Member->getSourceLocation(), 961 diag::error_multiple_base_initialization) 962 << BaseClass->getDesugaredType(true); 963 } 964 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 965 << 0; 966 err = true; 967 } 968 if (!err) 969 BuildBaseOrMemberInitializers(Context, Constructor, 970 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 971 NumMemInits); 972 973 if (!err && (Diags.getDiagnosticLevel(diag::warn_base_initialized) 974 != Diagnostic::Ignored || 975 Diags.getDiagnosticLevel(diag::warn_field_initialized) 976 != Diagnostic::Ignored)) { 977 // Also issue warning if order of ctor-initializer list does not match order 978 // of 1) base class declarations and 2) order of non-static data members. 979 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 980 981 CXXRecordDecl *ClassDecl 982 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 983 // Push virtual bases before others. 984 for (CXXRecordDecl::base_class_iterator VBase = 985 ClassDecl->vbases_begin(), 986 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 987 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>()); 988 989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 990 E = ClassDecl->bases_end(); Base != E; ++Base) { 991 // Virtuals are alread in the virtual base list and are constructed 992 // first. 993 if (Base->isVirtual()) 994 continue; 995 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>()); 996 } 997 998 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 999 E = ClassDecl->field_end(); Field != E; ++Field) 1000 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1001 1002 int Last = AllBaseOrMembers.size(); 1003 int curIndex = 0; 1004 CXXBaseOrMemberInitializer *PrevMember = 0; 1005 for (unsigned i = 0; i < NumMemInits; i++) { 1006 CXXBaseOrMemberInitializer *Member = 1007 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1008 void *MemberInCtorList = GetKeyForMember(Member, true); 1009 1010 for (; curIndex < Last; curIndex++) 1011 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1012 break; 1013 if (curIndex == Last) { 1014 assert(PrevMember && "Member not in member list?!"); 1015 // Initializer as specified in ctor-initializer list is out of order. 1016 // Issue a warning diagnostic. 1017 if (PrevMember->isBaseInitializer()) { 1018 // Diagnostics is for an initialized base class. 1019 Type *BaseClass = PrevMember->getBaseClass(); 1020 Diag(PrevMember->getSourceLocation(), 1021 diag::warn_base_initialized) 1022 << BaseClass->getDesugaredType(true); 1023 } else { 1024 FieldDecl *Field = PrevMember->getMember(); 1025 Diag(PrevMember->getSourceLocation(), 1026 diag::warn_field_initialized) 1027 << Field->getNameAsString(); 1028 } 1029 // Also the note! 1030 if (FieldDecl *Field = Member->getMember()) 1031 Diag(Member->getSourceLocation(), 1032 diag::note_fieldorbase_initialized_here) << 0 1033 << Field->getNameAsString(); 1034 else { 1035 Type *BaseClass = Member->getBaseClass(); 1036 Diag(Member->getSourceLocation(), 1037 diag::note_fieldorbase_initialized_here) << 1 1038 << BaseClass->getDesugaredType(true); 1039 } 1040 for (curIndex = 0; curIndex < Last; curIndex++) 1041 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1042 break; 1043 } 1044 PrevMember = Member; 1045 } 1046 } 1047} 1048 1049void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1050 if (!CDtorDecl) 1051 return; 1052 1053 AdjustDeclIfTemplate(CDtorDecl); 1054 1055 if (CXXConstructorDecl *Constructor 1056 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1057 BuildBaseOrMemberInitializers(Context, 1058 Constructor, 1059 (CXXBaseOrMemberInitializer **)0, 0); 1060} 1061 1062namespace { 1063 /// PureVirtualMethodCollector - traverses a class and its superclasses 1064 /// and determines if it has any pure virtual methods. 1065 class VISIBILITY_HIDDEN PureVirtualMethodCollector { 1066 ASTContext &Context; 1067 1068 public: 1069 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1070 1071 private: 1072 MethodList Methods; 1073 1074 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1075 1076 public: 1077 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1078 : Context(Ctx) { 1079 1080 MethodList List; 1081 Collect(RD, List); 1082 1083 // Copy the temporary list to methods, and make sure to ignore any 1084 // null entries. 1085 for (size_t i = 0, e = List.size(); i != e; ++i) { 1086 if (List[i]) 1087 Methods.push_back(List[i]); 1088 } 1089 } 1090 1091 bool empty() const { return Methods.empty(); } 1092 1093 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1094 MethodList::const_iterator methods_end() { return Methods.end(); } 1095 }; 1096 1097 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1098 MethodList& Methods) { 1099 // First, collect the pure virtual methods for the base classes. 1100 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1101 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1102 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1103 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1104 if (BaseDecl && BaseDecl->isAbstract()) 1105 Collect(BaseDecl, Methods); 1106 } 1107 } 1108 1109 // Next, zero out any pure virtual methods that this class overrides. 1110 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1111 1112 MethodSetTy OverriddenMethods; 1113 size_t MethodsSize = Methods.size(); 1114 1115 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1116 i != e; ++i) { 1117 // Traverse the record, looking for methods. 1118 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1119 // If the method is pure virtual, add it to the methods vector. 1120 if (MD->isPure()) { 1121 Methods.push_back(MD); 1122 continue; 1123 } 1124 1125 // Otherwise, record all the overridden methods in our set. 1126 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1127 E = MD->end_overridden_methods(); I != E; ++I) { 1128 // Keep track of the overridden methods. 1129 OverriddenMethods.insert(*I); 1130 } 1131 } 1132 } 1133 1134 // Now go through the methods and zero out all the ones we know are 1135 // overridden. 1136 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1137 if (OverriddenMethods.count(Methods[i])) 1138 Methods[i] = 0; 1139 } 1140 1141 } 1142} 1143 1144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1145 unsigned DiagID, AbstractDiagSelID SelID, 1146 const CXXRecordDecl *CurrentRD) { 1147 1148 if (!getLangOptions().CPlusPlus) 1149 return false; 1150 1151 if (const ArrayType *AT = Context.getAsArrayType(T)) 1152 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID, 1153 CurrentRD); 1154 1155 if (const PointerType *PT = T->getAs<PointerType>()) { 1156 // Find the innermost pointer type. 1157 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1158 PT = T; 1159 1160 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1161 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID, 1162 CurrentRD); 1163 } 1164 1165 const RecordType *RT = T->getAs<RecordType>(); 1166 if (!RT) 1167 return false; 1168 1169 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1170 if (!RD) 1171 return false; 1172 1173 if (CurrentRD && CurrentRD != RD) 1174 return false; 1175 1176 if (!RD->isAbstract()) 1177 return false; 1178 1179 Diag(Loc, DiagID) << RD->getDeclName() << SelID; 1180 1181 // Check if we've already emitted the list of pure virtual functions for this 1182 // class. 1183 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1184 return true; 1185 1186 PureVirtualMethodCollector Collector(Context, RD); 1187 1188 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1189 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1190 const CXXMethodDecl *MD = *I; 1191 1192 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1193 MD->getDeclName(); 1194 } 1195 1196 if (!PureVirtualClassDiagSet) 1197 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1198 PureVirtualClassDiagSet->insert(RD); 1199 1200 return true; 1201} 1202 1203namespace { 1204 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser 1205 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1206 Sema &SemaRef; 1207 CXXRecordDecl *AbstractClass; 1208 1209 bool VisitDeclContext(const DeclContext *DC) { 1210 bool Invalid = false; 1211 1212 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1213 E = DC->decls_end(); I != E; ++I) 1214 Invalid |= Visit(*I); 1215 1216 return Invalid; 1217 } 1218 1219 public: 1220 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1221 : SemaRef(SemaRef), AbstractClass(ac) { 1222 Visit(SemaRef.Context.getTranslationUnitDecl()); 1223 } 1224 1225 bool VisitFunctionDecl(const FunctionDecl *FD) { 1226 if (FD->isThisDeclarationADefinition()) { 1227 // No need to do the check if we're in a definition, because it requires 1228 // that the return/param types are complete. 1229 // because that requires 1230 return VisitDeclContext(FD); 1231 } 1232 1233 // Check the return type. 1234 QualType RTy = FD->getType()->getAsFunctionType()->getResultType(); 1235 bool Invalid = 1236 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1237 diag::err_abstract_type_in_decl, 1238 Sema::AbstractReturnType, 1239 AbstractClass); 1240 1241 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1242 E = FD->param_end(); I != E; ++I) { 1243 const ParmVarDecl *VD = *I; 1244 Invalid |= 1245 SemaRef.RequireNonAbstractType(VD->getLocation(), 1246 VD->getOriginalType(), 1247 diag::err_abstract_type_in_decl, 1248 Sema::AbstractParamType, 1249 AbstractClass); 1250 } 1251 1252 return Invalid; 1253 } 1254 1255 bool VisitDecl(const Decl* D) { 1256 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1257 return VisitDeclContext(DC); 1258 1259 return false; 1260 } 1261 }; 1262} 1263 1264void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1265 DeclPtrTy TagDecl, 1266 SourceLocation LBrac, 1267 SourceLocation RBrac) { 1268 if (!TagDecl) 1269 return; 1270 1271 AdjustDeclIfTemplate(TagDecl); 1272 ActOnFields(S, RLoc, TagDecl, 1273 (DeclPtrTy*)FieldCollector->getCurFields(), 1274 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1275 1276 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1277 if (!RD->isAbstract()) { 1278 // Collect all the pure virtual methods and see if this is an abstract 1279 // class after all. 1280 PureVirtualMethodCollector Collector(Context, RD); 1281 if (!Collector.empty()) 1282 RD->setAbstract(true); 1283 } 1284 1285 if (RD->isAbstract()) 1286 AbstractClassUsageDiagnoser(*this, RD); 1287 1288 if (!RD->isDependentType()) 1289 AddImplicitlyDeclaredMembersToClass(RD); 1290} 1291 1292/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1293/// special functions, such as the default constructor, copy 1294/// constructor, or destructor, to the given C++ class (C++ 1295/// [special]p1). This routine can only be executed just before the 1296/// definition of the class is complete. 1297void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1298 CanQualType ClassType 1299 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1300 1301 // FIXME: Implicit declarations have exception specifications, which are 1302 // the union of the specifications of the implicitly called functions. 1303 1304 if (!ClassDecl->hasUserDeclaredConstructor()) { 1305 // C++ [class.ctor]p5: 1306 // A default constructor for a class X is a constructor of class X 1307 // that can be called without an argument. If there is no 1308 // user-declared constructor for class X, a default constructor is 1309 // implicitly declared. An implicitly-declared default constructor 1310 // is an inline public member of its class. 1311 DeclarationName Name 1312 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1313 CXXConstructorDecl *DefaultCon = 1314 CXXConstructorDecl::Create(Context, ClassDecl, 1315 ClassDecl->getLocation(), Name, 1316 Context.getFunctionType(Context.VoidTy, 1317 0, 0, false, 0), 1318 /*DInfo=*/0, 1319 /*isExplicit=*/false, 1320 /*isInline=*/true, 1321 /*isImplicitlyDeclared=*/true); 1322 DefaultCon->setAccess(AS_public); 1323 DefaultCon->setImplicit(); 1324 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1325 ClassDecl->addDecl(DefaultCon); 1326 } 1327 1328 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1329 // C++ [class.copy]p4: 1330 // If the class definition does not explicitly declare a copy 1331 // constructor, one is declared implicitly. 1332 1333 // C++ [class.copy]p5: 1334 // The implicitly-declared copy constructor for a class X will 1335 // have the form 1336 // 1337 // X::X(const X&) 1338 // 1339 // if 1340 bool HasConstCopyConstructor = true; 1341 1342 // -- each direct or virtual base class B of X has a copy 1343 // constructor whose first parameter is of type const B& or 1344 // const volatile B&, and 1345 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1346 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 1347 const CXXRecordDecl *BaseClassDecl 1348 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1349 HasConstCopyConstructor 1350 = BaseClassDecl->hasConstCopyConstructor(Context); 1351 } 1352 1353 // -- for all the nonstatic data members of X that are of a 1354 // class type M (or array thereof), each such class type 1355 // has a copy constructor whose first parameter is of type 1356 // const M& or const volatile M&. 1357 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1358 HasConstCopyConstructor && Field != ClassDecl->field_end(); 1359 ++Field) { 1360 QualType FieldType = (*Field)->getType(); 1361 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1362 FieldType = Array->getElementType(); 1363 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1364 const CXXRecordDecl *FieldClassDecl 1365 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1366 HasConstCopyConstructor 1367 = FieldClassDecl->hasConstCopyConstructor(Context); 1368 } 1369 } 1370 1371 // Otherwise, the implicitly declared copy constructor will have 1372 // the form 1373 // 1374 // X::X(X&) 1375 QualType ArgType = ClassType; 1376 if (HasConstCopyConstructor) 1377 ArgType = ArgType.withConst(); 1378 ArgType = Context.getLValueReferenceType(ArgType); 1379 1380 // An implicitly-declared copy constructor is an inline public 1381 // member of its class. 1382 DeclarationName Name 1383 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1384 CXXConstructorDecl *CopyConstructor 1385 = CXXConstructorDecl::Create(Context, ClassDecl, 1386 ClassDecl->getLocation(), Name, 1387 Context.getFunctionType(Context.VoidTy, 1388 &ArgType, 1, 1389 false, 0), 1390 /*DInfo=*/0, 1391 /*isExplicit=*/false, 1392 /*isInline=*/true, 1393 /*isImplicitlyDeclared=*/true); 1394 CopyConstructor->setAccess(AS_public); 1395 CopyConstructor->setImplicit(); 1396 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 1397 1398 // Add the parameter to the constructor. 1399 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 1400 ClassDecl->getLocation(), 1401 /*IdentifierInfo=*/0, 1402 ArgType, /*DInfo=*/0, 1403 VarDecl::None, 0); 1404 CopyConstructor->setParams(Context, &FromParam, 1); 1405 ClassDecl->addDecl(CopyConstructor); 1406 } 1407 1408 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 1409 // Note: The following rules are largely analoguous to the copy 1410 // constructor rules. Note that virtual bases are not taken into account 1411 // for determining the argument type of the operator. Note also that 1412 // operators taking an object instead of a reference are allowed. 1413 // 1414 // C++ [class.copy]p10: 1415 // If the class definition does not explicitly declare a copy 1416 // assignment operator, one is declared implicitly. 1417 // The implicitly-defined copy assignment operator for a class X 1418 // will have the form 1419 // 1420 // X& X::operator=(const X&) 1421 // 1422 // if 1423 bool HasConstCopyAssignment = true; 1424 1425 // -- each direct base class B of X has a copy assignment operator 1426 // whose parameter is of type const B&, const volatile B& or B, 1427 // and 1428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1429 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 1430 const CXXRecordDecl *BaseClassDecl 1431 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1432 const CXXMethodDecl *MD = 0; 1433 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 1434 MD); 1435 } 1436 1437 // -- for all the nonstatic data members of X that are of a class 1438 // type M (or array thereof), each such class type has a copy 1439 // assignment operator whose parameter is of type const M&, 1440 // const volatile M& or M. 1441 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1442 HasConstCopyAssignment && Field != ClassDecl->field_end(); 1443 ++Field) { 1444 QualType FieldType = (*Field)->getType(); 1445 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1446 FieldType = Array->getElementType(); 1447 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1448 const CXXRecordDecl *FieldClassDecl 1449 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1450 const CXXMethodDecl *MD = 0; 1451 HasConstCopyAssignment 1452 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 1453 } 1454 } 1455 1456 // Otherwise, the implicitly declared copy assignment operator will 1457 // have the form 1458 // 1459 // X& X::operator=(X&) 1460 QualType ArgType = ClassType; 1461 QualType RetType = Context.getLValueReferenceType(ArgType); 1462 if (HasConstCopyAssignment) 1463 ArgType = ArgType.withConst(); 1464 ArgType = Context.getLValueReferenceType(ArgType); 1465 1466 // An implicitly-declared copy assignment operator is an inline public 1467 // member of its class. 1468 DeclarationName Name = 1469 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 1470 CXXMethodDecl *CopyAssignment = 1471 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 1472 Context.getFunctionType(RetType, &ArgType, 1, 1473 false, 0), 1474 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 1475 CopyAssignment->setAccess(AS_public); 1476 CopyAssignment->setImplicit(); 1477 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 1478 CopyAssignment->setCopyAssignment(true); 1479 1480 // Add the parameter to the operator. 1481 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 1482 ClassDecl->getLocation(), 1483 /*IdentifierInfo=*/0, 1484 ArgType, /*DInfo=*/0, 1485 VarDecl::None, 0); 1486 CopyAssignment->setParams(Context, &FromParam, 1); 1487 1488 // Don't call addedAssignmentOperator. There is no way to distinguish an 1489 // implicit from an explicit assignment operator. 1490 ClassDecl->addDecl(CopyAssignment); 1491 } 1492 1493 if (!ClassDecl->hasUserDeclaredDestructor()) { 1494 // C++ [class.dtor]p2: 1495 // If a class has no user-declared destructor, a destructor is 1496 // declared implicitly. An implicitly-declared destructor is an 1497 // inline public member of its class. 1498 DeclarationName Name 1499 = Context.DeclarationNames.getCXXDestructorName(ClassType); 1500 CXXDestructorDecl *Destructor 1501 = CXXDestructorDecl::Create(Context, ClassDecl, 1502 ClassDecl->getLocation(), Name, 1503 Context.getFunctionType(Context.VoidTy, 1504 0, 0, false, 0), 1505 /*isInline=*/true, 1506 /*isImplicitlyDeclared=*/true); 1507 Destructor->setAccess(AS_public); 1508 Destructor->setImplicit(); 1509 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 1510 ClassDecl->addDecl(Destructor); 1511 } 1512} 1513 1514void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 1515 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>(); 1516 if (!Template) 1517 return; 1518 1519 TemplateParameterList *Params = Template->getTemplateParameters(); 1520 for (TemplateParameterList::iterator Param = Params->begin(), 1521 ParamEnd = Params->end(); 1522 Param != ParamEnd; ++Param) { 1523 NamedDecl *Named = cast<NamedDecl>(*Param); 1524 if (Named->getDeclName()) { 1525 S->AddDecl(DeclPtrTy::make(Named)); 1526 IdResolver.AddDecl(Named); 1527 } 1528 } 1529} 1530 1531/// ActOnStartDelayedCXXMethodDeclaration - We have completed 1532/// parsing a top-level (non-nested) C++ class, and we are now 1533/// parsing those parts of the given Method declaration that could 1534/// not be parsed earlier (C++ [class.mem]p2), such as default 1535/// arguments. This action should enter the scope of the given 1536/// Method declaration as if we had just parsed the qualified method 1537/// name. However, it should not bring the parameters into scope; 1538/// that will be performed by ActOnDelayedCXXMethodParameter. 1539void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1540 if (!MethodD) 1541 return; 1542 1543 AdjustDeclIfTemplate(MethodD); 1544 1545 CXXScopeSpec SS; 1546 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1547 QualType ClassTy 1548 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1549 SS.setScopeRep( 1550 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1551 ActOnCXXEnterDeclaratorScope(S, SS); 1552} 1553 1554/// ActOnDelayedCXXMethodParameter - We've already started a delayed 1555/// C++ method declaration. We're (re-)introducing the given 1556/// function parameter into scope for use in parsing later parts of 1557/// the method declaration. For example, we could see an 1558/// ActOnParamDefaultArgument event for this parameter. 1559void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 1560 if (!ParamD) 1561 return; 1562 1563 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 1564 1565 // If this parameter has an unparsed default argument, clear it out 1566 // to make way for the parsed default argument. 1567 if (Param->hasUnparsedDefaultArg()) 1568 Param->setDefaultArg(0); 1569 1570 S->AddDecl(DeclPtrTy::make(Param)); 1571 if (Param->getDeclName()) 1572 IdResolver.AddDecl(Param); 1573} 1574 1575/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 1576/// processing the delayed method declaration for Method. The method 1577/// declaration is now considered finished. There may be a separate 1578/// ActOnStartOfFunctionDef action later (not necessarily 1579/// immediately!) for this method, if it was also defined inside the 1580/// class body. 1581void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1582 if (!MethodD) 1583 return; 1584 1585 AdjustDeclIfTemplate(MethodD); 1586 1587 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1588 CXXScopeSpec SS; 1589 QualType ClassTy 1590 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1591 SS.setScopeRep( 1592 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1593 ActOnCXXExitDeclaratorScope(S, SS); 1594 1595 // Now that we have our default arguments, check the constructor 1596 // again. It could produce additional diagnostics or affect whether 1597 // the class has implicitly-declared destructors, among other 1598 // things. 1599 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 1600 CheckConstructor(Constructor); 1601 1602 // Check the default arguments, which we may have added. 1603 if (!Method->isInvalidDecl()) 1604 CheckCXXDefaultArguments(Method); 1605} 1606 1607/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 1608/// the well-formedness of the constructor declarator @p D with type @p 1609/// R. If there are any errors in the declarator, this routine will 1610/// emit diagnostics and set the invalid bit to true. In any case, the type 1611/// will be updated to reflect a well-formed type for the constructor and 1612/// returned. 1613QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 1614 FunctionDecl::StorageClass &SC) { 1615 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1616 1617 // C++ [class.ctor]p3: 1618 // A constructor shall not be virtual (10.3) or static (9.4). A 1619 // constructor can be invoked for a const, volatile or const 1620 // volatile object. A constructor shall not be declared const, 1621 // volatile, or const volatile (9.3.2). 1622 if (isVirtual) { 1623 if (!D.isInvalidType()) 1624 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1625 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 1626 << SourceRange(D.getIdentifierLoc()); 1627 D.setInvalidType(); 1628 } 1629 if (SC == FunctionDecl::Static) { 1630 if (!D.isInvalidType()) 1631 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1632 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1633 << SourceRange(D.getIdentifierLoc()); 1634 D.setInvalidType(); 1635 SC = FunctionDecl::None; 1636 } 1637 1638 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1639 if (FTI.TypeQuals != 0) { 1640 if (FTI.TypeQuals & QualType::Const) 1641 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1642 << "const" << SourceRange(D.getIdentifierLoc()); 1643 if (FTI.TypeQuals & QualType::Volatile) 1644 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1645 << "volatile" << SourceRange(D.getIdentifierLoc()); 1646 if (FTI.TypeQuals & QualType::Restrict) 1647 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1648 << "restrict" << SourceRange(D.getIdentifierLoc()); 1649 } 1650 1651 // Rebuild the function type "R" without any type qualifiers (in 1652 // case any of the errors above fired) and with "void" as the 1653 // return type, since constructors don't have return types. We 1654 // *always* have to do this, because GetTypeForDeclarator will 1655 // put in a result type of "int" when none was specified. 1656 const FunctionProtoType *Proto = R->getAsFunctionProtoType(); 1657 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 1658 Proto->getNumArgs(), 1659 Proto->isVariadic(), 0); 1660} 1661 1662/// CheckConstructor - Checks a fully-formed constructor for 1663/// well-formedness, issuing any diagnostics required. Returns true if 1664/// the constructor declarator is invalid. 1665void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 1666 CXXRecordDecl *ClassDecl 1667 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 1668 if (!ClassDecl) 1669 return Constructor->setInvalidDecl(); 1670 1671 // C++ [class.copy]p3: 1672 // A declaration of a constructor for a class X is ill-formed if 1673 // its first parameter is of type (optionally cv-qualified) X and 1674 // either there are no other parameters or else all other 1675 // parameters have default arguments. 1676 if (!Constructor->isInvalidDecl() && 1677 ((Constructor->getNumParams() == 1) || 1678 (Constructor->getNumParams() > 1 && 1679 Constructor->getParamDecl(1)->hasDefaultArg()))) { 1680 QualType ParamType = Constructor->getParamDecl(0)->getType(); 1681 QualType ClassTy = Context.getTagDeclType(ClassDecl); 1682 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1683 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 1684 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 1685 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 1686 Constructor->setInvalidDecl(); 1687 } 1688 } 1689 1690 // Notify the class that we've added a constructor. 1691 ClassDecl->addedConstructor(Context, Constructor); 1692} 1693 1694static inline bool 1695FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 1696 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 1697 FTI.ArgInfo[0].Param && 1698 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 1699} 1700 1701/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 1702/// the well-formednes of the destructor declarator @p D with type @p 1703/// R. If there are any errors in the declarator, this routine will 1704/// emit diagnostics and set the declarator to invalid. Even if this happens, 1705/// will be updated to reflect a well-formed type for the destructor and 1706/// returned. 1707QualType Sema::CheckDestructorDeclarator(Declarator &D, 1708 FunctionDecl::StorageClass& SC) { 1709 // C++ [class.dtor]p1: 1710 // [...] A typedef-name that names a class is a class-name 1711 // (7.1.3); however, a typedef-name that names a class shall not 1712 // be used as the identifier in the declarator for a destructor 1713 // declaration. 1714 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType()); 1715 if (isa<TypedefType>(DeclaratorType)) { 1716 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 1717 << DeclaratorType; 1718 D.setInvalidType(); 1719 } 1720 1721 // C++ [class.dtor]p2: 1722 // A destructor is used to destroy objects of its class type. A 1723 // destructor takes no parameters, and no return type can be 1724 // specified for it (not even void). The address of a destructor 1725 // shall not be taken. A destructor shall not be static. A 1726 // destructor can be invoked for a const, volatile or const 1727 // volatile object. A destructor shall not be declared const, 1728 // volatile or const volatile (9.3.2). 1729 if (SC == FunctionDecl::Static) { 1730 if (!D.isInvalidType()) 1731 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 1732 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1733 << SourceRange(D.getIdentifierLoc()); 1734 SC = FunctionDecl::None; 1735 D.setInvalidType(); 1736 } 1737 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 1738 // Destructors don't have return types, but the parser will 1739 // happily parse something like: 1740 // 1741 // class X { 1742 // float ~X(); 1743 // }; 1744 // 1745 // The return type will be eliminated later. 1746 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 1747 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1748 << SourceRange(D.getIdentifierLoc()); 1749 } 1750 1751 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1752 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 1753 if (FTI.TypeQuals & QualType::Const) 1754 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1755 << "const" << SourceRange(D.getIdentifierLoc()); 1756 if (FTI.TypeQuals & QualType::Volatile) 1757 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1758 << "volatile" << SourceRange(D.getIdentifierLoc()); 1759 if (FTI.TypeQuals & QualType::Restrict) 1760 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 1761 << "restrict" << SourceRange(D.getIdentifierLoc()); 1762 D.setInvalidType(); 1763 } 1764 1765 // Make sure we don't have any parameters. 1766 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 1767 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 1768 1769 // Delete the parameters. 1770 FTI.freeArgs(); 1771 D.setInvalidType(); 1772 } 1773 1774 // Make sure the destructor isn't variadic. 1775 if (FTI.isVariadic) { 1776 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 1777 D.setInvalidType(); 1778 } 1779 1780 // Rebuild the function type "R" without any type qualifiers or 1781 // parameters (in case any of the errors above fired) and with 1782 // "void" as the return type, since destructors don't have return 1783 // types. We *always* have to do this, because GetTypeForDeclarator 1784 // will put in a result type of "int" when none was specified. 1785 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1786} 1787 1788/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 1789/// well-formednes of the conversion function declarator @p D with 1790/// type @p R. If there are any errors in the declarator, this routine 1791/// will emit diagnostics and return true. Otherwise, it will return 1792/// false. Either way, the type @p R will be updated to reflect a 1793/// well-formed type for the conversion operator. 1794void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 1795 FunctionDecl::StorageClass& SC) { 1796 // C++ [class.conv.fct]p1: 1797 // Neither parameter types nor return type can be specified. The 1798 // type of a conversion function (8.3.5) is "function taking no 1799 // parameter returning conversion-type-id." 1800 if (SC == FunctionDecl::Static) { 1801 if (!D.isInvalidType()) 1802 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 1803 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1804 << SourceRange(D.getIdentifierLoc()); 1805 D.setInvalidType(); 1806 SC = FunctionDecl::None; 1807 } 1808 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 1809 // Conversion functions don't have return types, but the parser will 1810 // happily parse something like: 1811 // 1812 // class X { 1813 // float operator bool(); 1814 // }; 1815 // 1816 // The return type will be changed later anyway. 1817 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 1818 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1819 << SourceRange(D.getIdentifierLoc()); 1820 } 1821 1822 // Make sure we don't have any parameters. 1823 if (R->getAsFunctionProtoType()->getNumArgs() > 0) { 1824 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 1825 1826 // Delete the parameters. 1827 D.getTypeObject(0).Fun.freeArgs(); 1828 D.setInvalidType(); 1829 } 1830 1831 // Make sure the conversion function isn't variadic. 1832 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) { 1833 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 1834 D.setInvalidType(); 1835 } 1836 1837 // C++ [class.conv.fct]p4: 1838 // The conversion-type-id shall not represent a function type nor 1839 // an array type. 1840 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType()); 1841 if (ConvType->isArrayType()) { 1842 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 1843 ConvType = Context.getPointerType(ConvType); 1844 D.setInvalidType(); 1845 } else if (ConvType->isFunctionType()) { 1846 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 1847 ConvType = Context.getPointerType(ConvType); 1848 D.setInvalidType(); 1849 } 1850 1851 // Rebuild the function type "R" without any parameters (in case any 1852 // of the errors above fired) and with the conversion type as the 1853 // return type. 1854 R = Context.getFunctionType(ConvType, 0, 0, false, 1855 R->getAsFunctionProtoType()->getTypeQuals()); 1856 1857 // C++0x explicit conversion operators. 1858 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 1859 Diag(D.getDeclSpec().getExplicitSpecLoc(), 1860 diag::warn_explicit_conversion_functions) 1861 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 1862} 1863 1864/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 1865/// the declaration of the given C++ conversion function. This routine 1866/// is responsible for recording the conversion function in the C++ 1867/// class, if possible. 1868Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 1869 assert(Conversion && "Expected to receive a conversion function declaration"); 1870 1871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 1872 1873 // Make sure we aren't redeclaring the conversion function. 1874 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 1875 1876 // C++ [class.conv.fct]p1: 1877 // [...] A conversion function is never used to convert a 1878 // (possibly cv-qualified) object to the (possibly cv-qualified) 1879 // same object type (or a reference to it), to a (possibly 1880 // cv-qualified) base class of that type (or a reference to it), 1881 // or to (possibly cv-qualified) void. 1882 // FIXME: Suppress this warning if the conversion function ends up being a 1883 // virtual function that overrides a virtual function in a base class. 1884 QualType ClassType 1885 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1886 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 1887 ConvType = ConvTypeRef->getPointeeType(); 1888 if (ConvType->isRecordType()) { 1889 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 1890 if (ConvType == ClassType) 1891 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 1892 << ClassType; 1893 else if (IsDerivedFrom(ClassType, ConvType)) 1894 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 1895 << ClassType << ConvType; 1896 } else if (ConvType->isVoidType()) { 1897 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 1898 << ClassType << ConvType; 1899 } 1900 1901 if (Conversion->getPreviousDeclaration()) { 1902 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 1903 if (FunctionTemplateDecl *ConversionTemplate 1904 = Conversion->getDescribedFunctionTemplate()) 1905 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 1906 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 1907 for (OverloadedFunctionDecl::function_iterator 1908 Conv = Conversions->function_begin(), 1909 ConvEnd = Conversions->function_end(); 1910 Conv != ConvEnd; ++Conv) { 1911 if (*Conv == ExpectedPrevDecl) { 1912 *Conv = Conversion; 1913 return DeclPtrTy::make(Conversion); 1914 } 1915 } 1916 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 1917 } else if (FunctionTemplateDecl *ConversionTemplate 1918 = Conversion->getDescribedFunctionTemplate()) 1919 ClassDecl->addConversionFunction(Context, ConversionTemplate); 1920 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 1921 ClassDecl->addConversionFunction(Context, Conversion); 1922 1923 return DeclPtrTy::make(Conversion); 1924} 1925 1926//===----------------------------------------------------------------------===// 1927// Namespace Handling 1928//===----------------------------------------------------------------------===// 1929 1930/// ActOnStartNamespaceDef - This is called at the start of a namespace 1931/// definition. 1932Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1933 SourceLocation IdentLoc, 1934 IdentifierInfo *II, 1935 SourceLocation LBrace) { 1936 NamespaceDecl *Namespc = 1937 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1938 Namespc->setLBracLoc(LBrace); 1939 1940 Scope *DeclRegionScope = NamespcScope->getParent(); 1941 1942 if (II) { 1943 // C++ [namespace.def]p2: 1944 // The identifier in an original-namespace-definition shall not have been 1945 // previously defined in the declarative region in which the 1946 // original-namespace-definition appears. The identifier in an 1947 // original-namespace-definition is the name of the namespace. Subsequently 1948 // in that declarative region, it is treated as an original-namespace-name. 1949 1950 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 1951 true); 1952 1953 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 1954 // This is an extended namespace definition. 1955 // Attach this namespace decl to the chain of extended namespace 1956 // definitions. 1957 OrigNS->setNextNamespace(Namespc); 1958 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 1959 1960 // Remove the previous declaration from the scope. 1961 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 1962 IdResolver.RemoveDecl(OrigNS); 1963 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 1964 } 1965 } else if (PrevDecl) { 1966 // This is an invalid name redefinition. 1967 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 1968 << Namespc->getDeclName(); 1969 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1970 Namespc->setInvalidDecl(); 1971 // Continue on to push Namespc as current DeclContext and return it. 1972 } 1973 1974 PushOnScopeChains(Namespc, DeclRegionScope); 1975 } else { 1976 // FIXME: Handle anonymous namespaces 1977 } 1978 1979 // Although we could have an invalid decl (i.e. the namespace name is a 1980 // redefinition), push it as current DeclContext and try to continue parsing. 1981 // FIXME: We should be able to push Namespc here, so that the each DeclContext 1982 // for the namespace has the declarations that showed up in that particular 1983 // namespace definition. 1984 PushDeclContext(NamespcScope, Namespc); 1985 return DeclPtrTy::make(Namespc); 1986} 1987 1988/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1989/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1990void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 1991 Decl *Dcl = D.getAs<Decl>(); 1992 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1993 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1994 Namespc->setRBracLoc(RBrace); 1995 PopDeclContext(); 1996} 1997 1998Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 1999 SourceLocation UsingLoc, 2000 SourceLocation NamespcLoc, 2001 const CXXScopeSpec &SS, 2002 SourceLocation IdentLoc, 2003 IdentifierInfo *NamespcName, 2004 AttributeList *AttrList) { 2005 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2006 assert(NamespcName && "Invalid NamespcName."); 2007 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2008 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2009 2010 UsingDirectiveDecl *UDir = 0; 2011 2012 // Lookup namespace name. 2013 LookupResult R = LookupParsedName(S, &SS, NamespcName, 2014 LookupNamespaceName, false); 2015 if (R.isAmbiguous()) { 2016 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 2017 return DeclPtrTy(); 2018 } 2019 if (NamedDecl *NS = R) { 2020 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 2021 // C++ [namespace.udir]p1: 2022 // A using-directive specifies that the names in the nominated 2023 // namespace can be used in the scope in which the 2024 // using-directive appears after the using-directive. During 2025 // unqualified name lookup (3.4.1), the names appear as if they 2026 // were declared in the nearest enclosing namespace which 2027 // contains both the using-directive and the nominated 2028 // namespace. [Note: in this context, "contains" means "contains 2029 // directly or indirectly". ] 2030 2031 // Find enclosing context containing both using-directive and 2032 // nominated namespace. 2033 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2034 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2035 CommonAncestor = CommonAncestor->getParent(); 2036 2037 UDir = UsingDirectiveDecl::Create(Context, 2038 CurContext, UsingLoc, 2039 NamespcLoc, 2040 SS.getRange(), 2041 (NestedNameSpecifier *)SS.getScopeRep(), 2042 IdentLoc, 2043 cast<NamespaceDecl>(NS), 2044 CommonAncestor); 2045 PushUsingDirective(S, UDir); 2046 } else { 2047 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2048 } 2049 2050 // FIXME: We ignore attributes for now. 2051 delete AttrList; 2052 return DeclPtrTy::make(UDir); 2053} 2054 2055void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2056 // If scope has associated entity, then using directive is at namespace 2057 // or translation unit scope. We add UsingDirectiveDecls, into 2058 // it's lookup structure. 2059 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2060 Ctx->addDecl(UDir); 2061 else 2062 // Otherwise it is block-sope. using-directives will affect lookup 2063 // only to the end of scope. 2064 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2065} 2066 2067 2068Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2069 SourceLocation UsingLoc, 2070 const CXXScopeSpec &SS, 2071 SourceLocation IdentLoc, 2072 IdentifierInfo *TargetName, 2073 OverloadedOperatorKind Op, 2074 AttributeList *AttrList, 2075 bool IsTypeName) { 2076 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2077 assert((TargetName || Op) && "Invalid TargetName."); 2078 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2079 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2080 2081 UsingDecl *UsingAlias = 0; 2082 2083 DeclarationName Name; 2084 if (TargetName) 2085 Name = TargetName; 2086 else 2087 Name = Context.DeclarationNames.getCXXOperatorName(Op); 2088 2089 // Lookup target name. 2090 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false); 2091 2092 if (NamedDecl *NS = R) { 2093 if (IsTypeName && !isa<TypeDecl>(NS)) { 2094 Diag(IdentLoc, diag::err_using_typename_non_type); 2095 } 2096 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(), 2097 NS->getLocation(), UsingLoc, NS, 2098 static_cast<NestedNameSpecifier *>(SS.getScopeRep()), 2099 IsTypeName); 2100 PushOnScopeChains(UsingAlias, S); 2101 } else { 2102 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange(); 2103 } 2104 2105 // FIXME: We ignore attributes for now. 2106 delete AttrList; 2107 return DeclPtrTy::make(UsingAlias); 2108} 2109 2110/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2111/// is a namespace alias, returns the namespace it points to. 2112static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2113 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2114 return AD->getNamespace(); 2115 return dyn_cast_or_null<NamespaceDecl>(D); 2116} 2117 2118Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 2119 SourceLocation NamespaceLoc, 2120 SourceLocation AliasLoc, 2121 IdentifierInfo *Alias, 2122 const CXXScopeSpec &SS, 2123 SourceLocation IdentLoc, 2124 IdentifierInfo *Ident) { 2125 2126 // Lookup the namespace name. 2127 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false); 2128 2129 // Check if we have a previous declaration with the same name. 2130 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) { 2131 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 2132 // We already have an alias with the same name that points to the same 2133 // namespace, so don't create a new one. 2134 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R)) 2135 return DeclPtrTy(); 2136 } 2137 2138 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 2139 diag::err_redefinition_different_kind; 2140 Diag(AliasLoc, DiagID) << Alias; 2141 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2142 return DeclPtrTy(); 2143 } 2144 2145 if (R.isAmbiguous()) { 2146 DiagnoseAmbiguousLookup(R, Ident, IdentLoc); 2147 return DeclPtrTy(); 2148 } 2149 2150 if (!R) { 2151 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 2152 return DeclPtrTy(); 2153 } 2154 2155 NamespaceAliasDecl *AliasDecl = 2156 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 2157 Alias, SS.getRange(), 2158 (NestedNameSpecifier *)SS.getScopeRep(), 2159 IdentLoc, R); 2160 2161 CurContext->addDecl(AliasDecl); 2162 return DeclPtrTy::make(AliasDecl); 2163} 2164 2165void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2166 CXXConstructorDecl *Constructor) { 2167 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 2168 !Constructor->isUsed()) && 2169 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 2170 2171 CXXRecordDecl *ClassDecl 2172 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 2173 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 2174 // Before the implicitly-declared default constructor for a class is 2175 // implicitly defined, all the implicitly-declared default constructors 2176 // for its base class and its non-static data members shall have been 2177 // implicitly defined. 2178 bool err = false; 2179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2180 E = ClassDecl->bases_end(); Base != E; ++Base) { 2181 CXXRecordDecl *BaseClassDecl 2182 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2183 if (!BaseClassDecl->hasTrivialConstructor()) { 2184 if (CXXConstructorDecl *BaseCtor = 2185 BaseClassDecl->getDefaultConstructor(Context)) 2186 MarkDeclarationReferenced(CurrentLocation, BaseCtor); 2187 else { 2188 Diag(CurrentLocation, diag::err_defining_default_ctor) 2189 << Context.getTagDeclType(ClassDecl) << 1 2190 << Context.getTagDeclType(BaseClassDecl); 2191 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl) 2192 << Context.getTagDeclType(BaseClassDecl); 2193 err = true; 2194 } 2195 } 2196 } 2197 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2198 E = ClassDecl->field_end(); Field != E; ++Field) { 2199 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2200 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2201 FieldType = Array->getElementType(); 2202 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2203 CXXRecordDecl *FieldClassDecl 2204 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2205 if (!FieldClassDecl->hasTrivialConstructor()) { 2206 if (CXXConstructorDecl *FieldCtor = 2207 FieldClassDecl->getDefaultConstructor(Context)) 2208 MarkDeclarationReferenced(CurrentLocation, FieldCtor); 2209 else { 2210 Diag(CurrentLocation, diag::err_defining_default_ctor) 2211 << Context.getTagDeclType(ClassDecl) << 0 << 2212 Context.getTagDeclType(FieldClassDecl); 2213 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl) 2214 << Context.getTagDeclType(FieldClassDecl); 2215 err = true; 2216 } 2217 } 2218 } else if (FieldType->isReferenceType()) { 2219 Diag(CurrentLocation, diag::err_unintialized_member) 2220 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2221 Diag((*Field)->getLocation(), diag::note_declared_at); 2222 err = true; 2223 } else if (FieldType.isConstQualified()) { 2224 Diag(CurrentLocation, diag::err_unintialized_member) 2225 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2226 Diag((*Field)->getLocation(), diag::note_declared_at); 2227 err = true; 2228 } 2229 } 2230 if (!err) 2231 Constructor->setUsed(); 2232 else 2233 Constructor->setInvalidDecl(); 2234} 2235 2236void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 2237 CXXDestructorDecl *Destructor) { 2238 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 2239 "DefineImplicitDestructor - call it for implicit default dtor"); 2240 2241 CXXRecordDecl *ClassDecl 2242 = cast<CXXRecordDecl>(Destructor->getDeclContext()); 2243 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 2244 // C++ [class.dtor] p5 2245 // Before the implicitly-declared default destructor for a class is 2246 // implicitly defined, all the implicitly-declared default destructors 2247 // for its base class and its non-static data members shall have been 2248 // implicitly defined. 2249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2250 E = ClassDecl->bases_end(); Base != E; ++Base) { 2251 CXXRecordDecl *BaseClassDecl 2252 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2253 if (!BaseClassDecl->hasTrivialDestructor()) { 2254 if (CXXDestructorDecl *BaseDtor = 2255 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 2256 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 2257 else 2258 assert(false && 2259 "DefineImplicitDestructor - missing dtor in a base class"); 2260 } 2261 } 2262 2263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2264 E = ClassDecl->field_end(); Field != E; ++Field) { 2265 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2266 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2267 FieldType = Array->getElementType(); 2268 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2269 CXXRecordDecl *FieldClassDecl 2270 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2271 if (!FieldClassDecl->hasTrivialDestructor()) { 2272 if (CXXDestructorDecl *FieldDtor = 2273 const_cast<CXXDestructorDecl*>( 2274 FieldClassDecl->getDestructor(Context))) 2275 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 2276 else 2277 assert(false && 2278 "DefineImplicitDestructor - missing dtor in class of a data member"); 2279 } 2280 } 2281 } 2282 Destructor->setUsed(); 2283} 2284 2285void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 2286 CXXMethodDecl *MethodDecl) { 2287 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 2288 MethodDecl->getOverloadedOperator() == OO_Equal && 2289 !MethodDecl->isUsed()) && 2290 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 2291 2292 CXXRecordDecl *ClassDecl 2293 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 2294 2295 // C++[class.copy] p12 2296 // Before the implicitly-declared copy assignment operator for a class is 2297 // implicitly defined, all implicitly-declared copy assignment operators 2298 // for its direct base classes and its nonstatic data members shall have 2299 // been implicitly defined. 2300 bool err = false; 2301 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2302 E = ClassDecl->bases_end(); Base != E; ++Base) { 2303 CXXRecordDecl *BaseClassDecl 2304 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2305 if (CXXMethodDecl *BaseAssignOpMethod = 2306 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 2307 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 2308 } 2309 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2310 E = ClassDecl->field_end(); Field != E; ++Field) { 2311 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2312 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2313 FieldType = Array->getElementType(); 2314 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2315 CXXRecordDecl *FieldClassDecl 2316 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2317 if (CXXMethodDecl *FieldAssignOpMethod = 2318 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 2319 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 2320 } else if (FieldType->isReferenceType()) { 2321 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2322 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2323 Diag(Field->getLocation(), diag::note_declared_at); 2324 Diag(CurrentLocation, diag::note_first_required_here); 2325 err = true; 2326 } else if (FieldType.isConstQualified()) { 2327 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2328 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2329 Diag(Field->getLocation(), diag::note_declared_at); 2330 Diag(CurrentLocation, diag::note_first_required_here); 2331 err = true; 2332 } 2333 } 2334 if (!err) 2335 MethodDecl->setUsed(); 2336} 2337 2338CXXMethodDecl * 2339Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 2340 CXXRecordDecl *ClassDecl) { 2341 QualType LHSType = Context.getTypeDeclType(ClassDecl); 2342 QualType RHSType(LHSType); 2343 // If class's assignment operator argument is const/volatile qualified, 2344 // look for operator = (const/volatile B&). Otherwise, look for 2345 // operator = (B&). 2346 if (ParmDecl->getType().isConstQualified()) 2347 RHSType.addConst(); 2348 if (ParmDecl->getType().isVolatileQualified()) 2349 RHSType.addVolatile(); 2350 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 2351 LHSType, 2352 SourceLocation())); 2353 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 2354 RHSType, 2355 SourceLocation())); 2356 Expr *Args[2] = { &*LHS, &*RHS }; 2357 OverloadCandidateSet CandidateSet; 2358 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 2359 CandidateSet); 2360 OverloadCandidateSet::iterator Best; 2361 if (BestViableFunction(CandidateSet, 2362 ClassDecl->getLocation(), Best) == OR_Success) 2363 return cast<CXXMethodDecl>(Best->Function); 2364 assert(false && 2365 "getAssignOperatorMethod - copy assignment operator method not found"); 2366 return 0; 2367} 2368 2369void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2370 CXXConstructorDecl *CopyConstructor, 2371 unsigned TypeQuals) { 2372 assert((CopyConstructor->isImplicit() && 2373 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 2374 !CopyConstructor->isUsed()) && 2375 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 2376 2377 CXXRecordDecl *ClassDecl 2378 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 2379 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 2380 // C++ [class.copy] p209 2381 // Before the implicitly-declared copy constructor for a class is 2382 // implicitly defined, all the implicitly-declared copy constructors 2383 // for its base class and its non-static data members shall have been 2384 // implicitly defined. 2385 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2386 Base != ClassDecl->bases_end(); ++Base) { 2387 CXXRecordDecl *BaseClassDecl 2388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2389 if (CXXConstructorDecl *BaseCopyCtor = 2390 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 2391 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 2392 } 2393 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2394 FieldEnd = ClassDecl->field_end(); 2395 Field != FieldEnd; ++Field) { 2396 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2397 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2398 FieldType = Array->getElementType(); 2399 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2400 CXXRecordDecl *FieldClassDecl 2401 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2402 if (CXXConstructorDecl *FieldCopyCtor = 2403 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 2404 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 2405 } 2406 } 2407 CopyConstructor->setUsed(); 2408} 2409 2410Expr *Sema::BuildCXXConstructExpr(QualType DeclInitType, 2411 CXXConstructorDecl *Constructor, 2412 Expr **Exprs, unsigned NumExprs) { 2413 bool Elidable = false; 2414 2415 // [class.copy]p15: 2416 // Whenever a temporary class object is copied using a copy constructor, and 2417 // this object and the copy have the same cv-unqualified type, an 2418 // implementation is permitted to treat the original and the copy as two 2419 // different ways of referring to the same object and not perform a copy at 2420 //all, even if the class copy constructor or destructor have side effects. 2421 2422 // FIXME: Is this enough? 2423 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) { 2424 Expr *E = Exprs[0]; 2425 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2426 E = BE->getSubExpr(); 2427 2428 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 2429 Elidable = true; 2430 } 2431 2432 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable, 2433 Exprs, NumExprs); 2434} 2435 2436/// BuildCXXConstructExpr - Creates a complete call to a constructor, 2437/// including handling of its default argument expressions. 2438Expr *Sema::BuildCXXConstructExpr(QualType DeclInitType, 2439 CXXConstructorDecl *Constructor, 2440 bool Elidable, 2441 Expr **Exprs, unsigned NumExprs) { 2442 CXXConstructExpr *Temp = CXXConstructExpr::Create(Context, DeclInitType, 2443 Constructor, 2444 Elidable, Exprs, NumExprs); 2445 // default arguments must be added to constructor call expression. 2446 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor); 2447 unsigned NumArgsInProto = FDecl->param_size(); 2448 for (unsigned j = NumExprs; j != NumArgsInProto; j++) { 2449 Expr *DefaultExpr = FDecl->getParamDecl(j)->getDefaultArg(); 2450 2451 // If the default expression creates temporaries, we need to 2452 // push them to the current stack of expression temporaries so they'll 2453 // be properly destroyed. 2454 if (CXXExprWithTemporaries *E 2455 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) { 2456 assert(!E->shouldDestroyTemporaries() && 2457 "Can't destroy temporaries in a default argument expr!"); 2458 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) 2459 ExprTemporaries.push_back(E->getTemporary(I)); 2460 } 2461 Expr *Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(j)); 2462 Temp->setArg(j, Arg); 2463 } 2464 return Temp; 2465} 2466 2467void Sema::InitializeVarWithConstructor(VarDecl *VD, 2468 CXXConstructorDecl *Constructor, 2469 QualType DeclInitType, 2470 Expr **Exprs, unsigned NumExprs) { 2471 Expr *Temp = BuildCXXConstructExpr(DeclInitType, Constructor, 2472 Exprs, NumExprs); 2473 MarkDeclarationReferenced(VD->getLocation(), Constructor); 2474 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 2475 VD->setInit(Context, Temp); 2476} 2477 2478void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) 2479{ 2480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 2481 DeclInitType->getAs<RecordType>()->getDecl()); 2482 if (!ClassDecl->hasTrivialDestructor()) 2483 if (CXXDestructorDecl *Destructor = 2484 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 2485 MarkDeclarationReferenced(VD->getLocation(), Destructor); 2486} 2487 2488/// AddCXXDirectInitializerToDecl - This action is called immediately after 2489/// ActOnDeclarator, when a C++ direct initializer is present. 2490/// e.g: "int x(1);" 2491void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 2492 SourceLocation LParenLoc, 2493 MultiExprArg Exprs, 2494 SourceLocation *CommaLocs, 2495 SourceLocation RParenLoc) { 2496 unsigned NumExprs = Exprs.size(); 2497 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 2498 Decl *RealDecl = Dcl.getAs<Decl>(); 2499 2500 // If there is no declaration, there was an error parsing it. Just ignore 2501 // the initializer. 2502 if (RealDecl == 0) 2503 return; 2504 2505 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2506 if (!VDecl) { 2507 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 2508 RealDecl->setInvalidDecl(); 2509 return; 2510 } 2511 2512 // FIXME: Need to handle dependent types and expressions here. 2513 2514 // We will treat direct-initialization as a copy-initialization: 2515 // int x(1); -as-> int x = 1; 2516 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 2517 // 2518 // Clients that want to distinguish between the two forms, can check for 2519 // direct initializer using VarDecl::hasCXXDirectInitializer(). 2520 // A major benefit is that clients that don't particularly care about which 2521 // exactly form was it (like the CodeGen) can handle both cases without 2522 // special case code. 2523 2524 // C++ 8.5p11: 2525 // The form of initialization (using parentheses or '=') is generally 2526 // insignificant, but does matter when the entity being initialized has a 2527 // class type. 2528 QualType DeclInitType = VDecl->getType(); 2529 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 2530 DeclInitType = Array->getElementType(); 2531 2532 // FIXME: This isn't the right place to complete the type. 2533 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 2534 diag::err_typecheck_decl_incomplete_type)) { 2535 VDecl->setInvalidDecl(); 2536 return; 2537 } 2538 2539 if (VDecl->getType()->isRecordType()) { 2540 CXXConstructorDecl *Constructor 2541 = PerformInitializationByConstructor(DeclInitType, 2542 (Expr **)Exprs.get(), NumExprs, 2543 VDecl->getLocation(), 2544 SourceRange(VDecl->getLocation(), 2545 RParenLoc), 2546 VDecl->getDeclName(), 2547 IK_Direct); 2548 if (!Constructor) 2549 RealDecl->setInvalidDecl(); 2550 else { 2551 VDecl->setCXXDirectInitializer(true); 2552 InitializeVarWithConstructor(VDecl, Constructor, DeclInitType, 2553 (Expr**)Exprs.release(), NumExprs); 2554 FinalizeVarWithDestructor(VDecl, DeclInitType); 2555 } 2556 return; 2557 } 2558 2559 if (NumExprs > 1) { 2560 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 2561 << SourceRange(VDecl->getLocation(), RParenLoc); 2562 RealDecl->setInvalidDecl(); 2563 return; 2564 } 2565 2566 // Let clients know that initialization was done with a direct initializer. 2567 VDecl->setCXXDirectInitializer(true); 2568 2569 assert(NumExprs == 1 && "Expected 1 expression"); 2570 // Set the init expression, handles conversions. 2571 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 2572 /*DirectInit=*/true); 2573} 2574 2575/// PerformInitializationByConstructor - Perform initialization by 2576/// constructor (C++ [dcl.init]p14), which may occur as part of 2577/// direct-initialization or copy-initialization. We are initializing 2578/// an object of type @p ClassType with the given arguments @p 2579/// Args. @p Loc is the location in the source code where the 2580/// initializer occurs (e.g., a declaration, member initializer, 2581/// functional cast, etc.) while @p Range covers the whole 2582/// initialization. @p InitEntity is the entity being initialized, 2583/// which may by the name of a declaration or a type. @p Kind is the 2584/// kind of initialization we're performing, which affects whether 2585/// explicit constructors will be considered. When successful, returns 2586/// the constructor that will be used to perform the initialization; 2587/// when the initialization fails, emits a diagnostic and returns 2588/// null. 2589CXXConstructorDecl * 2590Sema::PerformInitializationByConstructor(QualType ClassType, 2591 Expr **Args, unsigned NumArgs, 2592 SourceLocation Loc, SourceRange Range, 2593 DeclarationName InitEntity, 2594 InitializationKind Kind) { 2595 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 2596 assert(ClassRec && "Can only initialize a class type here"); 2597 2598 // C++ [dcl.init]p14: 2599 // 2600 // If the initialization is direct-initialization, or if it is 2601 // copy-initialization where the cv-unqualified version of the 2602 // source type is the same class as, or a derived class of, the 2603 // class of the destination, constructors are considered. The 2604 // applicable constructors are enumerated (13.3.1.3), and the 2605 // best one is chosen through overload resolution (13.3). The 2606 // constructor so selected is called to initialize the object, 2607 // with the initializer expression(s) as its argument(s). If no 2608 // constructor applies, or the overload resolution is ambiguous, 2609 // the initialization is ill-formed. 2610 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 2611 OverloadCandidateSet CandidateSet; 2612 2613 // Add constructors to the overload set. 2614 DeclarationName ConstructorName 2615 = Context.DeclarationNames.getCXXConstructorName( 2616 Context.getCanonicalType(ClassType.getUnqualifiedType())); 2617 DeclContext::lookup_const_iterator Con, ConEnd; 2618 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 2619 Con != ConEnd; ++Con) { 2620 // Find the constructor (which may be a template). 2621 CXXConstructorDecl *Constructor = 0; 2622 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 2623 if (ConstructorTmpl) 2624 Constructor 2625 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2626 else 2627 Constructor = cast<CXXConstructorDecl>(*Con); 2628 2629 if ((Kind == IK_Direct) || 2630 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 2631 (Kind == IK_Default && Constructor->isDefaultConstructor())) { 2632 if (ConstructorTmpl) 2633 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, 2634 Args, NumArgs, CandidateSet); 2635 else 2636 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 2637 } 2638 } 2639 2640 // FIXME: When we decide not to synthesize the implicitly-declared 2641 // constructors, we'll need to make them appear here. 2642 2643 OverloadCandidateSet::iterator Best; 2644 switch (BestViableFunction(CandidateSet, Loc, Best)) { 2645 case OR_Success: 2646 // We found a constructor. Return it. 2647 return cast<CXXConstructorDecl>(Best->Function); 2648 2649 case OR_No_Viable_Function: 2650 if (InitEntity) 2651 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 2652 << InitEntity << Range; 2653 else 2654 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 2655 << ClassType << Range; 2656 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 2657 return 0; 2658 2659 case OR_Ambiguous: 2660 if (InitEntity) 2661 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 2662 else 2663 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 2664 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 2665 return 0; 2666 2667 case OR_Deleted: 2668 if (InitEntity) 2669 Diag(Loc, diag::err_ovl_deleted_init) 2670 << Best->Function->isDeleted() 2671 << InitEntity << Range; 2672 else 2673 Diag(Loc, diag::err_ovl_deleted_init) 2674 << Best->Function->isDeleted() 2675 << InitEntity << Range; 2676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 2677 return 0; 2678 } 2679 2680 return 0; 2681} 2682 2683/// CompareReferenceRelationship - Compare the two types T1 and T2 to 2684/// determine whether they are reference-related, 2685/// reference-compatible, reference-compatible with added 2686/// qualification, or incompatible, for use in C++ initialization by 2687/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 2688/// type, and the first type (T1) is the pointee type of the reference 2689/// type being initialized. 2690Sema::ReferenceCompareResult 2691Sema::CompareReferenceRelationship(QualType T1, QualType T2, 2692 bool& DerivedToBase) { 2693 assert(!T1->isReferenceType() && 2694 "T1 must be the pointee type of the reference type"); 2695 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 2696 2697 T1 = Context.getCanonicalType(T1); 2698 T2 = Context.getCanonicalType(T2); 2699 QualType UnqualT1 = T1.getUnqualifiedType(); 2700 QualType UnqualT2 = T2.getUnqualifiedType(); 2701 2702 // C++ [dcl.init.ref]p4: 2703 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 2704 // reference-related to "cv2 T2" if T1 is the same type as T2, or 2705 // T1 is a base class of T2. 2706 if (UnqualT1 == UnqualT2) 2707 DerivedToBase = false; 2708 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 2709 DerivedToBase = true; 2710 else 2711 return Ref_Incompatible; 2712 2713 // At this point, we know that T1 and T2 are reference-related (at 2714 // least). 2715 2716 // C++ [dcl.init.ref]p4: 2717 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 2718 // reference-related to T2 and cv1 is the same cv-qualification 2719 // as, or greater cv-qualification than, cv2. For purposes of 2720 // overload resolution, cases for which cv1 is greater 2721 // cv-qualification than cv2 are identified as 2722 // reference-compatible with added qualification (see 13.3.3.2). 2723 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2724 return Ref_Compatible; 2725 else if (T1.isMoreQualifiedThan(T2)) 2726 return Ref_Compatible_With_Added_Qualification; 2727 else 2728 return Ref_Related; 2729} 2730 2731/// CheckReferenceInit - Check the initialization of a reference 2732/// variable with the given initializer (C++ [dcl.init.ref]). Init is 2733/// the initializer (either a simple initializer or an initializer 2734/// list), and DeclType is the type of the declaration. When ICS is 2735/// non-null, this routine will compute the implicit conversion 2736/// sequence according to C++ [over.ics.ref] and will not produce any 2737/// diagnostics; when ICS is null, it will emit diagnostics when any 2738/// errors are found. Either way, a return value of true indicates 2739/// that there was a failure, a return value of false indicates that 2740/// the reference initialization succeeded. 2741/// 2742/// When @p SuppressUserConversions, user-defined conversions are 2743/// suppressed. 2744/// When @p AllowExplicit, we also permit explicit user-defined 2745/// conversion functions. 2746/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 2747bool 2748Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 2749 ImplicitConversionSequence *ICS, 2750 bool SuppressUserConversions, 2751 bool AllowExplicit, bool ForceRValue) { 2752 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 2753 2754 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 2755 QualType T2 = Init->getType(); 2756 2757 // If the initializer is the address of an overloaded function, try 2758 // to resolve the overloaded function. If all goes well, T2 is the 2759 // type of the resulting function. 2760 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 2761 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 2762 ICS != 0); 2763 if (Fn) { 2764 // Since we're performing this reference-initialization for 2765 // real, update the initializer with the resulting function. 2766 if (!ICS) { 2767 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin())) 2768 return true; 2769 2770 FixOverloadedFunctionReference(Init, Fn); 2771 } 2772 2773 T2 = Fn->getType(); 2774 } 2775 } 2776 2777 // Compute some basic properties of the types and the initializer. 2778 bool isRValRef = DeclType->isRValueReferenceType(); 2779 bool DerivedToBase = false; 2780 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 2781 Init->isLvalue(Context); 2782 ReferenceCompareResult RefRelationship 2783 = CompareReferenceRelationship(T1, T2, DerivedToBase); 2784 2785 // Most paths end in a failed conversion. 2786 if (ICS) 2787 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 2788 2789 // C++ [dcl.init.ref]p5: 2790 // A reference to type "cv1 T1" is initialized by an expression 2791 // of type "cv2 T2" as follows: 2792 2793 // -- If the initializer expression 2794 2795 // Rvalue references cannot bind to lvalues (N2812). 2796 // There is absolutely no situation where they can. In particular, note that 2797 // this is ill-formed, even if B has a user-defined conversion to A&&: 2798 // B b; 2799 // A&& r = b; 2800 if (isRValRef && InitLvalue == Expr::LV_Valid) { 2801 if (!ICS) 2802 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref) 2803 << Init->getSourceRange(); 2804 return true; 2805 } 2806 2807 bool BindsDirectly = false; 2808 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 2809 // reference-compatible with "cv2 T2," or 2810 // 2811 // Note that the bit-field check is skipped if we are just computing 2812 // the implicit conversion sequence (C++ [over.best.ics]p2). 2813 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 2814 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 2815 BindsDirectly = true; 2816 2817 if (ICS) { 2818 // C++ [over.ics.ref]p1: 2819 // When a parameter of reference type binds directly (8.5.3) 2820 // to an argument expression, the implicit conversion sequence 2821 // is the identity conversion, unless the argument expression 2822 // has a type that is a derived class of the parameter type, 2823 // in which case the implicit conversion sequence is a 2824 // derived-to-base Conversion (13.3.3.1). 2825 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 2826 ICS->Standard.First = ICK_Identity; 2827 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 2828 ICS->Standard.Third = ICK_Identity; 2829 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 2830 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 2831 ICS->Standard.ReferenceBinding = true; 2832 ICS->Standard.DirectBinding = true; 2833 ICS->Standard.RRefBinding = false; 2834 ICS->Standard.CopyConstructor = 0; 2835 2836 // Nothing more to do: the inaccessibility/ambiguity check for 2837 // derived-to-base conversions is suppressed when we're 2838 // computing the implicit conversion sequence (C++ 2839 // [over.best.ics]p2). 2840 return false; 2841 } else { 2842 // Perform the conversion. 2843 // FIXME: Binding to a subobject of the lvalue is going to require more 2844 // AST annotation than this. 2845 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 2846 } 2847 } 2848 2849 // -- has a class type (i.e., T2 is a class type) and can be 2850 // implicitly converted to an lvalue of type "cv3 T3," 2851 // where "cv1 T1" is reference-compatible with "cv3 T3" 2852 // 92) (this conversion is selected by enumerating the 2853 // applicable conversion functions (13.3.1.6) and choosing 2854 // the best one through overload resolution (13.3)), 2855 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 2856 !RequireCompleteType(SourceLocation(), T2, 0)) { 2857 // FIXME: Look for conversions in base classes! 2858 CXXRecordDecl *T2RecordDecl 2859 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 2860 2861 OverloadCandidateSet CandidateSet; 2862 OverloadedFunctionDecl *Conversions 2863 = T2RecordDecl->getConversionFunctions(); 2864 for (OverloadedFunctionDecl::function_iterator Func 2865 = Conversions->function_begin(); 2866 Func != Conversions->function_end(); ++Func) { 2867 FunctionTemplateDecl *ConvTemplate 2868 = dyn_cast<FunctionTemplateDecl>(*Func); 2869 CXXConversionDecl *Conv; 2870 if (ConvTemplate) 2871 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2872 else 2873 Conv = cast<CXXConversionDecl>(*Func); 2874 2875 // If the conversion function doesn't return a reference type, 2876 // it can't be considered for this conversion. 2877 if (Conv->getConversionType()->isLValueReferenceType() && 2878 (AllowExplicit || !Conv->isExplicit())) { 2879 if (ConvTemplate) 2880 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 2881 CandidateSet); 2882 else 2883 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 2884 } 2885 } 2886 2887 OverloadCandidateSet::iterator Best; 2888 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) { 2889 case OR_Success: 2890 // This is a direct binding. 2891 BindsDirectly = true; 2892 2893 if (ICS) { 2894 // C++ [over.ics.ref]p1: 2895 // 2896 // [...] If the parameter binds directly to the result of 2897 // applying a conversion function to the argument 2898 // expression, the implicit conversion sequence is a 2899 // user-defined conversion sequence (13.3.3.1.2), with the 2900 // second standard conversion sequence either an identity 2901 // conversion or, if the conversion function returns an 2902 // entity of a type that is a derived class of the parameter 2903 // type, a derived-to-base Conversion. 2904 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 2905 ICS->UserDefined.Before = Best->Conversions[0].Standard; 2906 ICS->UserDefined.After = Best->FinalConversion; 2907 ICS->UserDefined.ConversionFunction = Best->Function; 2908 assert(ICS->UserDefined.After.ReferenceBinding && 2909 ICS->UserDefined.After.DirectBinding && 2910 "Expected a direct reference binding!"); 2911 return false; 2912 } else { 2913 // Perform the conversion. 2914 // FIXME: Binding to a subobject of the lvalue is going to require more 2915 // AST annotation than this. 2916 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 2917 } 2918 break; 2919 2920 case OR_Ambiguous: 2921 assert(false && "Ambiguous reference binding conversions not implemented."); 2922 return true; 2923 2924 case OR_No_Viable_Function: 2925 case OR_Deleted: 2926 // There was no suitable conversion, or we found a deleted 2927 // conversion; continue with other checks. 2928 break; 2929 } 2930 } 2931 2932 if (BindsDirectly) { 2933 // C++ [dcl.init.ref]p4: 2934 // [...] In all cases where the reference-related or 2935 // reference-compatible relationship of two types is used to 2936 // establish the validity of a reference binding, and T1 is a 2937 // base class of T2, a program that necessitates such a binding 2938 // is ill-formed if T1 is an inaccessible (clause 11) or 2939 // ambiguous (10.2) base class of T2. 2940 // 2941 // Note that we only check this condition when we're allowed to 2942 // complain about errors, because we should not be checking for 2943 // ambiguity (or inaccessibility) unless the reference binding 2944 // actually happens. 2945 if (DerivedToBase) 2946 return CheckDerivedToBaseConversion(T2, T1, 2947 Init->getSourceRange().getBegin(), 2948 Init->getSourceRange()); 2949 else 2950 return false; 2951 } 2952 2953 // -- Otherwise, the reference shall be to a non-volatile const 2954 // type (i.e., cv1 shall be const), or the reference shall be an 2955 // rvalue reference and the initializer expression shall be an rvalue. 2956 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) { 2957 if (!ICS) 2958 Diag(Init->getSourceRange().getBegin(), 2959 diag::err_not_reference_to_const_init) 2960 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 2961 << T2 << Init->getSourceRange(); 2962 return true; 2963 } 2964 2965 // -- If the initializer expression is an rvalue, with T2 a 2966 // class type, and "cv1 T1" is reference-compatible with 2967 // "cv2 T2," the reference is bound in one of the 2968 // following ways (the choice is implementation-defined): 2969 // 2970 // -- The reference is bound to the object represented by 2971 // the rvalue (see 3.10) or to a sub-object within that 2972 // object. 2973 // 2974 // -- A temporary of type "cv1 T2" [sic] is created, and 2975 // a constructor is called to copy the entire rvalue 2976 // object into the temporary. The reference is bound to 2977 // the temporary or to a sub-object within the 2978 // temporary. 2979 // 2980 // The constructor that would be used to make the copy 2981 // shall be callable whether or not the copy is actually 2982 // done. 2983 // 2984 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 2985 // freedom, so we will always take the first option and never build 2986 // a temporary in this case. FIXME: We will, however, have to check 2987 // for the presence of a copy constructor in C++98/03 mode. 2988 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 2989 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 2990 if (ICS) { 2991 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 2992 ICS->Standard.First = ICK_Identity; 2993 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 2994 ICS->Standard.Third = ICK_Identity; 2995 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 2996 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 2997 ICS->Standard.ReferenceBinding = true; 2998 ICS->Standard.DirectBinding = false; 2999 ICS->Standard.RRefBinding = isRValRef; 3000 ICS->Standard.CopyConstructor = 0; 3001 } else { 3002 // FIXME: Binding to a subobject of the rvalue is going to require more 3003 // AST annotation than this. 3004 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false); 3005 } 3006 return false; 3007 } 3008 3009 // -- Otherwise, a temporary of type "cv1 T1" is created and 3010 // initialized from the initializer expression using the 3011 // rules for a non-reference copy initialization (8.5). The 3012 // reference is then bound to the temporary. If T1 is 3013 // reference-related to T2, cv1 must be the same 3014 // cv-qualification as, or greater cv-qualification than, 3015 // cv2; otherwise, the program is ill-formed. 3016 if (RefRelationship == Ref_Related) { 3017 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3018 // we would be reference-compatible or reference-compatible with 3019 // added qualification. But that wasn't the case, so the reference 3020 // initialization fails. 3021 if (!ICS) 3022 Diag(Init->getSourceRange().getBegin(), 3023 diag::err_reference_init_drops_quals) 3024 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3025 << T2 << Init->getSourceRange(); 3026 return true; 3027 } 3028 3029 // If at least one of the types is a class type, the types are not 3030 // related, and we aren't allowed any user conversions, the 3031 // reference binding fails. This case is important for breaking 3032 // recursion, since TryImplicitConversion below will attempt to 3033 // create a temporary through the use of a copy constructor. 3034 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 3035 (T1->isRecordType() || T2->isRecordType())) { 3036 if (!ICS) 3037 Diag(Init->getSourceRange().getBegin(), 3038 diag::err_typecheck_convert_incompatible) 3039 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 3040 return true; 3041 } 3042 3043 // Actually try to convert the initializer to T1. 3044 if (ICS) { 3045 // C++ [over.ics.ref]p2: 3046 // 3047 // When a parameter of reference type is not bound directly to 3048 // an argument expression, the conversion sequence is the one 3049 // required to convert the argument expression to the 3050 // underlying type of the reference according to 3051 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3052 // to copy-initializing a temporary of the underlying type with 3053 // the argument expression. Any difference in top-level 3054 // cv-qualification is subsumed by the initialization itself 3055 // and does not constitute a conversion. 3056 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 3057 // Of course, that's still a reference binding. 3058 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 3059 ICS->Standard.ReferenceBinding = true; 3060 ICS->Standard.RRefBinding = isRValRef; 3061 } else if(ICS->ConversionKind == 3062 ImplicitConversionSequence::UserDefinedConversion) { 3063 ICS->UserDefined.After.ReferenceBinding = true; 3064 ICS->UserDefined.After.RRefBinding = isRValRef; 3065 } 3066 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 3067 } else { 3068 return PerformImplicitConversion(Init, T1, "initializing"); 3069 } 3070} 3071 3072/// CheckOverloadedOperatorDeclaration - Check whether the declaration 3073/// of this overloaded operator is well-formed. If so, returns false; 3074/// otherwise, emits appropriate diagnostics and returns true. 3075bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 3076 assert(FnDecl && FnDecl->isOverloadedOperator() && 3077 "Expected an overloaded operator declaration"); 3078 3079 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 3080 3081 // C++ [over.oper]p5: 3082 // The allocation and deallocation functions, operator new, 3083 // operator new[], operator delete and operator delete[], are 3084 // described completely in 3.7.3. The attributes and restrictions 3085 // found in the rest of this subclause do not apply to them unless 3086 // explicitly stated in 3.7.3. 3087 // FIXME: Write a separate routine for checking this. For now, just allow it. 3088 if (Op == OO_New || Op == OO_Array_New || 3089 Op == OO_Delete || Op == OO_Array_Delete) 3090 return false; 3091 3092 // C++ [over.oper]p6: 3093 // An operator function shall either be a non-static member 3094 // function or be a non-member function and have at least one 3095 // parameter whose type is a class, a reference to a class, an 3096 // enumeration, or a reference to an enumeration. 3097 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 3098 if (MethodDecl->isStatic()) 3099 return Diag(FnDecl->getLocation(), 3100 diag::err_operator_overload_static) << FnDecl->getDeclName(); 3101 } else { 3102 bool ClassOrEnumParam = false; 3103 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 3104 ParamEnd = FnDecl->param_end(); 3105 Param != ParamEnd; ++Param) { 3106 QualType ParamType = (*Param)->getType().getNonReferenceType(); 3107 if (ParamType->isDependentType() || ParamType->isRecordType() || 3108 ParamType->isEnumeralType()) { 3109 ClassOrEnumParam = true; 3110 break; 3111 } 3112 } 3113 3114 if (!ClassOrEnumParam) 3115 return Diag(FnDecl->getLocation(), 3116 diag::err_operator_overload_needs_class_or_enum) 3117 << FnDecl->getDeclName(); 3118 } 3119 3120 // C++ [over.oper]p8: 3121 // An operator function cannot have default arguments (8.3.6), 3122 // except where explicitly stated below. 3123 // 3124 // Only the function-call operator allows default arguments 3125 // (C++ [over.call]p1). 3126 if (Op != OO_Call) { 3127 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 3128 Param != FnDecl->param_end(); ++Param) { 3129 if ((*Param)->hasUnparsedDefaultArg()) 3130 return Diag((*Param)->getLocation(), 3131 diag::err_operator_overload_default_arg) 3132 << FnDecl->getDeclName(); 3133 else if (Expr *DefArg = (*Param)->getDefaultArg()) 3134 return Diag((*Param)->getLocation(), 3135 diag::err_operator_overload_default_arg) 3136 << FnDecl->getDeclName() << DefArg->getSourceRange(); 3137 } 3138 } 3139 3140 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 3141 { false, false, false } 3142#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3143 , { Unary, Binary, MemberOnly } 3144#include "clang/Basic/OperatorKinds.def" 3145 }; 3146 3147 bool CanBeUnaryOperator = OperatorUses[Op][0]; 3148 bool CanBeBinaryOperator = OperatorUses[Op][1]; 3149 bool MustBeMemberOperator = OperatorUses[Op][2]; 3150 3151 // C++ [over.oper]p8: 3152 // [...] Operator functions cannot have more or fewer parameters 3153 // than the number required for the corresponding operator, as 3154 // described in the rest of this subclause. 3155 unsigned NumParams = FnDecl->getNumParams() 3156 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 3157 if (Op != OO_Call && 3158 ((NumParams == 1 && !CanBeUnaryOperator) || 3159 (NumParams == 2 && !CanBeBinaryOperator) || 3160 (NumParams < 1) || (NumParams > 2))) { 3161 // We have the wrong number of parameters. 3162 unsigned ErrorKind; 3163 if (CanBeUnaryOperator && CanBeBinaryOperator) { 3164 ErrorKind = 2; // 2 -> unary or binary. 3165 } else if (CanBeUnaryOperator) { 3166 ErrorKind = 0; // 0 -> unary 3167 } else { 3168 assert(CanBeBinaryOperator && 3169 "All non-call overloaded operators are unary or binary!"); 3170 ErrorKind = 1; // 1 -> binary 3171 } 3172 3173 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 3174 << FnDecl->getDeclName() << NumParams << ErrorKind; 3175 } 3176 3177 // Overloaded operators other than operator() cannot be variadic. 3178 if (Op != OO_Call && 3179 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) { 3180 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 3181 << FnDecl->getDeclName(); 3182 } 3183 3184 // Some operators must be non-static member functions. 3185 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 3186 return Diag(FnDecl->getLocation(), 3187 diag::err_operator_overload_must_be_member) 3188 << FnDecl->getDeclName(); 3189 } 3190 3191 // C++ [over.inc]p1: 3192 // The user-defined function called operator++ implements the 3193 // prefix and postfix ++ operator. If this function is a member 3194 // function with no parameters, or a non-member function with one 3195 // parameter of class or enumeration type, it defines the prefix 3196 // increment operator ++ for objects of that type. If the function 3197 // is a member function with one parameter (which shall be of type 3198 // int) or a non-member function with two parameters (the second 3199 // of which shall be of type int), it defines the postfix 3200 // increment operator ++ for objects of that type. 3201 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 3202 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 3203 bool ParamIsInt = false; 3204 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 3205 ParamIsInt = BT->getKind() == BuiltinType::Int; 3206 3207 if (!ParamIsInt) 3208 return Diag(LastParam->getLocation(), 3209 diag::err_operator_overload_post_incdec_must_be_int) 3210 << LastParam->getType() << (Op == OO_MinusMinus); 3211 } 3212 3213 // Notify the class if it got an assignment operator. 3214 if (Op == OO_Equal) { 3215 // Would have returned earlier otherwise. 3216 assert(isa<CXXMethodDecl>(FnDecl) && 3217 "Overloaded = not member, but not filtered."); 3218 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 3219 Method->setCopyAssignment(true); 3220 Method->getParent()->addedAssignmentOperator(Context, Method); 3221 } 3222 3223 return false; 3224} 3225 3226/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 3227/// linkage specification, including the language and (if present) 3228/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 3229/// the location of the language string literal, which is provided 3230/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 3231/// the '{' brace. Otherwise, this linkage specification does not 3232/// have any braces. 3233Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 3234 SourceLocation ExternLoc, 3235 SourceLocation LangLoc, 3236 const char *Lang, 3237 unsigned StrSize, 3238 SourceLocation LBraceLoc) { 3239 LinkageSpecDecl::LanguageIDs Language; 3240 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3241 Language = LinkageSpecDecl::lang_c; 3242 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3243 Language = LinkageSpecDecl::lang_cxx; 3244 else { 3245 Diag(LangLoc, diag::err_bad_language); 3246 return DeclPtrTy(); 3247 } 3248 3249 // FIXME: Add all the various semantics of linkage specifications 3250 3251 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 3252 LangLoc, Language, 3253 LBraceLoc.isValid()); 3254 CurContext->addDecl(D); 3255 PushDeclContext(S, D); 3256 return DeclPtrTy::make(D); 3257} 3258 3259/// ActOnFinishLinkageSpecification - Completely the definition of 3260/// the C++ linkage specification LinkageSpec. If RBraceLoc is 3261/// valid, it's the position of the closing '}' brace in a linkage 3262/// specification that uses braces. 3263Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 3264 DeclPtrTy LinkageSpec, 3265 SourceLocation RBraceLoc) { 3266 if (LinkageSpec) 3267 PopDeclContext(); 3268 return LinkageSpec; 3269} 3270 3271/// \brief Perform semantic analysis for the variable declaration that 3272/// occurs within a C++ catch clause, returning the newly-created 3273/// variable. 3274VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 3275 DeclaratorInfo *DInfo, 3276 IdentifierInfo *Name, 3277 SourceLocation Loc, 3278 SourceRange Range) { 3279 bool Invalid = false; 3280 3281 // Arrays and functions decay. 3282 if (ExDeclType->isArrayType()) 3283 ExDeclType = Context.getArrayDecayedType(ExDeclType); 3284 else if (ExDeclType->isFunctionType()) 3285 ExDeclType = Context.getPointerType(ExDeclType); 3286 3287 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 3288 // The exception-declaration shall not denote a pointer or reference to an 3289 // incomplete type, other than [cv] void*. 3290 // N2844 forbids rvalue references. 3291 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 3292 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 3293 Invalid = true; 3294 } 3295 3296 QualType BaseType = ExDeclType; 3297 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 3298 unsigned DK = diag::err_catch_incomplete; 3299 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 3300 BaseType = Ptr->getPointeeType(); 3301 Mode = 1; 3302 DK = diag::err_catch_incomplete_ptr; 3303 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 3304 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 3305 BaseType = Ref->getPointeeType(); 3306 Mode = 2; 3307 DK = diag::err_catch_incomplete_ref; 3308 } 3309 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 3310 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 3311 Invalid = true; 3312 3313 if (!Invalid && !ExDeclType->isDependentType() && 3314 RequireNonAbstractType(Loc, ExDeclType, 3315 diag::err_abstract_type_in_decl, 3316 AbstractVariableType)) 3317 Invalid = true; 3318 3319 // FIXME: Need to test for ability to copy-construct and destroy the 3320 // exception variable. 3321 3322 // FIXME: Need to check for abstract classes. 3323 3324 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 3325 Name, ExDeclType, DInfo, VarDecl::None); 3326 3327 if (Invalid) 3328 ExDecl->setInvalidDecl(); 3329 3330 return ExDecl; 3331} 3332 3333/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 3334/// handler. 3335Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 3336 DeclaratorInfo *DInfo = 0; 3337 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 3338 3339 bool Invalid = D.isInvalidType(); 3340 IdentifierInfo *II = D.getIdentifier(); 3341 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3342 // The scope should be freshly made just for us. There is just no way 3343 // it contains any previous declaration. 3344 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 3345 if (PrevDecl->isTemplateParameter()) { 3346 // Maybe we will complain about the shadowed template parameter. 3347 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3348 } 3349 } 3350 3351 if (D.getCXXScopeSpec().isSet() && !Invalid) { 3352 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 3353 << D.getCXXScopeSpec().getRange(); 3354 Invalid = true; 3355 } 3356 3357 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 3358 D.getIdentifier(), 3359 D.getIdentifierLoc(), 3360 D.getDeclSpec().getSourceRange()); 3361 3362 if (Invalid) 3363 ExDecl->setInvalidDecl(); 3364 3365 // Add the exception declaration into this scope. 3366 if (II) 3367 PushOnScopeChains(ExDecl, S); 3368 else 3369 CurContext->addDecl(ExDecl); 3370 3371 ProcessDeclAttributes(S, ExDecl, D); 3372 return DeclPtrTy::make(ExDecl); 3373} 3374 3375Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 3376 ExprArg assertexpr, 3377 ExprArg assertmessageexpr) { 3378 Expr *AssertExpr = (Expr *)assertexpr.get(); 3379 StringLiteral *AssertMessage = 3380 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 3381 3382 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 3383 llvm::APSInt Value(32); 3384 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 3385 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 3386 AssertExpr->getSourceRange(); 3387 return DeclPtrTy(); 3388 } 3389 3390 if (Value == 0) { 3391 std::string str(AssertMessage->getStrData(), 3392 AssertMessage->getByteLength()); 3393 Diag(AssertLoc, diag::err_static_assert_failed) 3394 << str << AssertExpr->getSourceRange(); 3395 } 3396 } 3397 3398 assertexpr.release(); 3399 assertmessageexpr.release(); 3400 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 3401 AssertExpr, AssertMessage); 3402 3403 CurContext->addDecl(Decl); 3404 return DeclPtrTy::make(Decl); 3405} 3406 3407Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S, 3408 llvm::PointerUnion<const DeclSpec*,Declarator*> DU, 3409 bool IsDefinition) { 3410 Declarator *D = DU.dyn_cast<Declarator*>(); 3411 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>()); 3412 3413 assert(DS.isFriendSpecified()); 3414 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 3415 3416 // If there's no declarator, then this can only be a friend class 3417 // declaration (or else it's just syntactically invalid). 3418 if (!D) { 3419 SourceLocation Loc = DS.getSourceRange().getBegin(); 3420 3421 QualType T; 3422 DeclContext *DC; 3423 3424 // In C++0x, we just accept any old type. 3425 if (getLangOptions().CPlusPlus0x) { 3426 bool invalid = false; 3427 QualType T = ConvertDeclSpecToType(DS, Loc, invalid); 3428 if (invalid) 3429 return DeclPtrTy(); 3430 3431 // The semantic context in which to create the decl. If it's not 3432 // a record decl (or we don't yet know if it is), create it in the 3433 // current context. 3434 DC = CurContext; 3435 if (const RecordType *RT = T->getAs<RecordType>()) 3436 DC = RT->getDecl()->getDeclContext(); 3437 3438 // The C++98 rules are somewhat more complex. 3439 } else { 3440 // C++ [class.friend]p2: 3441 // An elaborated-type-specifier shall be used in a friend declaration 3442 // for a class.* 3443 // * The class-key of the elaborated-type-specifier is required. 3444 CXXRecordDecl *RD = 0; 3445 3446 switch (DS.getTypeSpecType()) { 3447 case DeclSpec::TST_class: 3448 case DeclSpec::TST_struct: 3449 case DeclSpec::TST_union: 3450 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep()); 3451 if (!RD) return DeclPtrTy(); 3452 break; 3453 3454 case DeclSpec::TST_typename: 3455 if (const RecordType *RT = 3456 ((const Type*) DS.getTypeRep())->getAs<RecordType>()) 3457 RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3458 // fallthrough 3459 default: 3460 if (RD) { 3461 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type) 3462 << (RD->isUnion()) 3463 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 3464 RD->isUnion() ? " union" : " class"); 3465 return DeclPtrTy::make(RD); 3466 } 3467 3468 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 3469 << DS.getSourceRange(); 3470 return DeclPtrTy(); 3471 } 3472 3473 // The record declaration we get from friend declarations is not 3474 // canonicalized; see ActOnTag. 3475 3476 // C++ [class.friend]p2: A class shall not be defined inside 3477 // a friend declaration. 3478 if (RD->isDefinition()) 3479 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class) 3480 << RD->getSourceRange(); 3481 3482 // C++98 [class.friend]p1: A friend of a class is a function 3483 // or class that is not a member of the class . . . 3484 // But that's a silly restriction which nobody implements for 3485 // inner classes, and C++0x removes it anyway, so we only report 3486 // this (as a warning) if we're being pedantic. 3487 // 3488 // Also, definitions currently get treated in a way that causes 3489 // this error, so only report it if we didn't see a definition. 3490 else if (RD->getDeclContext() == CurContext && 3491 !getLangOptions().CPlusPlus0x) 3492 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 3493 3494 T = QualType(RD->getTypeForDecl(), 0); 3495 DC = RD->getDeclContext(); 3496 } 3497 3498 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T, 3499 DS.getFriendSpecLoc()); 3500 FCD->setLexicalDeclContext(CurContext); 3501 3502 if (CurContext->isDependentContext()) 3503 CurContext->addHiddenDecl(FCD); 3504 else 3505 CurContext->addDecl(FCD); 3506 3507 return DeclPtrTy::make(FCD); 3508 } 3509 3510 // We have a declarator. 3511 assert(D); 3512 3513 SourceLocation Loc = D->getIdentifierLoc(); 3514 DeclaratorInfo *DInfo = 0; 3515 QualType T = GetTypeForDeclarator(*D, S, &DInfo); 3516 3517 // C++ [class.friend]p1 3518 // A friend of a class is a function or class.... 3519 // Note that this sees through typedefs, which is intended. 3520 if (!T->isFunctionType()) { 3521 Diag(Loc, diag::err_unexpected_friend); 3522 3523 // It might be worthwhile to try to recover by creating an 3524 // appropriate declaration. 3525 return DeclPtrTy(); 3526 } 3527 3528 // C++ [namespace.memdef]p3 3529 // - If a friend declaration in a non-local class first declares a 3530 // class or function, the friend class or function is a member 3531 // of the innermost enclosing namespace. 3532 // - The name of the friend is not found by simple name lookup 3533 // until a matching declaration is provided in that namespace 3534 // scope (either before or after the class declaration granting 3535 // friendship). 3536 // - If a friend function is called, its name may be found by the 3537 // name lookup that considers functions from namespaces and 3538 // classes associated with the types of the function arguments. 3539 // - When looking for a prior declaration of a class or a function 3540 // declared as a friend, scopes outside the innermost enclosing 3541 // namespace scope are not considered. 3542 3543 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec(); 3544 DeclarationName Name = GetNameForDeclarator(*D); 3545 assert(Name); 3546 3547 // The existing declaration we found. 3548 FunctionDecl *FD = NULL; 3549 3550 // The context we found the declaration in, or in which we should 3551 // create the declaration. 3552 DeclContext *DC; 3553 3554 // FIXME: handle local classes 3555 3556 // Recover from invalid scope qualifiers as if they just weren't there. 3557 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 3558 DC = computeDeclContext(ScopeQual); 3559 3560 // FIXME: handle dependent contexts 3561 if (!DC) return DeclPtrTy(); 3562 3563 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 3564 3565 // If searching in that context implicitly found a declaration in 3566 // a different context, treat it like it wasn't found at all. 3567 // TODO: better diagnostics for this case. Suggesting the right 3568 // qualified scope would be nice... 3569 if (!Dec || Dec->getDeclContext() != DC) { 3570 D->setInvalidType(); 3571 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 3572 return DeclPtrTy(); 3573 } 3574 3575 // C++ [class.friend]p1: A friend of a class is a function or 3576 // class that is not a member of the class . . . 3577 if (DC == CurContext) 3578 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 3579 3580 FD = cast<FunctionDecl>(Dec); 3581 3582 // Otherwise walk out to the nearest namespace scope looking for matches. 3583 } else { 3584 // TODO: handle local class contexts. 3585 3586 DC = CurContext; 3587 while (true) { 3588 // Skip class contexts. If someone can cite chapter and verse 3589 // for this behavior, that would be nice --- it's what GCC and 3590 // EDG do, and it seems like a reasonable intent, but the spec 3591 // really only says that checks for unqualified existing 3592 // declarations should stop at the nearest enclosing namespace, 3593 // not that they should only consider the nearest enclosing 3594 // namespace. 3595 while (DC->isRecord()) DC = DC->getParent(); 3596 3597 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 3598 3599 // TODO: decide what we think about using declarations. 3600 if (Dec) { 3601 FD = cast<FunctionDecl>(Dec); 3602 break; 3603 } 3604 if (DC->isFileContext()) break; 3605 DC = DC->getParent(); 3606 } 3607 3608 // C++ [class.friend]p1: A friend of a class is a function or 3609 // class that is not a member of the class . . . 3610 // C++0x changes this for both friend types and functions. 3611 // Most C++ 98 compilers do seem to give an error here, so 3612 // we do, too. 3613 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x) 3614 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 3615 } 3616 3617 bool Redeclaration = (FD != 0); 3618 3619 // If we found a match, create a friend function declaration with 3620 // that function as the previous declaration. 3621 if (Redeclaration) { 3622 // Create it in the semantic context of the original declaration. 3623 DC = FD->getDeclContext(); 3624 3625 // If we didn't find something matching the type exactly, create 3626 // a declaration. This declaration should only be findable via 3627 // argument-dependent lookup. 3628 } else { 3629 assert(DC->isFileContext()); 3630 3631 // This implies that it has to be an operator or function. 3632 if (D->getKind() == Declarator::DK_Constructor || 3633 D->getKind() == Declarator::DK_Destructor || 3634 D->getKind() == Declarator::DK_Conversion) { 3635 Diag(Loc, diag::err_introducing_special_friend) << 3636 (D->getKind() == Declarator::DK_Constructor ? 0 : 3637 D->getKind() == Declarator::DK_Destructor ? 1 : 2); 3638 return DeclPtrTy(); 3639 } 3640 } 3641 3642 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo, 3643 /* PrevDecl = */ FD, 3644 MultiTemplateParamsArg(*this), 3645 IsDefinition, 3646 Redeclaration); 3647 FD = cast_or_null<FriendFunctionDecl>(ND); 3648 3649 assert(FD->getDeclContext() == DC); 3650 assert(FD->getLexicalDeclContext() == CurContext); 3651 3652 // If this is a dependent context, just add the decl to the 3653 // class's decl list and don't both with the lookup tables. This 3654 // doesn't affect lookup because any call that might find this 3655 // function via ADL necessarily has to involve dependently-typed 3656 // arguments and hence can't be resolved until 3657 // template-instantiation anyway. 3658 if (CurContext->isDependentContext()) 3659 CurContext->addHiddenDecl(FD); 3660 else 3661 CurContext->addDecl(FD); 3662 3663 return DeclPtrTy::make(FD); 3664} 3665 3666void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 3667 AdjustDeclIfTemplate(dcl); 3668 3669 Decl *Dcl = dcl.getAs<Decl>(); 3670 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 3671 if (!Fn) { 3672 Diag(DelLoc, diag::err_deleted_non_function); 3673 return; 3674 } 3675 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 3676 Diag(DelLoc, diag::err_deleted_decl_not_first); 3677 Diag(Prev->getLocation(), diag::note_previous_declaration); 3678 // If the declaration wasn't the first, we delete the function anyway for 3679 // recovery. 3680 } 3681 Fn->setDeleted(); 3682} 3683 3684static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 3685 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 3686 ++CI) { 3687 Stmt *SubStmt = *CI; 3688 if (!SubStmt) 3689 continue; 3690 if (isa<ReturnStmt>(SubStmt)) 3691 Self.Diag(SubStmt->getSourceRange().getBegin(), 3692 diag::err_return_in_constructor_handler); 3693 if (!isa<Expr>(SubStmt)) 3694 SearchForReturnInStmt(Self, SubStmt); 3695 } 3696} 3697 3698void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 3699 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 3700 CXXCatchStmt *Handler = TryBlock->getHandler(I); 3701 SearchForReturnInStmt(*this, Handler); 3702 } 3703} 3704 3705bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 3706 const CXXMethodDecl *Old) { 3707 QualType NewTy = New->getType()->getAsFunctionType()->getResultType(); 3708 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType(); 3709 3710 QualType CNewTy = Context.getCanonicalType(NewTy); 3711 QualType COldTy = Context.getCanonicalType(OldTy); 3712 3713 if (CNewTy == COldTy && 3714 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers()) 3715 return false; 3716 3717 // Check if the return types are covariant 3718 QualType NewClassTy, OldClassTy; 3719 3720 /// Both types must be pointers or references to classes. 3721 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 3722 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 3723 NewClassTy = NewPT->getPointeeType(); 3724 OldClassTy = OldPT->getPointeeType(); 3725 } 3726 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 3727 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 3728 NewClassTy = NewRT->getPointeeType(); 3729 OldClassTy = OldRT->getPointeeType(); 3730 } 3731 } 3732 3733 // The return types aren't either both pointers or references to a class type. 3734 if (NewClassTy.isNull()) { 3735 Diag(New->getLocation(), 3736 diag::err_different_return_type_for_overriding_virtual_function) 3737 << New->getDeclName() << NewTy << OldTy; 3738 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3739 3740 return true; 3741 } 3742 3743 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) { 3744 // Check if the new class derives from the old class. 3745 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 3746 Diag(New->getLocation(), 3747 diag::err_covariant_return_not_derived) 3748 << New->getDeclName() << NewTy << OldTy; 3749 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3750 return true; 3751 } 3752 3753 // Check if we the conversion from derived to base is valid. 3754 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 3755 diag::err_covariant_return_inaccessible_base, 3756 diag::err_covariant_return_ambiguous_derived_to_base_conv, 3757 // FIXME: Should this point to the return type? 3758 New->getLocation(), SourceRange(), New->getDeclName())) { 3759 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3760 return true; 3761 } 3762 } 3763 3764 // The qualifiers of the return types must be the same. 3765 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) { 3766 Diag(New->getLocation(), 3767 diag::err_covariant_return_type_different_qualifications) 3768 << New->getDeclName() << NewTy << OldTy; 3769 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3770 return true; 3771 }; 3772 3773 3774 // The new class type must have the same or less qualifiers as the old type. 3775 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 3776 Diag(New->getLocation(), 3777 diag::err_covariant_return_type_class_type_more_qualified) 3778 << New->getDeclName() << NewTy << OldTy; 3779 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3780 return true; 3781 }; 3782 3783 return false; 3784} 3785 3786bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 3787 const CXXMethodDecl *Old) 3788{ 3789 return CheckExceptionSpecSubset(diag::err_override_exception_spec, 3790 diag::note_overridden_virtual_function, 3791 Old->getType()->getAsFunctionProtoType(), 3792 Old->getLocation(), 3793 New->getType()->getAsFunctionProtoType(), 3794 New->getLocation()); 3795} 3796 3797/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3798/// initializer for the declaration 'Dcl'. 3799/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3800/// static data member of class X, names should be looked up in the scope of 3801/// class X. 3802void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 3803 AdjustDeclIfTemplate(Dcl); 3804 3805 Decl *D = Dcl.getAs<Decl>(); 3806 // If there is no declaration, there was an error parsing it. 3807 if (D == 0) 3808 return; 3809 3810 // Check whether it is a declaration with a nested name specifier like 3811 // int foo::bar; 3812 if (!D->isOutOfLine()) 3813 return; 3814 3815 // C++ [basic.lookup.unqual]p13 3816 // 3817 // A name used in the definition of a static data member of class X 3818 // (after the qualified-id of the static member) is looked up as if the name 3819 // was used in a member function of X. 3820 3821 // Change current context into the context of the initializing declaration. 3822 EnterDeclaratorContext(S, D->getDeclContext()); 3823} 3824 3825/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3826/// initializer for the declaration 'Dcl'. 3827void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 3828 AdjustDeclIfTemplate(Dcl); 3829 3830 Decl *D = Dcl.getAs<Decl>(); 3831 // If there is no declaration, there was an error parsing it. 3832 if (D == 0) 3833 return; 3834 3835 // Check whether it is a declaration with a nested name specifier like 3836 // int foo::bar; 3837 if (!D->isOutOfLine()) 3838 return; 3839 3840 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 3841 ExitDeclaratorContext(S); 3842} 3843