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