blob: 9155ec45d7669c160ad1711f65630da54bc1c66d [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 ).
59Action::ExprResult
60Sema::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)
64 return Diag(OpLoc, diag::err_need_header_before_typeid);
65
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)
70 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Ted Kremenek8189cde2009-02-07 01:47:29 +000074 return new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000079Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Ted Kremenek8189cde2009-02-07 01:47:29 +000083 return new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
86/// ActOnCXXThrow - Parse throw expressions.
87Action::ExprResult
88Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
Ted Kremenek8189cde2009-02-07 01:47:29 +000089 return new (Context) CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
Chris Lattner50dd2892008-02-26 00:51:44 +000090}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000091
92Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
93 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
94 /// is a non-lvalue expression whose value is the address of the object for
95 /// which the function is called.
96
97 if (!isa<FunctionDecl>(CurContext)) {
98 Diag(ThisLoc, diag::err_invalid_this_use);
99 return ExprResult(true);
100 }
101
102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
103 if (MD->isInstance())
Ted Kremenek8189cde2009-02-07 01:47:29 +0000104 return new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000105
106 return Diag(ThisLoc, diag::err_invalid_this_use);
107}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000108
109/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
110/// Can be interpreted either as function-style casting ("int(x)")
111/// or class type construction ("ClassType(x,y,z)")
112/// or creation of a value-initialized type ("int()").
113Action::ExprResult
114Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
115 SourceLocation LParenLoc,
116 ExprTy **ExprTys, unsigned NumExprs,
117 SourceLocation *CommaLocs,
118 SourceLocation RParenLoc) {
119 assert(TypeRep && "Missing type!");
120 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
121 Expr **Exprs = (Expr**)ExprTys;
122 SourceLocation TyBeginLoc = TypeRange.getBegin();
123 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
124
Douglas Gregor506ae412009-01-16 18:33:17 +0000125 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000126 // If the expression list is a single expression, the type conversion
127 // expression is equivalent (in definedness, and if defined in meaning) to the
128 // corresponding cast expression.
129 //
130 if (NumExprs == 1) {
131 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
132 return true;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000133 return new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty,
134 TyBeginLoc, Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000135 }
136
Douglas Gregor506ae412009-01-16 18:33:17 +0000137 if (const RecordType *RT = Ty->getAsRecordType()) {
138 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
139
140 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
141 CXXConstructorDecl *Constructor
142 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
143 TypeRange.getBegin(),
144 SourceRange(TypeRange.getBegin(),
145 RParenLoc),
146 DeclarationName(),
147 IK_Direct);
148
149 if (!Constructor)
150 return true;
151
Ted Kremenek8189cde2009-02-07 01:47:29 +0000152 return new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor506ae412009-01-16 18:33:17 +0000153 Exprs, NumExprs, RParenLoc);
154 }
155
156 // Fall through to value-initialize an object of class type that
157 // doesn't have a user-declared default constructor.
158 }
159
160 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000161 // If the expression list specifies more than a single value, the type shall
162 // be a class with a suitably declared constructor.
163 //
164 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000165 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
166 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000167
168 assert(NumExprs == 0 && "Expected 0 expressions");
169
Douglas Gregor506ae412009-01-16 18:33:17 +0000170 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000171 // The expression T(), where T is a simple-type-specifier for a non-array
172 // complete object type or the (possibly cv-qualified) void type, creates an
173 // rvalue of the specified type, which is value-initialized.
174 //
175 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000176 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000177 if (!Ty->isDependentType() && !Ty->isVoidType() &&
178 DiagnoseIncompleteType(TyBeginLoc, Ty,
179 diag::err_invalid_incomplete_type_use, FullRange))
180 return true;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000181
Ted Kremenek8189cde2009-02-07 01:47:29 +0000182 return new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000183}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000184
185
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000186/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
187/// @code new (memory) int[size][4] @endcode
188/// or
189/// @code ::new Foo(23, "hello") @endcode
190/// For the interpretation of this heap of arguments, consult the base version.
191Action::ExprResult
192Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
193 SourceLocation PlacementLParen,
194 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
195 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000196 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000197 ExprTy **ConstructorArgs, unsigned NumConsArgs,
198 SourceLocation ConstructorRParen)
199{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000200 // FIXME: Throughout this function, we have rather bad location information.
201 // Implementing Declarator::getSourceRange() would go a long way toward
202 // fixing that.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000203
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000204 Expr *ArraySize = 0;
205 unsigned Skip = 0;
206 // If the specified type is an array, unwrap it and save the expression.
207 if (D.getNumTypeObjects() > 0 &&
208 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
209 DeclaratorChunk &Chunk = D.getTypeObject(0);
210 if (Chunk.Arr.hasStatic)
211 return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
212 if (!Chunk.Arr.NumElts)
213 return Diag(Chunk.Loc, diag::err_array_new_needs_size);
214 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
215 Skip = 1;
216 }
217
218 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
219 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000220 return true;
221
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000222 if (CheckAllocatedType(AllocType, D))
223 return true;
224
225 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000226
227 // That every array dimension except the first is constant was already
228 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000229
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000230 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
231 // or enumeration type with a non-negative value."
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000232 if (ArraySize) {
233 QualType SizeType = ArraySize->getType();
234 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
235 return Diag(ArraySize->getSourceRange().getBegin(),
236 diag::err_array_size_not_integral)
237 << SizeType << ArraySize->getSourceRange();
238 // Let's see if this is a constant < 0. If so, we reject it out of hand.
239 // We don't care about special rules, so we tell the machinery it's not
240 // evaluated - it gives us a result in more cases.
241 llvm::APSInt Value;
242 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
243 if (Value < llvm::APSInt(
244 llvm::APInt::getNullValue(Value.getBitWidth()), false))
245 return Diag(ArraySize->getSourceRange().getBegin(),
246 diag::err_typecheck_negative_array_size)
247 << ArraySize->getSourceRange();
248 }
249 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000250
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000251 FunctionDecl *OperatorNew = 0;
252 FunctionDecl *OperatorDelete = 0;
253 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000254 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
255 PlaceArgs, NumPlaceArgs, OperatorNew,
256 OperatorDelete))
257 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000258
259 bool Init = ConstructorLParen.isValid();
260 // --- Choosing a constructor ---
261 // C++ 5.3.4p15
262 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
263 // the object is not initialized. If the object, or any part of it, is
264 // const-qualified, it's an error.
265 // 2) If T is a POD and there's an empty initializer, the object is value-
266 // initialized.
267 // 3) If T is a POD and there's one initializer argument, the object is copy-
268 // constructed.
269 // 4) If T is a POD and there's more initializer arguments, it's an error.
270 // 5) If T is not a POD, the initializer arguments are used as constructor
271 // arguments.
272 //
273 // Or by the C++0x formulation:
274 // 1) If there's no initializer, the object is default-initialized according
275 // to C++0x rules.
276 // 2) Otherwise, the object is direct-initialized.
277 CXXConstructorDecl *Constructor = 0;
278 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000280 // FIXME: This is incorrect for when there is an empty initializer and
281 // no user-defined constructor. Must zero-initialize, not default-construct.
282 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000283 AllocType, ConsArgs, NumConsArgs,
284 D.getDeclSpec().getSourceRange().getBegin(),
285 SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
286 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000287 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000288 NumConsArgs != 0 ? IK_Direct : IK_Default);
289 if (!Constructor)
290 return true;
291 } else {
292 if (!Init) {
293 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000294 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000295 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000296 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000297 return true;
298 }
299 } else if (NumConsArgs == 0) {
300 // Object is value-initialized. Do nothing.
301 } else if (NumConsArgs == 1) {
302 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000303 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000305 DeclarationName() /*AllocType.getAsString()*/,
306 /*DirectInit=*/true))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000307 return true;
308 } else {
309 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
310 << SourceRange(ConstructorLParen, ConstructorRParen);
311 }
312 }
313
314 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
315
Ted Kremenek8189cde2009-02-07 01:47:29 +0000316 return new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
317 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000318 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000319 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000320}
321
322/// CheckAllocatedType - Checks that a type is suitable as the allocated type
323/// in a new-expression.
324/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000326{
327 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
328 // abstract class type or array thereof.
329 // FIXME: We don't have abstract types yet.
330 // FIXME: Under C++ semantics, an incomplete object type is still an object
331 // type. This code assumes the C semantics, where it's not.
332 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000333 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000334 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000335 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000336 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000337 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000338 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000339 assert(AllocType->isReferenceType() && "What else could it be?");
340 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000341 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 SourceRange TyR = D.getDeclSpec().getSourceRange();
343 // FIXME: This is very much a guess and won't work for, e.g., pointers.
344 if (D.getNumTypeObjects() > 0)
345 TyR.setEnd(D.getTypeObject(0).Loc);
346 Diag(TyR.getBegin(), diag::err_bad_new_type)
347 << AllocType.getAsString() << type << TyR;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000348 return true;
349 }
350
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000351 // Every dimension shall be of constant size.
352 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000353 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
354 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000355 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
356 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000357 return true;
358 }
359 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000360 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361 }
362
363 return false;
364}
365
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000366/// FindAllocationFunctions - Finds the overloads of operator new and delete
367/// that are appropriate for the allocation.
368bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
369 QualType AllocType, bool IsArray,
370 Expr **PlaceArgs, unsigned NumPlaceArgs,
371 FunctionDecl *&OperatorNew,
372 FunctionDecl *&OperatorDelete)
373{
374 // --- Choosing an allocation function ---
375 // C++ 5.3.4p8 - 14 & 18
376 // 1) If UseGlobal is true, only look in the global scope. Else, also look
377 // in the scope of the allocated class.
378 // 2) If an array size is given, look for operator new[], else look for
379 // operator new.
380 // 3) The first argument is always size_t. Append the arguments from the
381 // placement form.
382 // FIXME: Also find the appropriate delete operator.
383
384 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
385 // We don't care about the actual value of this argument.
386 // FIXME: Should the Sema create the expression and embed it in the syntax
387 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000388 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000389 Context.Target.getPointerWidth(0)),
390 Context.getSizeType(),
391 SourceLocation());
392 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
393
394 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
395 IsArray ? OO_Array_New : OO_New);
396 if (AllocType->isRecordType() && !UseGlobal) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000397 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
398 ->getDecl();
399 // FIXME: We fail to find inherited overloads.
400 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
401 AllocArgs.size(), Record, /*AllowMissing=*/true,
402 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000403 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000404 }
405 if (!OperatorNew) {
406 // Didn't find a member overload. Look for a global one.
407 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000408 DeclContext *TUDecl = Context.getTranslationUnitDecl();
409 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
410 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
411 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000412 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000413 }
414
Sebastian Redl7f662392008-12-04 22:20:51 +0000415 // FIXME: This is leaked on error. But so much is currently in Sema that it's
416 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000417 AllocArgs[0]->Destroy(Context);
418 return false;
419}
420
Sebastian Redl7f662392008-12-04 22:20:51 +0000421/// FindAllocationOverload - Find an fitting overload for the allocation
422/// function in the specified scope.
423bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
424 Expr** Args, unsigned NumArgs,
425 DeclContext *Ctx, bool AllowMissing,
426 FunctionDecl *&Operator)
427{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000428 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000429 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000430 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000431 if (AllowMissing)
432 return false;
433 // FIXME: Bad location information.
434 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
435 << Name << 0;
436 }
437
438 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000439 for (; Alloc != AllocEnd; ++Alloc) {
440 // Even member operator new/delete are implicitly treated as
441 // static, so don't use AddMemberCandidate.
442 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
443 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
444 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000445 }
446
447 // Do the resolution.
448 OverloadCandidateSet::iterator Best;
449 switch(BestViableFunction(Candidates, Best)) {
450 case OR_Success: {
451 // Got one!
452 FunctionDecl *FnDecl = Best->Function;
453 // The first argument is size_t, and the first parameter must be size_t,
454 // too. This is checked on declaration and can be assumed. (It can't be
455 // asserted on, though, since invalid decls are left in there.)
456 for (unsigned i = 1; i < NumArgs; ++i) {
457 // FIXME: Passing word to diagnostic.
458 if (PerformCopyInitialization(Args[i-1],
459 FnDecl->getParamDecl(i)->getType(),
460 "passing"))
461 return true;
462 }
463 Operator = FnDecl;
464 return false;
465 }
466
467 case OR_No_Viable_Function:
468 if (AllowMissing)
469 return false;
470 // FIXME: Bad location information.
471 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
472 << Name << (unsigned)Candidates.size();
473 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
474 return true;
475
476 case OR_Ambiguous:
477 // FIXME: Bad location information.
478 Diag(StartLoc, diag::err_ovl_ambiguous_call)
479 << Name;
480 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
481 return true;
482 }
483 assert(false && "Unreachable, bad result from BestViableFunction");
484 return true;
485}
486
487
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000488/// DeclareGlobalNewDelete - Declare the global forms of operator new and
489/// delete. These are:
490/// @code
491/// void* operator new(std::size_t) throw(std::bad_alloc);
492/// void* operator new[](std::size_t) throw(std::bad_alloc);
493/// void operator delete(void *) throw();
494/// void operator delete[](void *) throw();
495/// @endcode
496/// Note that the placement and nothrow forms of new are *not* implicitly
497/// declared. Their use requires including \<new\>.
498void Sema::DeclareGlobalNewDelete()
499{
500 if (GlobalNewDeleteDeclared)
501 return;
502 GlobalNewDeleteDeclared = true;
503
504 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
505 QualType SizeT = Context.getSizeType();
506
507 // FIXME: Exception specifications are not added.
508 DeclareGlobalAllocationFunction(
509 Context.DeclarationNames.getCXXOperatorName(OO_New),
510 VoidPtr, SizeT);
511 DeclareGlobalAllocationFunction(
512 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
513 VoidPtr, SizeT);
514 DeclareGlobalAllocationFunction(
515 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
516 Context.VoidTy, VoidPtr);
517 DeclareGlobalAllocationFunction(
518 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
519 Context.VoidTy, VoidPtr);
520}
521
522/// DeclareGlobalAllocationFunction - Declares a single implicit global
523/// allocation function if it doesn't already exist.
524void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
525 QualType Return, QualType Argument)
526{
527 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
528
529 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000530 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000531 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000532 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000533 Alloc != AllocEnd; ++Alloc) {
534 // FIXME: Do we need to check for default arguments here?
535 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
536 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000537 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000538 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000539 }
540 }
541
542 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
543 FunctionDecl *Alloc =
544 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000545 FnType, FunctionDecl::None, false,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000546 SourceLocation());
547 Alloc->setImplicit();
548 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000549 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000550 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000551
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000552 // FIXME: Also add this declaration to the IdentifierResolver, but
553 // make sure it is at the end of the chain to coincide with the
554 // global scope.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000555 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000556}
557
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000558/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
559/// @code ::delete ptr; @endcode
560/// or
561/// @code delete [] ptr; @endcode
562Action::ExprResult
563Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
564 bool ArrayForm, ExprTy *Operand)
565{
566 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
567 // having a single conversion function to a pointer type. The result has
568 // type void."
569 // DR599 amends "pointer type" to "pointer to object type" in both cases.
570
571 Expr *Ex = (Expr *)Operand;
572 QualType Type = Ex->getType();
573
574 if (Type->isRecordType()) {
575 // FIXME: Find that one conversion function and amend the type.
576 }
577
578 if (!Type->isPointerType()) {
Chris Lattnerd1625842008-11-24 06:25:27 +0000579 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000580 return true;
581 }
582
583 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000584 if (!Pointee->isVoidType() &&
585 DiagnoseIncompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
586 Ex->getSourceRange()))
587 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000588 else if (!Pointee->isObjectType()) {
589 Diag(StartLoc, diag::err_delete_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +0000590 << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000591 return true;
592 }
593
594 // FIXME: Look up the correct operator delete overload and pass a pointer
595 // along.
596 // FIXME: Check access and ambiguity of operator delete and destructor.
597
Ted Kremenek8189cde2009-02-07 01:47:29 +0000598 return new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0,
599 Ex, StartLoc);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000600}
601
602
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000603/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
604/// C++ if/switch/while/for statement.
605/// e.g: "if (int x = f()) {...}"
606Action::ExprResult
607Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
608 Declarator &D,
609 SourceLocation EqualLoc,
610 ExprTy *AssignExprVal) {
611 assert(AssignExprVal && "Null assignment expression");
612
613 // C++ 6.4p2:
614 // The declarator shall not specify a function or an array.
615 // The type-specifier-seq shall not contain typedef and shall not declare a
616 // new class or enumeration.
617
618 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
619 "Parser allowed 'typedef' as storage class of condition decl.");
620
621 QualType Ty = GetTypeForDeclarator(D, S);
622
623 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
624 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
625 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000626 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
627 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000628 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000629 Diag(StartLoc, diag::err_invalid_use_of_array_type)
630 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000631 } else if (const RecordType *RT = Ty->getAsRecordType()) {
632 RecordDecl *RD = RT->getDecl();
633 // The type-specifier-seq shall not declare a new class...
634 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
635 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
636 } else if (const EnumType *ET = Ty->getAsEnumType()) {
637 EnumDecl *ED = ET->getDecl();
638 // ...or enumeration.
639 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
640 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
641 }
642
643 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
644 if (!Dcl)
645 return true;
Sebastian Redl798d1192008-12-13 16:23:55 +0000646 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000647
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000648 // Mark this variable as one that is declared within a conditional.
649 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
650 VD->setDeclaredInCondition(true);
651
Ted Kremenek8189cde2009-02-07 01:47:29 +0000652 return new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000653 cast<VarDecl>(static_cast<Decl *>(Dcl)));
654}
655
656/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
657bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
658 // C++ 6.4p4:
659 // The value of a condition that is an initialized declaration in a statement
660 // other than a switch statement is the value of the declared variable
661 // implicitly converted to type bool. If that conversion is ill-formed, the
662 // program is ill-formed.
663 // The value of a condition that is an expression is the value of the
664 // expression, implicitly converted to bool.
665 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000666 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000667}
Douglas Gregor77a52232008-09-12 00:47:35 +0000668
669/// Helper function to determine whether this is the (deprecated) C++
670/// conversion from a string literal to a pointer to non-const char or
671/// non-const wchar_t (for narrow and wide string literals,
672/// respectively).
673bool
674Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
675 // Look inside the implicit cast, if it exists.
676 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
677 From = Cast->getSubExpr();
678
679 // A string literal (2.13.4) that is not a wide string literal can
680 // be converted to an rvalue of type "pointer to char"; a wide
681 // string literal can be converted to an rvalue of type "pointer
682 // to wchar_t" (C++ 4.2p2).
683 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
684 if (const PointerType *ToPtrType = ToType->getAsPointerType())
685 if (const BuiltinType *ToPointeeType
686 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
687 // This conversion is considered only when there is an
688 // explicit appropriate pointer target type (C++ 4.2p2).
689 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
690 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
691 (!StrLit->isWide() &&
692 (ToPointeeType->getKind() == BuiltinType::Char_U ||
693 ToPointeeType->getKind() == BuiltinType::Char_S))))
694 return true;
695 }
696
697 return false;
698}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000699
700/// PerformImplicitConversion - Perform an implicit conversion of the
701/// expression From to the type ToType. Returns true if there was an
702/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000703/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000704/// performing, used in the error message. If @p AllowExplicit,
705/// explicit user-defined conversions are permitted.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000706bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000707Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000708 const char *Flavor, bool AllowExplicit)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000709{
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000710 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
711 AllowExplicit);
712 return PerformImplicitConversion(From, ToType, ICS, Flavor);
713}
714
715/// PerformImplicitConversion - Perform an implicit conversion of the
716/// expression From to the type ToType using the pre-computed implicit
717/// conversion sequence ICS. Returns true if there was an error, false
718/// otherwise. The expression From is replaced with the converted
719/// expression. Flavor is the kind of conversion we're performing,
720/// used in the error message.
721bool
722Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
723 const ImplicitConversionSequence &ICS,
724 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000725 switch (ICS.ConversionKind) {
726 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000727 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000728 return true;
729 break;
730
731 case ImplicitConversionSequence::UserDefinedConversion:
732 // FIXME: This is, of course, wrong. We'll need to actually call
733 // the constructor or conversion operator, and then cope with the
734 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000735 ImpCastExprToType(From, ToType.getNonReferenceType(),
736 ToType->isReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000737 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000738
739 case ImplicitConversionSequence::EllipsisConversion:
740 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000741 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000742
743 case ImplicitConversionSequence::BadConversion:
744 return true;
745 }
746
747 // Everything went well.
748 return false;
749}
750
751/// PerformImplicitConversion - Perform an implicit conversion of the
752/// expression From to the type ToType by following the standard
753/// conversion sequence SCS. Returns true if there was an error, false
754/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000755/// expression. Flavor is the context in which we're performing this
756/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000757bool
758Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000759 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000760 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000761 // Overall FIXME: we are recomputing too many types here and doing
762 // far too much extra work. What this means is that we need to keep
763 // track of more information that is computed when we try the
764 // implicit conversion initially, so that we don't need to recompute
765 // anything here.
766 QualType FromType = From->getType();
767
Douglas Gregor225c41e2008-11-03 19:09:14 +0000768 if (SCS.CopyConstructor) {
769 // FIXME: Create a temporary object by calling the copy
770 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000771 ImpCastExprToType(From, ToType.getNonReferenceType(),
772 ToType->isReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000773 return false;
774 }
775
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000776 // Perform the first implicit conversion.
777 switch (SCS.First) {
778 case ICK_Identity:
779 case ICK_Lvalue_To_Rvalue:
780 // Nothing to do.
781 break;
782
783 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000784 if (FromType->isOverloadType()) {
785 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
786 if (!Fn)
787 return true;
788
789 FixOverloadedFunctionReference(From, Fn);
790 FromType = From->getType();
791 } else {
792 FromType = Context.getArrayDecayedType(FromType);
793 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000794 ImpCastExprToType(From, FromType);
795 break;
796
797 case ICK_Function_To_Pointer:
798 FromType = Context.getPointerType(FromType);
799 ImpCastExprToType(From, FromType);
800 break;
801
802 default:
803 assert(false && "Improper first standard conversion");
804 break;
805 }
806
807 // Perform the second implicit conversion
808 switch (SCS.Second) {
809 case ICK_Identity:
810 // Nothing to do.
811 break;
812
813 case ICK_Integral_Promotion:
814 case ICK_Floating_Promotion:
815 case ICK_Integral_Conversion:
816 case ICK_Floating_Conversion:
817 case ICK_Floating_Integral:
818 FromType = ToType.getUnqualifiedType();
819 ImpCastExprToType(From, FromType);
820 break;
821
822 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000823 if (SCS.IncompatibleObjC) {
824 // Diagnose incompatible Objective-C conversions
825 Diag(From->getSourceRange().getBegin(),
826 diag::ext_typecheck_convert_incompatible_pointer)
827 << From->getType() << ToType << Flavor
828 << From->getSourceRange();
829 }
830
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000831 if (CheckPointerConversion(From, ToType))
832 return true;
833 ImpCastExprToType(From, ToType);
834 break;
835
836 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000837 if (CheckMemberPointerConversion(From, ToType))
838 return true;
839 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000840 break;
841
842 case ICK_Boolean_Conversion:
843 FromType = Context.BoolTy;
844 ImpCastExprToType(From, FromType);
845 break;
846
847 default:
848 assert(false && "Improper second standard conversion");
849 break;
850 }
851
852 switch (SCS.Third) {
853 case ICK_Identity:
854 // Nothing to do.
855 break;
856
857 case ICK_Qualification:
Douglas Gregor66b947f2009-01-16 19:38:23 +0000858 ImpCastExprToType(From, ToType.getNonReferenceType(),
859 ToType->isReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000860 break;
861
862 default:
863 assert(false && "Improper second standard conversion");
864 break;
865 }
866
867 return false;
868}
869
Sebastian Redl64b45f72009-01-05 20:52:13 +0000870Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
871 SourceLocation KWLoc,
872 SourceLocation LParen,
873 TypeTy *Ty,
874 SourceLocation RParen) {
875 // FIXME: Some of the type traits have requirements. Interestingly, only the
876 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
877 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
878 // type is indeed a POD.
879
880 // There is no point in eagerly computing the value. The traits are designed
881 // to be used from type trait templates, so Ty will be a template parameter
882 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000883 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000884 QualType::getFromOpaquePtr(Ty),
885 RParen, Context.BoolTy));
886}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000887
888QualType Sema::CheckPointerToMemberOperands(
889 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
890{
891 const char *OpSpelling = isIndirect ? "->*" : ".*";
892 // C++ 5.5p2
893 // The binary operator .* [p3: ->*] binds its second operand, which shall
894 // be of type "pointer to member of T" (where T is a completely-defined
895 // class type) [...]
896 QualType RType = rex->getType();
897 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
898 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
899 Diag(Loc, diag::err_bad_memptr_rhs)
900 << OpSpelling << RType << rex->getSourceRange();
901 return QualType();
902 }
903 QualType Class(MemPtr->getClass(), 0);
904
905 // C++ 5.5p2
906 // [...] to its first operand, which shall be of class T or of a class of
907 // which T is an unambiguous and accessible base class. [p3: a pointer to
908 // such a class]
909 QualType LType = lex->getType();
910 if (isIndirect) {
911 if (const PointerType *Ptr = LType->getAsPointerType())
912 LType = Ptr->getPointeeType().getNonReferenceType();
913 else {
914 Diag(Loc, diag::err_bad_memptr_lhs)
915 << OpSpelling << 1 << LType << lex->getSourceRange();
916 return QualType();
917 }
918 }
919
920 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
921 Context.getCanonicalType(LType).getUnqualifiedType()) {
922 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
923 /*DetectVirtual=*/false);
924 // FIXME: Would it be useful to print full ambiguity paths,
925 // or is that overkill?
926 if (!IsDerivedFrom(LType, Class, Paths) ||
927 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
928 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
929 << (int)isIndirect << lex->getType() << lex->getSourceRange();
930 return QualType();
931 }
932 }
933
934 // C++ 5.5p2
935 // The result is an object or a function of the type specified by the
936 // second operand.
937 // The cv qualifiers are the union of those in the pointer and the left side,
938 // in accordance with 5.5p5 and 5.2.5.
939 // FIXME: This returns a dereferenced member function pointer as a normal
940 // function type. However, the only operation valid on such functions is
941 // calling them. There's also a GCC extension to get a function pointer to
942 // the thing, which is another complication, because this type - unlike the
943 // type that is the result of this expression - takes the class as the first
944 // argument.
945 // We probably need a "MemberFunctionClosureType" or something like that.
946 QualType Result = MemPtr->getPointeeType();
947 if (LType.isConstQualified())
948 Result.addConst();
949 if (LType.isVolatileQualified())
950 Result.addVolatile();
951 return Result;
952}