blob: 6b0c04440a8c4e4cf7d51a5752b1b45f0a84a461 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redlf53597f2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077}
78
Steve Naroff1b273c42007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000083 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
Chris Lattner50dd2892008-02-26 00:51:44 +000087
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
91 return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy,
92 OpLoc));
Chris Lattner50dd2892008-02-26 00:51:44 +000093}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000094
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000096 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97 /// is a non-lvalue expression whose value is the address of the object for
98 /// which the function is called.
99
Sebastian Redlf53597f2009-03-15 17:47:39 +0000100 if (!isa<FunctionDecl>(CurContext))
101 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000102
103 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
104 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXThisExpr(ThisLoc,
106 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000110
111/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
112/// Can be interpreted either as function-style casting ("int(x)")
113/// or class type construction ("ClassType(x,y,z)")
114/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000116Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
117 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000119 SourceLocation *CommaLocs,
120 SourceLocation RParenLoc) {
121 assert(TypeRep && "Missing type!");
122 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000123 unsigned NumExprs = exprs.size();
124 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000125 SourceLocation TyBeginLoc = TypeRange.getBegin();
126 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000129 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000131
132 // FIXME: Is this correct?
133 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000134 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
135 TyBeginLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000136 Exprs, NumExprs,
137 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000138 }
139
140
Douglas Gregor506ae412009-01-16 18:33:17 +0000141 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000142 // If the expression list is a single expression, the type conversion
143 // expression is equivalent (in definedness, and if defined in meaning) to the
144 // corresponding cast expression.
145 //
146 if (NumExprs == 1) {
147 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148 return ExprError();
149 exprs.release();
150 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
151 Ty, TyBeginLoc, Exprs[0],
152 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000153 }
154
Douglas Gregor506ae412009-01-16 18:33:17 +0000155 if (const RecordType *RT = Ty->getAsRecordType()) {
156 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157
Douglas Gregor506ae412009-01-16 18:33:17 +0000158 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
159 CXXConstructorDecl *Constructor
160 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
161 TypeRange.getBegin(),
162 SourceRange(TypeRange.getBegin(),
163 RParenLoc),
164 DeclarationName(),
165 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000166
Sebastian Redlf53597f2009-03-15 17:47:39 +0000167 if (!Constructor)
168 return ExprError();
169
Anders Carlsson26de5492009-04-24 05:23:13 +0000170 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
171
Sebastian Redlf53597f2009-03-15 17:47:39 +0000172 exprs.release();
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000173 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
174 Constructor, Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 TyBeginLoc, Exprs,
176 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000177 }
178
179 // Fall through to value-initialize an object of class type that
180 // doesn't have a user-declared default constructor.
181 }
182
183 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000184 // If the expression list specifies more than a single value, the type shall
185 // be a class with a suitably declared constructor.
186 //
187 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000188 return ExprError(Diag(CommaLocs[0],
189 diag::err_builtin_func_cast_more_than_one_arg)
190 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000191
192 assert(NumExprs == 0 && "Expected 0 expressions");
193
Douglas Gregor506ae412009-01-16 18:33:17 +0000194 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000195 // The expression T(), where T is a simple-type-specifier for a non-array
196 // complete object type or the (possibly cv-qualified) void type, creates an
197 // rvalue of the specified type, which is value-initialized.
198 //
199 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000200 return ExprError(Diag(TyBeginLoc,
201 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000202 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000203 RequireCompleteType(TyBeginLoc, Ty,
204 diag::err_invalid_incomplete_type_use, FullRange))
205 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000206
Anders Carlsson8211eff2009-03-24 01:19:16 +0000207 if (RequireNonAbstractType(TyBeginLoc, Ty,
208 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000209 return ExprError();
210
Sebastian Redlf53597f2009-03-15 17:47:39 +0000211 exprs.release();
212 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000214
215
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000216/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
217/// @code new (memory) int[size][4] @endcode
218/// or
219/// @code ::new Foo(23, "hello") @endcode
220/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000221Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000222Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000223 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000224 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000225 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000226 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000227 SourceLocation ConstructorRParen)
228{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000229 Expr *ArraySize = 0;
230 unsigned Skip = 0;
231 // If the specified type is an array, unwrap it and save the expression.
232 if (D.getNumTypeObjects() > 0 &&
233 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
234 DeclaratorChunk &Chunk = D.getTypeObject(0);
235 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000236 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
237 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000238 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000239 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
240 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000241 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
242 Skip = 1;
243 }
244
245 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000246 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000247 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000248
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000249 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000250 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000251
Sebastian Redl28507842009-02-26 14:39:58 +0000252 QualType ResultType = AllocType->isDependentType()
253 ? Context.DependentTy
254 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000255
256 // That every array dimension except the first is constant was already
257 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000258
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000259 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
260 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000261 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000262 QualType SizeType = ArraySize->getType();
263 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
265 diag::err_array_size_not_integral)
266 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000267 // Let's see if this is a constant < 0. If so, we reject it out of hand.
268 // We don't care about special rules, so we tell the machinery it's not
269 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000270 if (!ArraySize->isValueDependent()) {
271 llvm::APSInt Value;
272 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
273 if (Value < llvm::APSInt(
274 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000275 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
276 diag::err_typecheck_negative_array_size)
277 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000278 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 }
280 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000281
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000282 FunctionDecl *OperatorNew = 0;
283 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000284 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
285 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000286 if (!AllocType->isDependentType() &&
287 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
288 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000289 SourceRange(PlacementLParen, PlacementRParen),
290 UseGlobal, AllocType, ArraySize, PlaceArgs,
291 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000292 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000293
294 bool Init = ConstructorLParen.isValid();
295 // --- Choosing a constructor ---
296 // C++ 5.3.4p15
297 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
298 // the object is not initialized. If the object, or any part of it, is
299 // const-qualified, it's an error.
300 // 2) If T is a POD and there's an empty initializer, the object is value-
301 // initialized.
302 // 3) If T is a POD and there's one initializer argument, the object is copy-
303 // constructed.
304 // 4) If T is a POD and there's more initializer arguments, it's an error.
305 // 5) If T is not a POD, the initializer arguments are used as constructor
306 // arguments.
307 //
308 // Or by the C++0x formulation:
309 // 1) If there's no initializer, the object is default-initialized according
310 // to C++0x rules.
311 // 2) Otherwise, the object is direct-initialized.
312 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000313 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
314 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000315 if (AllocType->isDependentType()) {
316 // Skip all the checks.
317 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000318 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000319 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000320 // FIXME: This is incorrect for when there is an empty initializer and
321 // no user-defined constructor. Must zero-initialize, not default-construct.
322 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000323 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000324 D.getSourceRange().getBegin(),
325 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000327 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328 NumConsArgs != 0 ? IK_Direct : IK_Default);
329 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000330 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000331 } else {
332 if (!Init) {
333 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000334 if (AllocType.isConstQualified())
335 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
336 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000337 } else if (NumConsArgs == 0) {
338 // Object is value-initialized. Do nothing.
339 } else if (NumConsArgs == 1) {
340 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000341 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000343 DeclarationName() /*AllocType.getAsString()*/,
344 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000345 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000346 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000347 return ExprError(Diag(StartLoc,
348 diag::err_builtin_direct_init_more_than_one_arg)
349 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000350 }
351 }
352
353 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
354
Sebastian Redlf53597f2009-03-15 17:47:39 +0000355 PlacementArgs.release();
356 ConstructorArgs.release();
357 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000358 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000359 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000360 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361}
362
363/// CheckAllocatedType - Checks that a type is suitable as the allocated type
364/// in a new-expression.
365/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000366bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000367{
368 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
369 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000370 if (AllocType->isFunctionType())
371 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
372 << AllocType << 0 << D.getSourceRange();
373 else if (AllocType->isReferenceType())
374 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
375 << AllocType << 1 << D.getSourceRange();
376 else if (!AllocType->isDependentType() &&
377 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
378 diag::err_new_incomplete_type,
379 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000380 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000381 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
382 diag::err_allocation_of_abstract_type))
383 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000384
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000385 // Every dimension shall be of constant size.
386 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000387 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
388 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000389 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
390 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000391 return true;
392 }
393 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395 }
396
397 return false;
398}
399
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000400/// FindAllocationFunctions - Finds the overloads of operator new and delete
401/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000402bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
403 bool UseGlobal, QualType AllocType,
404 bool IsArray, Expr **PlaceArgs,
405 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000406 FunctionDecl *&OperatorNew,
407 FunctionDecl *&OperatorDelete)
408{
409 // --- Choosing an allocation function ---
410 // C++ 5.3.4p8 - 14 & 18
411 // 1) If UseGlobal is true, only look in the global scope. Else, also look
412 // in the scope of the allocated class.
413 // 2) If an array size is given, look for operator new[], else look for
414 // operator new.
415 // 3) The first argument is always size_t. Append the arguments from the
416 // placement form.
417 // FIXME: Also find the appropriate delete operator.
418
419 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
420 // We don't care about the actual value of this argument.
421 // FIXME: Should the Sema create the expression and embed it in the syntax
422 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000423 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000424 Context.Target.getPointerWidth(0)),
425 Context.getSizeType(),
426 SourceLocation());
427 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
428
429 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
430 IsArray ? OO_Array_New : OO_New);
431 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000432 CXXRecordDecl *Record
433 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000434 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000435 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000436 AllocArgs.size(), Record, /*AllowMissing=*/true,
437 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000438 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000439 }
440 if (!OperatorNew) {
441 // Didn't find a member overload. Look for a global one.
442 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000443 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000444 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000445 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
446 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000447 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000448 }
449
Sebastian Redl7f662392008-12-04 22:20:51 +0000450 // FIXME: This is leaked on error. But so much is currently in Sema that it's
451 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000452 AllocArgs[0]->Destroy(Context);
453 return false;
454}
455
Sebastian Redl7f662392008-12-04 22:20:51 +0000456/// FindAllocationOverload - Find an fitting overload for the allocation
457/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000458bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
459 DeclarationName Name, Expr** Args,
460 unsigned NumArgs, DeclContext *Ctx,
461 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000462{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000463 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000464 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000465 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000466 if (AllowMissing)
467 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000468 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000469 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000470 }
471
472 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000473 for (; Alloc != AllocEnd; ++Alloc) {
474 // Even member operator new/delete are implicitly treated as
475 // static, so don't use AddMemberCandidate.
476 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
477 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
478 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000479 }
480
481 // Do the resolution.
482 OverloadCandidateSet::iterator Best;
483 switch(BestViableFunction(Candidates, Best)) {
484 case OR_Success: {
485 // Got one!
486 FunctionDecl *FnDecl = Best->Function;
487 // The first argument is size_t, and the first parameter must be size_t,
488 // too. This is checked on declaration and can be assumed. (It can't be
489 // asserted on, though, since invalid decls are left in there.)
490 for (unsigned i = 1; i < NumArgs; ++i) {
491 // FIXME: Passing word to diagnostic.
492 if (PerformCopyInitialization(Args[i-1],
493 FnDecl->getParamDecl(i)->getType(),
494 "passing"))
495 return true;
496 }
497 Operator = FnDecl;
498 return false;
499 }
500
501 case OR_No_Viable_Function:
502 if (AllowMissing)
503 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000505 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000506 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
507 return true;
508
509 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000510 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000511 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000512 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
513 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000514
515 case OR_Deleted:
516 Diag(StartLoc, diag::err_ovl_deleted_call)
517 << Best->Function->isDeleted()
518 << Name << Range;
519 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
520 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000521 }
522 assert(false && "Unreachable, bad result from BestViableFunction");
523 return true;
524}
525
526
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000527/// DeclareGlobalNewDelete - Declare the global forms of operator new and
528/// delete. These are:
529/// @code
530/// void* operator new(std::size_t) throw(std::bad_alloc);
531/// void* operator new[](std::size_t) throw(std::bad_alloc);
532/// void operator delete(void *) throw();
533/// void operator delete[](void *) throw();
534/// @endcode
535/// Note that the placement and nothrow forms of new are *not* implicitly
536/// declared. Their use requires including \<new\>.
537void Sema::DeclareGlobalNewDelete()
538{
539 if (GlobalNewDeleteDeclared)
540 return;
541 GlobalNewDeleteDeclared = true;
542
543 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
544 QualType SizeT = Context.getSizeType();
545
546 // FIXME: Exception specifications are not added.
547 DeclareGlobalAllocationFunction(
548 Context.DeclarationNames.getCXXOperatorName(OO_New),
549 VoidPtr, SizeT);
550 DeclareGlobalAllocationFunction(
551 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
552 VoidPtr, SizeT);
553 DeclareGlobalAllocationFunction(
554 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
555 Context.VoidTy, VoidPtr);
556 DeclareGlobalAllocationFunction(
557 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
558 Context.VoidTy, VoidPtr);
559}
560
561/// DeclareGlobalAllocationFunction - Declares a single implicit global
562/// allocation function if it doesn't already exist.
563void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
564 QualType Return, QualType Argument)
565{
566 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
567
568 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000569 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000570 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000571 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000572 Alloc != AllocEnd; ++Alloc) {
573 // FIXME: Do we need to check for default arguments here?
574 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
575 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000576 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000577 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000578 }
579 }
580
581 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
582 FunctionDecl *Alloc =
583 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000584 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000585 SourceLocation());
586 Alloc->setImplicit();
587 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000588 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000589 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000590
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000591 // FIXME: Also add this declaration to the IdentifierResolver, but
592 // make sure it is at the end of the chain to coincide with the
593 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000594 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000595}
596
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000597/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
598/// @code ::delete ptr; @endcode
599/// or
600/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000601Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000602Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000603 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000604{
605 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
606 // having a single conversion function to a pointer type. The result has
607 // type void."
608 // DR599 amends "pointer type" to "pointer to object type" in both cases.
609
Sebastian Redlf53597f2009-03-15 17:47:39 +0000610 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000611 if (!Ex->isTypeDependent()) {
612 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000613
Sebastian Redl28507842009-02-26 14:39:58 +0000614 if (Type->isRecordType()) {
615 // FIXME: Find that one conversion function and amend the type.
616 }
617
Sebastian Redlf53597f2009-03-15 17:47:39 +0000618 if (!Type->isPointerType())
619 return ExprError(Diag(StartLoc, diag::err_delete_operand)
620 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000621
622 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000623 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000624 return ExprError(Diag(StartLoc, diag::err_delete_operand)
625 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000626 else if (!Pointee->isDependentType() &&
627 RequireCompleteType(StartLoc, Pointee,
628 diag::warn_delete_incomplete,
629 Ex->getSourceRange()))
630 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000631
632 // FIXME: Look up the correct operator delete overload and pass a pointer
633 // along.
634 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000635 }
636
Sebastian Redlf53597f2009-03-15 17:47:39 +0000637 Operand.release();
638 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
639 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000640}
641
642
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000643/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
644/// C++ if/switch/while/for statement.
645/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000646Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000647Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
648 Declarator &D,
649 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000650 ExprArg AssignExprVal) {
651 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000652
653 // C++ 6.4p2:
654 // The declarator shall not specify a function or an array.
655 // The type-specifier-seq shall not contain typedef and shall not declare a
656 // new class or enumeration.
657
658 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
659 "Parser allowed 'typedef' as storage class of condition decl.");
660
661 QualType Ty = GetTypeForDeclarator(D, S);
662
663 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
664 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
665 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000666 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
667 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000668 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000669 Diag(StartLoc, diag::err_invalid_use_of_array_type)
670 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000671 } else if (const RecordType *RT = Ty->getAsRecordType()) {
672 RecordDecl *RD = RT->getDecl();
673 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000674 if (RD->isDefinition() &&
675 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000676 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
677 } else if (const EnumType *ET = Ty->getAsEnumType()) {
678 EnumDecl *ED = ET->getDecl();
679 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000680 if (ED->isDefinition() &&
681 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000682 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
683 }
684
Chris Lattnerb28317a2009-03-28 19:18:32 +0000685 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000686 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000687 return ExprError();
688 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000689
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000690 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000691 // We know that the decl had to be a VarDecl because that is the only type of
692 // decl that can be assigned and the grammar requires an '='.
693 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
694 VD->setDeclaredInCondition(true);
695 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000696}
697
698/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
699bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
700 // C++ 6.4p4:
701 // The value of a condition that is an initialized declaration in a statement
702 // other than a switch statement is the value of the declared variable
703 // implicitly converted to type bool. If that conversion is ill-formed, the
704 // program is ill-formed.
705 // The value of a condition that is an expression is the value of the
706 // expression, implicitly converted to bool.
707 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000708 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000709}
Douglas Gregor77a52232008-09-12 00:47:35 +0000710
711/// Helper function to determine whether this is the (deprecated) C++
712/// conversion from a string literal to a pointer to non-const char or
713/// non-const wchar_t (for narrow and wide string literals,
714/// respectively).
715bool
716Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
717 // Look inside the implicit cast, if it exists.
718 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
719 From = Cast->getSubExpr();
720
721 // A string literal (2.13.4) that is not a wide string literal can
722 // be converted to an rvalue of type "pointer to char"; a wide
723 // string literal can be converted to an rvalue of type "pointer
724 // to wchar_t" (C++ 4.2p2).
725 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
726 if (const PointerType *ToPtrType = ToType->getAsPointerType())
727 if (const BuiltinType *ToPointeeType
728 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
729 // This conversion is considered only when there is an
730 // explicit appropriate pointer target type (C++ 4.2p2).
731 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
732 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
733 (!StrLit->isWide() &&
734 (ToPointeeType->getKind() == BuiltinType::Char_U ||
735 ToPointeeType->getKind() == BuiltinType::Char_S))))
736 return true;
737 }
738
739 return false;
740}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000741
742/// PerformImplicitConversion - Perform an implicit conversion of the
743/// expression From to the type ToType. Returns true if there was an
744/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000745/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000746/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000747/// explicit user-defined conversions are permitted. @p Elidable should be true
748/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
749/// resolution works differently in that case.
750bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000751Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000752 const char *Flavor, bool AllowExplicit,
753 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000754{
Sebastian Redle2b68332009-04-12 17:16:29 +0000755 ImplicitConversionSequence ICS;
756 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
757 if (Elidable && getLangOptions().CPlusPlus0x) {
758 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
759 AllowExplicit, /*ForceRValue*/true);
760 }
761 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
762 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
763 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000764 return PerformImplicitConversion(From, ToType, ICS, Flavor);
765}
766
767/// PerformImplicitConversion - Perform an implicit conversion of the
768/// expression From to the type ToType using the pre-computed implicit
769/// conversion sequence ICS. Returns true if there was an error, false
770/// otherwise. The expression From is replaced with the converted
771/// expression. Flavor is the kind of conversion we're performing,
772/// used in the error message.
773bool
774Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
775 const ImplicitConversionSequence &ICS,
776 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000777 switch (ICS.ConversionKind) {
778 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000779 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000780 return true;
781 break;
782
783 case ImplicitConversionSequence::UserDefinedConversion:
784 // FIXME: This is, of course, wrong. We'll need to actually call
785 // the constructor or conversion operator, and then cope with the
786 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000787 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000788 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000789 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000790
791 case ImplicitConversionSequence::EllipsisConversion:
792 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000793 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000794
795 case ImplicitConversionSequence::BadConversion:
796 return true;
797 }
798
799 // Everything went well.
800 return false;
801}
802
803/// PerformImplicitConversion - Perform an implicit conversion of the
804/// expression From to the type ToType by following the standard
805/// conversion sequence SCS. Returns true if there was an error, false
806/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000807/// expression. Flavor is the context in which we're performing this
808/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000809bool
810Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000811 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000812 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000813 // Overall FIXME: we are recomputing too many types here and doing
814 // far too much extra work. What this means is that we need to keep
815 // track of more information that is computed when we try the
816 // implicit conversion initially, so that we don't need to recompute
817 // anything here.
818 QualType FromType = From->getType();
819
Douglas Gregor225c41e2008-11-03 19:09:14 +0000820 if (SCS.CopyConstructor) {
821 // FIXME: Create a temporary object by calling the copy
822 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000823 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000824 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000825 return false;
826 }
827
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000828 // Perform the first implicit conversion.
829 switch (SCS.First) {
830 case ICK_Identity:
831 case ICK_Lvalue_To_Rvalue:
832 // Nothing to do.
833 break;
834
835 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000836 FromType = Context.getArrayDecayedType(FromType);
837 ImpCastExprToType(From, FromType);
838 break;
839
840 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000841 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000842 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
843 if (!Fn)
844 return true;
845
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000846 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
847 return true;
848
Douglas Gregor904eed32008-11-10 20:40:00 +0000849 FixOverloadedFunctionReference(From, Fn);
850 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000851 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000852 FromType = Context.getPointerType(FromType);
853 ImpCastExprToType(From, FromType);
854 break;
855
856 default:
857 assert(false && "Improper first standard conversion");
858 break;
859 }
860
861 // Perform the second implicit conversion
862 switch (SCS.Second) {
863 case ICK_Identity:
864 // Nothing to do.
865 break;
866
867 case ICK_Integral_Promotion:
868 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000869 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000870 case ICK_Integral_Conversion:
871 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000872 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000873 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000874 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000875 case ICK_Compatible_Conversion:
876 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000877 FromType = ToType.getUnqualifiedType();
878 ImpCastExprToType(From, FromType);
879 break;
880
881 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000882 if (SCS.IncompatibleObjC) {
883 // Diagnose incompatible Objective-C conversions
884 Diag(From->getSourceRange().getBegin(),
885 diag::ext_typecheck_convert_incompatible_pointer)
886 << From->getType() << ToType << Flavor
887 << From->getSourceRange();
888 }
889
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000890 if (CheckPointerConversion(From, ToType))
891 return true;
892 ImpCastExprToType(From, ToType);
893 break;
894
895 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000896 if (CheckMemberPointerConversion(From, ToType))
897 return true;
898 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000899 break;
900
901 case ICK_Boolean_Conversion:
902 FromType = Context.BoolTy;
903 ImpCastExprToType(From, FromType);
904 break;
905
906 default:
907 assert(false && "Improper second standard conversion");
908 break;
909 }
910
911 switch (SCS.Third) {
912 case ICK_Identity:
913 // Nothing to do.
914 break;
915
916 case ICK_Qualification:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000917 // FIXME: Not sure about lvalue vs rvalue here in the presence of
918 // rvalue references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000919 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000920 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000921 break;
922
923 default:
924 assert(false && "Improper second standard conversion");
925 break;
926 }
927
928 return false;
929}
930
Sebastian Redl64b45f72009-01-05 20:52:13 +0000931Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
932 SourceLocation KWLoc,
933 SourceLocation LParen,
934 TypeTy *Ty,
935 SourceLocation RParen) {
936 // FIXME: Some of the type traits have requirements. Interestingly, only the
937 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
938 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
939 // type is indeed a POD.
940
941 // There is no point in eagerly computing the value. The traits are designed
942 // to be used from type trait templates, so Ty will be a template parameter
943 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000944 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000945 QualType::getFromOpaquePtr(Ty),
946 RParen, Context.BoolTy));
947}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000948
949QualType Sema::CheckPointerToMemberOperands(
950 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
951{
952 const char *OpSpelling = isIndirect ? "->*" : ".*";
953 // C++ 5.5p2
954 // The binary operator .* [p3: ->*] binds its second operand, which shall
955 // be of type "pointer to member of T" (where T is a completely-defined
956 // class type) [...]
957 QualType RType = rex->getType();
958 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000959 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000960 Diag(Loc, diag::err_bad_memptr_rhs)
961 << OpSpelling << RType << rex->getSourceRange();
962 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000963 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0),
964 diag::err_memptr_rhs_incomplete,
965 rex->getSourceRange()))
966 return QualType();
967
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000968 QualType Class(MemPtr->getClass(), 0);
969
970 // C++ 5.5p2
971 // [...] to its first operand, which shall be of class T or of a class of
972 // which T is an unambiguous and accessible base class. [p3: a pointer to
973 // such a class]
974 QualType LType = lex->getType();
975 if (isIndirect) {
976 if (const PointerType *Ptr = LType->getAsPointerType())
977 LType = Ptr->getPointeeType().getNonReferenceType();
978 else {
979 Diag(Loc, diag::err_bad_memptr_lhs)
980 << OpSpelling << 1 << LType << lex->getSourceRange();
981 return QualType();
982 }
983 }
984
985 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
986 Context.getCanonicalType(LType).getUnqualifiedType()) {
987 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
988 /*DetectVirtual=*/false);
989 // FIXME: Would it be useful to print full ambiguity paths,
990 // or is that overkill?
991 if (!IsDerivedFrom(LType, Class, Paths) ||
992 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
993 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
994 << (int)isIndirect << lex->getType() << lex->getSourceRange();
995 return QualType();
996 }
997 }
998
999 // C++ 5.5p2
1000 // The result is an object or a function of the type specified by the
1001 // second operand.
1002 // The cv qualifiers are the union of those in the pointer and the left side,
1003 // in accordance with 5.5p5 and 5.2.5.
1004 // FIXME: This returns a dereferenced member function pointer as a normal
1005 // function type. However, the only operation valid on such functions is
1006 // calling them. There's also a GCC extension to get a function pointer to
1007 // the thing, which is another complication, because this type - unlike the
1008 // type that is the result of this expression - takes the class as the first
1009 // argument.
1010 // We probably need a "MemberFunctionClosureType" or something like that.
1011 QualType Result = MemPtr->getPointeeType();
1012 if (LType.isConstQualified())
1013 Result.addConst();
1014 if (LType.isVolatileQualified())
1015 Result.addVolatile();
1016 return Result;
1017}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001018
1019/// \brief Get the target type of a standard or user-defined conversion.
1020static QualType TargetType(const ImplicitConversionSequence &ICS) {
1021 assert((ICS.ConversionKind ==
1022 ImplicitConversionSequence::StandardConversion ||
1023 ICS.ConversionKind ==
1024 ImplicitConversionSequence::UserDefinedConversion) &&
1025 "function only valid for standard or user-defined conversions");
1026 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1027 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1028 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1029}
1030
1031/// \brief Try to convert a type to another according to C++0x 5.16p3.
1032///
1033/// This is part of the parameter validation for the ? operator. If either
1034/// value operand is a class type, the two operands are attempted to be
1035/// converted to each other. This function does the conversion in one direction.
1036/// It emits a diagnostic and returns true only if it finds an ambiguous
1037/// conversion.
1038static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1039 SourceLocation QuestionLoc,
1040 ImplicitConversionSequence &ICS)
1041{
1042 // C++0x 5.16p3
1043 // The process for determining whether an operand expression E1 of type T1
1044 // can be converted to match an operand expression E2 of type T2 is defined
1045 // as follows:
1046 // -- If E2 is an lvalue:
1047 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1048 // E1 can be converted to match E2 if E1 can be implicitly converted to
1049 // type "lvalue reference to T2", subject to the constraint that in the
1050 // conversion the reference must bind directly to E1.
1051 if (!Self.CheckReferenceInit(From,
1052 Self.Context.getLValueReferenceType(To->getType()),
1053 &ICS))
1054 {
1055 assert((ICS.ConversionKind ==
1056 ImplicitConversionSequence::StandardConversion ||
1057 ICS.ConversionKind ==
1058 ImplicitConversionSequence::UserDefinedConversion) &&
1059 "expected a definite conversion");
1060 bool DirectBinding =
1061 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1062 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1063 if (DirectBinding)
1064 return false;
1065 }
1066 }
1067 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1068 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1069 // -- if E1 and E2 have class type, and the underlying class types are
1070 // the same or one is a base class of the other:
1071 QualType FTy = From->getType();
1072 QualType TTy = To->getType();
1073 const RecordType *FRec = FTy->getAsRecordType();
1074 const RecordType *TRec = TTy->getAsRecordType();
1075 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1076 if (FRec && TRec && (FRec == TRec ||
1077 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1078 // E1 can be converted to match E2 if the class of T2 is the
1079 // same type as, or a base class of, the class of T1, and
1080 // [cv2 > cv1].
1081 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1082 // Could still fail if there's no copy constructor.
1083 // FIXME: Is this a hard error then, or just a conversion failure? The
1084 // standard doesn't say.
1085 ICS = Self.TryCopyInitialization(From, TTy);
1086 }
1087 } else {
1088 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1089 // implicitly converted to the type that expression E2 would have
1090 // if E2 were converted to an rvalue.
1091 // First find the decayed type.
1092 if (TTy->isFunctionType())
1093 TTy = Self.Context.getPointerType(TTy);
1094 else if(TTy->isArrayType())
1095 TTy = Self.Context.getArrayDecayedType(TTy);
1096
1097 // Now try the implicit conversion.
1098 // FIXME: This doesn't detect ambiguities.
1099 ICS = Self.TryImplicitConversion(From, TTy);
1100 }
1101 return false;
1102}
1103
1104/// \brief Try to find a common type for two according to C++0x 5.16p5.
1105///
1106/// This is part of the parameter validation for the ? operator. If either
1107/// value operand is a class type, overload resolution is used to find a
1108/// conversion to a common type.
1109static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1110 SourceLocation Loc) {
1111 Expr *Args[2] = { LHS, RHS };
1112 OverloadCandidateSet CandidateSet;
1113 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1114
1115 OverloadCandidateSet::iterator Best;
1116 switch (Self.BestViableFunction(CandidateSet, Best)) {
1117 case Sema::OR_Success:
1118 // We found a match. Perform the conversions on the arguments and move on.
1119 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1120 Best->Conversions[0], "converting") ||
1121 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1122 Best->Conversions[1], "converting"))
1123 break;
1124 return false;
1125
1126 case Sema::OR_No_Viable_Function:
1127 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1128 << LHS->getType() << RHS->getType()
1129 << LHS->getSourceRange() << RHS->getSourceRange();
1130 return true;
1131
1132 case Sema::OR_Ambiguous:
1133 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1134 << LHS->getType() << RHS->getType()
1135 << LHS->getSourceRange() << RHS->getSourceRange();
1136 // FIXME: Print the possible common types by printing the return types
1137 // of the viable candidates.
1138 break;
1139
1140 case Sema::OR_Deleted:
1141 assert(false && "Conditional operator has only built-in overloads");
1142 break;
1143 }
1144 return true;
1145}
1146
Sebastian Redl76458502009-04-17 16:30:52 +00001147/// \brief Perform an "extended" implicit conversion as returned by
1148/// TryClassUnification.
1149///
1150/// TryClassUnification generates ICSs that include reference bindings.
1151/// PerformImplicitConversion is not suitable for this; it chokes if the
1152/// second part of a standard conversion is ICK_DerivedToBase. This function
1153/// handles the reference binding specially.
1154static bool ConvertForConditional(Sema &Self, Expr *&E,
1155 const ImplicitConversionSequence &ICS)
1156{
1157 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1158 ICS.Standard.ReferenceBinding) {
1159 assert(ICS.Standard.DirectBinding &&
1160 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redl78eb8742009-04-19 21:53:20 +00001161 // FIXME: Should use CheckReferenceInit here, but we no longer have a
1162 // reference type.
Sebastian Redl76458502009-04-17 16:30:52 +00001163 Self.ImpCastExprToType(E, TargetType(ICS), true);
1164 return false;
1165 }
1166 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1167 ICS.UserDefined.After.ReferenceBinding) {
1168 assert(ICS.UserDefined.After.DirectBinding &&
1169 "TryClassUnification should never generate indirect ref bindings");
1170 Self.ImpCastExprToType(E, TargetType(ICS), true);
1171 return false;
1172 }
1173 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1174 return true;
1175 return false;
1176}
1177
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001178/// \brief Check the operands of ?: under C++ semantics.
1179///
1180/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1181/// extension. In this case, LHS == Cond. (But they're not aliases.)
1182QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1183 SourceLocation QuestionLoc) {
1184 // FIXME: Handle C99's complex types, vector types, block pointers and
1185 // Obj-C++ interface pointers.
1186
1187 // C++0x 5.16p1
1188 // The first expression is contextually converted to bool.
1189 if (!Cond->isTypeDependent()) {
1190 if (CheckCXXBooleanCondition(Cond))
1191 return QualType();
1192 }
1193
1194 // Either of the arguments dependent?
1195 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1196 return Context.DependentTy;
1197
1198 // C++0x 5.16p2
1199 // If either the second or the third operand has type (cv) void, ...
1200 QualType LTy = LHS->getType();
1201 QualType RTy = RHS->getType();
1202 bool LVoid = LTy->isVoidType();
1203 bool RVoid = RTy->isVoidType();
1204 if (LVoid || RVoid) {
1205 // ... then the [l2r] conversions are performed on the second and third
1206 // operands ...
1207 DefaultFunctionArrayConversion(LHS);
1208 DefaultFunctionArrayConversion(RHS);
1209 LTy = LHS->getType();
1210 RTy = RHS->getType();
1211
1212 // ... and one of the following shall hold:
1213 // -- The second or the third operand (but not both) is a throw-
1214 // expression; the result is of the type of the other and is an rvalue.
1215 bool LThrow = isa<CXXThrowExpr>(LHS);
1216 bool RThrow = isa<CXXThrowExpr>(RHS);
1217 if (LThrow && !RThrow)
1218 return RTy;
1219 if (RThrow && !LThrow)
1220 return LTy;
1221
1222 // -- Both the second and third operands have type void; the result is of
1223 // type void and is an rvalue.
1224 if (LVoid && RVoid)
1225 return Context.VoidTy;
1226
1227 // Neither holds, error.
1228 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1229 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1230 << LHS->getSourceRange() << RHS->getSourceRange();
1231 return QualType();
1232 }
1233
1234 // Neither is void.
1235
1236 // C++0x 5.16p3
1237 // Otherwise, if the second and third operand have different types, and
1238 // either has (cv) class type, and attempt is made to convert each of those
1239 // operands to the other.
1240 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1241 (LTy->isRecordType() || RTy->isRecordType())) {
1242 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1243 // These return true if a single direction is already ambiguous.
1244 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1245 return QualType();
1246 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1247 return QualType();
1248
1249 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1250 ImplicitConversionSequence::BadConversion;
1251 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1252 ImplicitConversionSequence::BadConversion;
1253 // If both can be converted, [...] the program is ill-formed.
1254 if (HaveL2R && HaveR2L) {
1255 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1256 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1257 return QualType();
1258 }
1259
1260 // If exactly one conversion is possible, that conversion is applied to
1261 // the chosen operand and the converted operands are used in place of the
1262 // original operands for the remainder of this section.
1263 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001264 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001265 return QualType();
1266 LTy = LHS->getType();
1267 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001268 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001269 return QualType();
1270 RTy = RHS->getType();
1271 }
1272 }
1273
1274 // C++0x 5.16p4
1275 // If the second and third operands are lvalues and have the same type,
1276 // the result is of that type [...]
1277 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1278 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1279 RHS->isLvalue(Context) == Expr::LV_Valid)
1280 return LTy;
1281
1282 // C++0x 5.16p5
1283 // Otherwise, the result is an rvalue. If the second and third operands
1284 // do not have the same type, and either has (cv) class type, ...
1285 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1286 // ... overload resolution is used to determine the conversions (if any)
1287 // to be applied to the operands. If the overload resolution fails, the
1288 // program is ill-formed.
1289 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1290 return QualType();
1291 }
1292
1293 // C++0x 5.16p6
1294 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1295 // conversions are performed on the second and third operands.
1296 DefaultFunctionArrayConversion(LHS);
1297 DefaultFunctionArrayConversion(RHS);
1298 LTy = LHS->getType();
1299 RTy = RHS->getType();
1300
1301 // After those conversions, one of the following shall hold:
1302 // -- The second and third operands have the same type; the result
1303 // is of that type.
1304 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1305 return LTy;
1306
1307 // -- The second and third operands have arithmetic or enumeration type;
1308 // the usual arithmetic conversions are performed to bring them to a
1309 // common type, and the result is of that type.
1310 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1311 UsualArithmeticConversions(LHS, RHS);
1312 return LHS->getType();
1313 }
1314
1315 // -- The second and third operands have pointer type, or one has pointer
1316 // type and the other is a null pointer constant; pointer conversions
1317 // and qualification conversions are performed to bring them to their
1318 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001319 QualType Composite = FindCompositePointerType(LHS, RHS);
1320 if (!Composite.isNull())
1321 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001322
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001323 // Fourth bullet is same for pointers-to-member. However, the possible
1324 // conversions are far more limited: we have null-to-pointer, upcast of
1325 // containing class, and second-level cv-ness.
1326 // cv-ness is not a union, but must match one of the two operands. (Which,
1327 // frankly, is stupid.)
1328 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1329 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1330 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1331 ImpCastExprToType(RHS, LTy);
1332 return LTy;
1333 }
1334 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1335 ImpCastExprToType(LHS, RTy);
1336 return RTy;
1337 }
1338 if (LMemPtr && RMemPtr) {
1339 QualType LPointee = LMemPtr->getPointeeType();
1340 QualType RPointee = RMemPtr->getPointeeType();
1341 // First, we check that the unqualified pointee type is the same. If it's
1342 // not, there's no conversion that will unify the two pointers.
1343 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1344 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1345 // Second, we take the greater of the two cv qualifications. If neither
1346 // is greater than the other, the conversion is not possible.
1347 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1348 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1349 // Third, we check if either of the container classes is derived from
1350 // the other.
1351 QualType LContainer(LMemPtr->getClass(), 0);
1352 QualType RContainer(RMemPtr->getClass(), 0);
1353 QualType MoreDerived;
1354 if (Context.getCanonicalType(LContainer) ==
1355 Context.getCanonicalType(RContainer))
1356 MoreDerived = LContainer;
1357 else if (IsDerivedFrom(LContainer, RContainer))
1358 MoreDerived = LContainer;
1359 else if (IsDerivedFrom(RContainer, LContainer))
1360 MoreDerived = RContainer;
1361
1362 if (!MoreDerived.isNull()) {
1363 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1364 // We don't use ImpCastExprToType here because this could still fail
1365 // for ambiguous or inaccessible conversions.
1366 QualType Common = Context.getMemberPointerType(
1367 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1368 if (PerformImplicitConversion(LHS, Common, "converting"))
1369 return QualType();
1370 if (PerformImplicitConversion(RHS, Common, "converting"))
1371 return QualType();
1372 return Common;
1373 }
1374 }
1375 }
1376 }
1377
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001378 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1379 << LHS->getType() << RHS->getType()
1380 << LHS->getSourceRange() << RHS->getSourceRange();
1381 return QualType();
1382}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001383
1384/// \brief Find a merged pointer type and convert the two expressions to it.
1385///
1386/// This finds the composite pointer type for @p E1 and @p E2 according to
1387/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1388/// It does not emit diagnostics.
1389QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1390 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1391 QualType T1 = E1->getType(), T2 = E2->getType();
1392 if(!T1->isPointerType() && !T2->isPointerType())
1393 return QualType();
1394
1395 // C++0x 5.9p2
1396 // Pointer conversions and qualification conversions are performed on
1397 // pointer operands to bring them to their composite pointer type. If
1398 // one operand is a null pointer constant, the composite pointer type is
1399 // the type of the other operand.
1400 if (E1->isNullPointerConstant(Context)) {
1401 ImpCastExprToType(E1, T2);
1402 return T2;
1403 }
1404 if (E2->isNullPointerConstant(Context)) {
1405 ImpCastExprToType(E2, T1);
1406 return T1;
1407 }
1408 // Now both have to be pointers.
1409 if(!T1->isPointerType() || !T2->isPointerType())
1410 return QualType();
1411
1412 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1413 // the other has type "pointer to cv2 T" and the composite pointer type is
1414 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1415 // Otherwise, the composite pointer type is a pointer type similar to the
1416 // type of one of the operands, with a cv-qualification signature that is
1417 // the union of the cv-qualification signatures of the operand types.
1418 // In practice, the first part here is redundant; it's subsumed by the second.
1419 // What we do here is, we build the two possible composite types, and try the
1420 // conversions in both directions. If only one works, or if the two composite
1421 // types are the same, we have succeeded.
1422 llvm::SmallVector<unsigned, 4> QualifierUnion;
1423 QualType Composite1 = T1, Composite2 = T2;
1424 const PointerType *Ptr1, *Ptr2;
1425 while ((Ptr1 = Composite1->getAsPointerType()) &&
1426 (Ptr2 = Composite2->getAsPointerType())) {
1427 Composite1 = Ptr1->getPointeeType();
1428 Composite2 = Ptr2->getPointeeType();
1429 QualifierUnion.push_back(
1430 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1431 }
1432 // Rewrap the composites as pointers with the union CVRs.
1433 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1434 E = QualifierUnion.end(); I != E; ++I) {
1435 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1436 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1437 }
1438
1439 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1440 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1441 ImplicitConversionSequence E1ToC2, E2ToC2;
1442 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1443 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1444 if (Context.getCanonicalType(Composite1) !=
1445 Context.getCanonicalType(Composite2)) {
1446 E1ToC2 = TryImplicitConversion(E1, Composite2);
1447 E2ToC2 = TryImplicitConversion(E2, Composite2);
1448 }
1449
1450 bool ToC1Viable = E1ToC1.ConversionKind !=
1451 ImplicitConversionSequence::BadConversion
1452 && E2ToC1.ConversionKind !=
1453 ImplicitConversionSequence::BadConversion;
1454 bool ToC2Viable = E1ToC2.ConversionKind !=
1455 ImplicitConversionSequence::BadConversion
1456 && E2ToC2.ConversionKind !=
1457 ImplicitConversionSequence::BadConversion;
1458 if (ToC1Viable && !ToC2Viable) {
1459 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1460 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1461 return Composite1;
1462 }
1463 if (ToC2Viable && !ToC1Viable) {
1464 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1465 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1466 return Composite2;
1467 }
1468 return QualType();
1469}