blob: 0d1614abe96d2c47591040f3695c00932441eda1 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenekd6b87082010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000032using namespace clang;
33
David Chisnall9f57c292009-08-17 16:35:33 +000034
Douglas Gregor171c45a2009-02-18 21:56:37 +000035/// \brief Determine whether the use of this declaration is valid, and
36/// emit any corresponding diagnostics.
37///
38/// This routine diagnoses various problems with referencing
39/// declarations that can occur when using a declaration. For example,
40/// it might warn if a deprecated or unavailable declaration is being
41/// used, or produce an error (and return true) if a C++0x deleted
42/// function is being used.
43///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor171c45a2009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000049///
John McCall28a6aea2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000054 }
55
Chris Lattnera27dd592009-10-25 17:21:40 +000056 // See if the decl is unavailable
57 if (D->getAttr<UnavailableAttr>()) {
58 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
59 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
60 }
61
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000064 if (FD->isDeleted()) {
65 Diag(Loc, diag::err_deleted_function_use);
66 Diag(D->getLocation(), diag::note_unavailable_here) << true;
67 return true;
68 }
Douglas Gregorde681d42009-02-24 04:26:15 +000069 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000070
Douglas Gregor171c45a2009-02-18 21:56:37 +000071 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000076/// attribute. It warns if call does not have the sentinel argument.
77///
78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000085
Mike Stump87c57ac2009-05-16 07:39:55 +000086 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
87 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000089 bool warnNotEnoughArgs = false;
90 int isMethod = 0;
91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
92 // skip over named parameters.
93 ObjCMethodDecl::param_iterator P, E = MD->param_end();
94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
95 if (nullPos)
96 --nullPos;
97 else
98 ++i;
99 }
100 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000103 // skip over named parameters.
104 ObjCMethodDecl::param_iterator P, E = FD->param_end();
105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
106 if (nullPos)
107 --nullPos;
108 else
109 ++i;
110 }
111 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
120 unsigned NumArgsInProto = Proto->getNumArgs();
121 unsigned k;
122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
123 if (nullPos)
124 --nullPos;
125 else
126 ++i;
127 }
128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 }
130 if (Ty->isBlockPointerType())
131 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000133 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000140 return;
141 }
142 int sentinel = i;
143 while (sentinelPos > 0 && i < NumArgs-1) {
144 --sentinelPos;
145 ++i;
146 }
147 if (sentinelPos > 0) {
148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000165}
166
Douglas Gregor87f95b02009-02-26 21:00:50 +0000167SourceRange Sema::getExprRange(ExprTy *E) const {
168 Expr *Ex = (Expr *)E;
169 return Ex? Ex->getSourceRange() : SourceRange();
170}
171
Chris Lattner513165e2008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattner513165e2008-07-25 21:10:04 +0000176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
177void Sema::DefaultFunctionArrayConversion(Expr *&E) {
178 QualType Ty = E->getType();
179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180
Chris Lattner513165e2008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000184 else if (Ty->isArrayType()) {
185 // In C90 mode, arrays only promote to pointers if the array expression is
186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
187 // type 'array of type' is converted to an expression that has type 'pointer
188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
189 // that has type 'array of type' ...". The relevant change is "an lvalue"
190 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000191 //
192 // C++ 4.2p1:
193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
194 // T" can be converted to an rvalue of type "pointer to T".
195 //
196 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
197 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000200 }
Chris Lattner513165e2008-07-25 21:10:04 +0000201}
202
Douglas Gregorb92a1562010-02-03 00:27:59 +0000203void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
204 DefaultFunctionArrayConversion(E);
205
206 QualType Ty = E->getType();
207 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
208 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
209 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
210 E->isLvalue(Context) == Expr::LV_Valid) {
211 // C++ [conv.lval]p1:
212 // [...] If T is a non-class type, the type of the rvalue is the
213 // cv-unqualified version of T. Otherwise, the type of the
214 // rvalue is T
215 //
216 // C99 6.3.2.1p2:
217 // If the lvalue has qualified type, the value has the unqualified
218 // version of the type of the lvalue; otherwise, the value has the
219 // type of the lvalue.
220 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
221 }
222}
223
224
Chris Lattner513165e2008-07-25 21:10:04 +0000225/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000226/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000227/// sometimes surpressed. For example, the array->pointer conversion doesn't
228/// apply if the array is an argument to the sizeof or address (&) operators.
229/// In these instances, this routine should *not* be called.
230Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
231 QualType Ty = Expr->getType();
232 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 // C99 6.3.1.1p2:
235 //
236 // The following may be used in an expression wherever an int or
237 // unsigned int may be used:
238 // - an object or expression with an integer type whose integer
239 // conversion rank is less than or equal to the rank of int
240 // and unsigned int.
241 // - A bit-field of type _Bool, int, signed int, or unsigned int.
242 //
243 // If an int can represent all values of the original type, the
244 // value is converted to an int; otherwise, it is converted to an
245 // unsigned int. These are called the integer promotions. All
246 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000247 QualType PTy = Context.isPromotableBitField(Expr);
248 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000249 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000250 return Expr;
251 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000252 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000253 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000254 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000255 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000256 }
257
Douglas Gregorb92a1562010-02-03 00:27:59 +0000258 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000259 return Expr;
260}
261
Chris Lattner2ce500f2008-07-25 22:25:12 +0000262/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000263/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000264/// double. All other argument types are converted by UsualUnaryConversions().
265void Sema::DefaultArgumentPromotion(Expr *&Expr) {
266 QualType Ty = Expr->getType();
267 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattner2ce500f2008-07-25 22:25:12 +0000269 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000270 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000271 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000272 return ImpCastExprToType(Expr, Context.DoubleTy,
273 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner2ce500f2008-07-25 22:25:12 +0000275 UsualUnaryConversions(Expr);
276}
277
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000278/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
279/// will warn if the resulting type is not a POD type, and rejects ObjC
280/// interfaces passed by value. This returns true if the argument type is
281/// completely illegal.
282bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000283 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000284
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000285 if (Expr->getType()->isObjCInterfaceType() &&
286 DiagRuntimeBehavior(Expr->getLocStart(),
287 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
288 << Expr->getType() << CT))
289 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000290
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000291 if (!Expr->getType()->isPODType() &&
292 DiagRuntimeBehavior(Expr->getLocStart(),
293 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
294 << Expr->getType() << CT))
295 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000296
297 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000298}
299
300
Chris Lattner513165e2008-07-25 21:10:04 +0000301/// UsualArithmeticConversions - Performs various conversions that are common to
302/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000303/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000304/// responsible for emitting appropriate error diagnostics.
305/// FIXME: verify the conversion rules for "complex int" are consistent with
306/// GCC.
307QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
308 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000309 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000310 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000311
312 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000313
Mike Stump11289f42009-09-09 15:08:12 +0000314 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000315 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000316 QualType lhs =
317 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000318 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000319 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000320
321 // If both types are identical, no conversion is needed.
322 if (lhs == rhs)
323 return lhs;
324
325 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
326 // The caller can deal with this (e.g. pointer + int).
327 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
328 return lhs;
329
Douglas Gregord2c2d172009-05-02 00:36:19 +0000330 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000331 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000332 if (!LHSBitfieldPromoteTy.isNull())
333 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000334 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000335 if (!RHSBitfieldPromoteTy.isNull())
336 rhs = RHSBitfieldPromoteTy;
337
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000338 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000339 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000340 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
341 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000342 return destType;
343}
344
Chris Lattner513165e2008-07-25 21:10:04 +0000345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff83895f72007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner8a24e582009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000361 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000363
Chris Lattner23b7eb62007-06-15 23:05:46 +0000364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000367
Chris Lattner36fc8792008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000375
Chris Lattner36fc8792008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattner5b183d82006-11-10 05:03:26 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000389}
390
Chris Lattner2a9d9892008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000396/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000397/// up-to-date.
398///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000399static bool ShouldSnapshotBlockValueReference(BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattner2a9d9892008-10-20 05:16:36 +0000406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000414 if (!Var->hasLocalStorage())
415 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner497d7b02009-04-21 22:26:47 +0000417 // Blocks that have these can't be constant.
418 CurBlock->hasBlockDeclRefExprs = true;
419
420 // If we have nested blocks, the decl may be declared in an outer block (in
421 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
422 // be defined outside all of the current blocks (in which case the blocks do
423 // all get the bit). Walk the nesting chain.
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000424 for (BlockScopeInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
Chris Lattner497d7b02009-04-21 22:26:47 +0000425 NextBlock = NextBlock->PrevBlockInfo) {
426 // If we found the defining block for the variable, don't mark the block as
427 // having a reference outside it.
428 if (NextBlock->TheDecl == VD->getDeclContext())
429 break;
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattner497d7b02009-04-21 22:26:47 +0000431 // Otherwise, the DeclRef from the inner block causes the outer one to need
432 // a snapshot as well.
433 NextBlock->hasBlockDeclRefExprs = true;
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner2a9d9892008-10-20 05:16:36 +0000436 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000437}
438
Chris Lattner2a9d9892008-10-20 05:16:36 +0000439
440
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000441/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000442Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000443Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000444 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000445 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
446 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000447 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000448 << D->getDeclName();
449 return ExprError();
450 }
Mike Stump11289f42009-09-09 15:08:12 +0000451
Anders Carlsson946b86d2009-06-24 00:10:43 +0000452 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
453 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
454 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
455 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000457 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000458 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000459 << D->getIdentifier();
460 return ExprError();
461 }
462 }
463 }
464 }
Mike Stump11289f42009-09-09 15:08:12 +0000465
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000466 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000468 return Owned(DeclRefExpr::Create(Context,
469 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
470 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000471 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000472}
473
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000474/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
475/// variable corresponding to the anonymous union or struct whose type
476/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000477static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
478 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000479 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000480 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000481
Mike Stump87c57ac2009-05-16 07:39:55 +0000482 // FIXME: Once Decls are directly linked together, this will be an O(1)
483 // operation rather than a slow walk through DeclContext's vector (which
484 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000485 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000486 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000487 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000488 D != DEnd; ++D) {
489 if (*D == Record) {
490 // The object for the anonymous struct/union directly
491 // follows its type in the list of declarations.
492 ++D;
493 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000494 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000495 return *D;
496 }
497 }
498
499 assert(false && "Missing object for anonymous record");
500 return 0;
501}
502
Douglas Gregord5846a12009-04-15 06:41:24 +0000503/// \brief Given a field that represents a member of an anonymous
504/// struct/union, build the path from that field's context to the
505/// actual member.
506///
507/// Construct the sequence of field member references we'll have to
508/// perform to get to the field in the anonymous union/struct. The
509/// list of members is built from the field outward, so traverse it
510/// backwards to go from an object in the current context to the field
511/// we found.
512///
513/// \returns The variable from which the field access should begin,
514/// for an anonymous struct/union that is not a member of another
515/// class. Otherwise, returns NULL.
516VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
517 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000518 assert(Field->getDeclContext()->isRecord() &&
519 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
520 && "Field must be stored inside an anonymous struct or union");
521
Douglas Gregord5846a12009-04-15 06:41:24 +0000522 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000523 VarDecl *BaseObject = 0;
524 DeclContext *Ctx = Field->getDeclContext();
525 do {
526 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000527 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000528 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000529 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000530 else {
531 BaseObject = cast<VarDecl>(AnonObject);
532 break;
533 }
534 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000535 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000536 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000537
538 return BaseObject;
539}
540
541Sema::OwningExprResult
542Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
543 FieldDecl *Field,
544 Expr *BaseObjectExpr,
545 SourceLocation OpLoc) {
546 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000547 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000548 AnonFields);
549
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000550 // Build the expression that refers to the base object, from
551 // which we will build a sequence of member references to each
552 // of the anonymous union objects and, eventually, the field we
553 // found via name lookup.
554 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000555 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000556 if (BaseObject) {
557 // BaseObject is an anonymous struct/union variable (and is,
558 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000559 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000560 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000561 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000562 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000563 BaseQuals
564 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000565 } else if (BaseObjectExpr) {
566 // The caller provided the base object expression. Determine
567 // whether its a pointer and whether it adds any qualifiers to the
568 // anonymous struct/union fields we're looking into.
569 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 ObjectType = ObjectPtr->getPointeeType();
573 }
John McCall8ccfcb52009-09-24 19:53:00 +0000574 BaseQuals
575 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 } else {
577 // We've found a member of an anonymous struct/union that is
578 // inside a non-anonymous struct/union, so in a well-formed
579 // program our base object expression is "this".
580 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
581 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000582 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000583 = Context.getTagDeclType(
584 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
585 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000586 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000587 == Context.getCanonicalType(ThisType)) ||
588 IsDerivedFrom(ThisType, AnonFieldType)) {
589 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000590 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000591 MD->getThisType(Context),
592 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000593 BaseObjectIsPointer = true;
594 }
595 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000596 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
597 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000598 }
John McCall8ccfcb52009-09-24 19:53:00 +0000599 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000600 }
601
Mike Stump11289f42009-09-09 15:08:12 +0000602 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000603 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
604 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000605 }
606
607 // Build the implicit member references to the field of the
608 // anonymous struct/union.
609 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000610 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000611 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
612 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
613 FI != FIEnd; ++FI) {
614 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000615 Qualifiers MemberTypeQuals =
616 Context.getCanonicalType(MemberType).getQualifiers();
617
618 // CVR attributes from the base are picked up by members,
619 // except that 'mutable' members don't pick up 'const'.
620 if ((*FI)->isMutable())
621 ResultQuals.removeConst();
622
623 // GC attributes are never picked up by members.
624 ResultQuals.removeObjCGCAttr();
625
626 // TR 18037 does not allow fields to be declared with address spaces.
627 assert(!MemberTypeQuals.hasAddressSpace());
628
629 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
630 if (NewQuals != MemberTypeQuals)
631 MemberType = Context.getQualifiedType(MemberType, NewQuals);
632
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000633 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000634 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000639 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000640 }
641
Sebastian Redlffbcf962009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000643}
644
John McCall10eae182009-11-30 22:42:35 +0000645/// Decomposes the given name into a DeclarationName, its location, and
646/// possibly a list of template arguments.
647///
648/// If this produces template arguments, it is permitted to call
649/// DecomposeTemplateName.
650///
651/// This actually loses a lot of source location information for
652/// non-standard name kinds; we should consider preserving that in
653/// some way.
654static void DecomposeUnqualifiedId(Sema &SemaRef,
655 const UnqualifiedId &Id,
656 TemplateArgumentListInfo &Buffer,
657 DeclarationName &Name,
658 SourceLocation &NameLoc,
659 const TemplateArgumentListInfo *&TemplateArgs) {
660 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
661 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
662 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
663
664 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
665 Id.TemplateId->getTemplateArgs(),
666 Id.TemplateId->NumArgs);
667 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
668 TemplateArgsPtr.release();
669
670 TemplateName TName =
671 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
672
673 Name = SemaRef.Context.getNameForTemplate(TName);
674 NameLoc = Id.TemplateId->TemplateNameLoc;
675 TemplateArgs = &Buffer;
676 } else {
677 Name = SemaRef.GetNameFromUnqualifiedId(Id);
678 NameLoc = Id.StartLocation;
679 TemplateArgs = 0;
680 }
681}
682
683/// Decompose the given template name into a list of lookup results.
684///
685/// The unqualified ID must name a non-dependent template, which can
686/// be more easily tested by checking whether DecomposeUnqualifiedId
687/// found template arguments.
688static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
689 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
690 TemplateName TName =
691 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
692
John McCalle66edc12009-11-24 19:00:30 +0000693 if (TemplateDecl *TD = TName.getAsTemplateDecl())
694 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000695 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
696 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
697 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000698 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000699
John McCalle66edc12009-11-24 19:00:30 +0000700 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000701}
702
John McCall69f9dbc2010-02-08 19:26:07 +0000703/// Determines whether the given record is "fully-formed" at the given
704/// location, i.e. whether a qualified lookup into it is assured of
705/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000706static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000707 if (!Record->hasDefinition())
708 return false;
709
John McCall10eae182009-11-30 22:42:35 +0000710 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
711 E = Record->bases_end(); I != E; ++I) {
712 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
713 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
714 if (!BaseRT) return false;
715
716 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000717 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000718 !IsFullyFormedScope(SemaRef, BaseRecord))
719 return false;
720 }
721
722 return true;
723}
724
John McCallf786fb12009-11-30 23:50:49 +0000725/// Determines whether we can lookup this id-expression now or whether
726/// we have to wait until template instantiation is complete.
727static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000728 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000729
John McCallf786fb12009-11-30 23:50:49 +0000730 // If the qualifier scope isn't computable, it's definitely dependent.
731 if (!DC) return true;
732
733 // If the qualifier scope doesn't name a record, we can always look into it.
734 if (!isa<CXXRecordDecl>(DC)) return false;
735
736 // We can't look into record types unless they're fully-formed.
737 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
738
John McCall2d74de92009-12-01 22:10:20 +0000739 return false;
740}
John McCallf786fb12009-11-30 23:50:49 +0000741
John McCall2d74de92009-12-01 22:10:20 +0000742/// Determines if the given class is provably not derived from all of
743/// the prospective base classes.
744static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
745 CXXRecordDecl *Record,
746 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000747 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000748 return false;
749
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000750 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +0000751 if (!RD) return false;
752 Record = cast<CXXRecordDecl>(RD);
753
John McCall2d74de92009-12-01 22:10:20 +0000754 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
755 E = Record->bases_end(); I != E; ++I) {
756 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
757 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
758 if (!BaseRT) return false;
759
760 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000761 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
762 return false;
763 }
764
765 return true;
766}
767
John McCall5af04502009-12-02 20:26:00 +0000768/// Determines if this is an instance member of a class.
769static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000770 assert(D->isCXXClassMember() &&
John McCall2d74de92009-12-01 22:10:20 +0000771 "checking whether non-member is instance member");
772
773 if (isa<FieldDecl>(D)) return true;
774
775 if (isa<CXXMethodDecl>(D))
776 return !cast<CXXMethodDecl>(D)->isStatic();
777
778 if (isa<FunctionTemplateDecl>(D)) {
779 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
780 return !cast<CXXMethodDecl>(D)->isStatic();
781 }
782
783 return false;
784}
785
786enum IMAKind {
787 /// The reference is definitely not an instance member access.
788 IMA_Static,
789
790 /// The reference may be an implicit instance member access.
791 IMA_Mixed,
792
793 /// The reference may be to an instance member, but it is invalid if
794 /// so, because the context is not an instance method.
795 IMA_Mixed_StaticContext,
796
797 /// The reference may be to an instance member, but it is invalid if
798 /// so, because the context is from an unrelated class.
799 IMA_Mixed_Unrelated,
800
801 /// The reference is definitely an implicit instance member access.
802 IMA_Instance,
803
804 /// The reference may be to an unresolved using declaration.
805 IMA_Unresolved,
806
807 /// The reference may be to an unresolved using declaration and the
808 /// context is not an instance method.
809 IMA_Unresolved_StaticContext,
810
811 /// The reference is to a member of an anonymous structure in a
812 /// non-class context.
813 IMA_AnonymousMember,
814
815 /// All possible referrents are instance members and the current
816 /// context is not an instance method.
817 IMA_Error_StaticContext,
818
819 /// All possible referrents are instance members of an unrelated
820 /// class.
821 IMA_Error_Unrelated
822};
823
824/// The given lookup names class member(s) and is not being used for
825/// an address-of-member expression. Classify the type of access
826/// according to whether it's possible that this reference names an
827/// instance member. This is best-effort; it is okay to
828/// conservatively answer "yes", in which case some errors will simply
829/// not be caught until template-instantiation.
830static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
831 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000832 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000833
834 bool isStaticContext =
835 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
836 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
837
838 if (R.isUnresolvableResult())
839 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
840
841 // Collect all the declaring classes of instance members we find.
842 bool hasNonInstance = false;
843 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
844 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
845 NamedDecl *D = (*I)->getUnderlyingDecl();
846 if (IsInstanceMember(D)) {
847 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
848
849 // If this is a member of an anonymous record, move out to the
850 // innermost non-anonymous struct or union. If there isn't one,
851 // that's a special case.
852 while (R->isAnonymousStructOrUnion()) {
853 R = dyn_cast<CXXRecordDecl>(R->getParent());
854 if (!R) return IMA_AnonymousMember;
855 }
856 Classes.insert(R->getCanonicalDecl());
857 }
858 else
859 hasNonInstance = true;
860 }
861
862 // If we didn't find any instance members, it can't be an implicit
863 // member reference.
864 if (Classes.empty())
865 return IMA_Static;
866
867 // If the current context is not an instance method, it can't be
868 // an implicit member reference.
869 if (isStaticContext)
870 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
871
872 // If we can prove that the current context is unrelated to all the
873 // declaring classes, it can't be an implicit member reference (in
874 // which case it's an error if any of those members are selected).
875 if (IsProvablyNotDerivedFrom(SemaRef,
876 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
877 Classes))
878 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
879
880 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
881}
882
883/// Diagnose a reference to a field with no object available.
884static void DiagnoseInstanceReference(Sema &SemaRef,
885 const CXXScopeSpec &SS,
886 const LookupResult &R) {
887 SourceLocation Loc = R.getNameLoc();
888 SourceRange Range(Loc);
889 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
890
891 if (R.getAsSingle<FieldDecl>()) {
892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
893 if (MD->isStatic()) {
894 // "invalid use of member 'x' in static member function"
895 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
896 << Range << R.getLookupName();
897 return;
898 }
899 }
900
901 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
902 << R.getLookupName() << Range;
903 return;
904 }
905
906 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000907}
908
John McCalld681c392009-12-16 08:11:27 +0000909/// Diagnose an empty lookup.
910///
911/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000912bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000913 LookupResult &R) {
914 DeclarationName Name = R.getLookupName();
915
John McCalld681c392009-12-16 08:11:27 +0000916 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000917 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000918 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
919 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000920 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000921 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000922 diagnostic_suggest = diag::err_undeclared_use_suggest;
923 }
John McCalld681c392009-12-16 08:11:27 +0000924
Douglas Gregor598b08f2009-12-31 05:20:13 +0000925 // If the original lookup was an unqualified lookup, fake an
926 // unqualified lookup. This is useful when (for example) the
927 // original lookup would not have found something because it was a
928 // dependent name.
929 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
930 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000931 if (isa<CXXRecordDecl>(DC)) {
932 LookupQualifiedName(R, DC);
933
934 if (!R.empty()) {
935 // Don't give errors about ambiguities in this lookup.
936 R.suppressDiagnostics();
937
938 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
939 bool isInstance = CurMethod &&
940 CurMethod->isInstance() &&
941 DC == CurMethod->getParent();
942
943 // Give a code modification hint to insert 'this->'.
944 // TODO: fixit for inserting 'Base<T>::' in the other cases.
945 // Actually quite difficult!
946 if (isInstance)
947 Diag(R.getNameLoc(), diagnostic) << Name
948 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
949 "this->");
950 else
951 Diag(R.getNameLoc(), diagnostic) << Name;
952
953 // Do we really want to note all of these?
954 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
955 Diag((*I)->getLocation(), diag::note_dependent_var_use);
956
957 // Tell the callee to try to recover.
958 return false;
959 }
960 }
961 }
962
Douglas Gregor598b08f2009-12-31 05:20:13 +0000963 // We didn't find anything, so try to correct for a typo.
Douglas Gregor25363982010-01-01 00:15:04 +0000964 if (S && CorrectTypo(R, S, &SS)) {
965 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
966 if (SS.isEmpty())
967 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
968 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000969 R.getLookupName().getAsString());
Douglas Gregor25363982010-01-01 00:15:04 +0000970 else
971 Diag(R.getNameLoc(), diag::err_no_member_suggest)
972 << Name << computeDeclContext(SS, false) << R.getLookupName()
973 << SS.getRange()
974 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000975 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000976 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
977 Diag(ND->getLocation(), diag::note_previous_decl)
978 << ND->getDeclName();
979
Douglas Gregor25363982010-01-01 00:15:04 +0000980 // Tell the callee to try to recover.
981 return false;
982 }
983
984 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
985 // FIXME: If we ended up with a typo for a type name or
986 // Objective-C class name, we're in trouble because the parser
987 // is in the wrong place to recover. Suggest the typo
988 // correction, but don't make it a fix-it since we're not going
989 // to recover well anyway.
990 if (SS.isEmpty())
991 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
992 else
993 Diag(R.getNameLoc(), diag::err_no_member_suggest)
994 << Name << computeDeclContext(SS, false) << R.getLookupName()
995 << SS.getRange();
996
997 // Don't try to recover; it won't work.
998 return true;
999 }
1000
1001 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001002 }
1003
1004 // Emit a special diagnostic for failed member lookups.
1005 // FIXME: computing the declaration context might fail here (?)
1006 if (!SS.isEmpty()) {
1007 Diag(R.getNameLoc(), diag::err_no_member)
1008 << Name << computeDeclContext(SS, false)
1009 << SS.getRange();
1010 return true;
1011 }
1012
John McCalld681c392009-12-16 08:11:27 +00001013 // Give up, we can't recover.
1014 Diag(R.getNameLoc(), diagnostic) << Name;
1015 return true;
1016}
1017
John McCalle66edc12009-11-24 19:00:30 +00001018Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
1019 const CXXScopeSpec &SS,
1020 UnqualifiedId &Id,
1021 bool HasTrailingLParen,
1022 bool isAddressOfOperand) {
1023 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1024 "cannot be direct & operand and have a trailing lparen");
1025
1026 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001027 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001028
John McCall10eae182009-11-30 22:42:35 +00001029 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001030
1031 // Decompose the UnqualifiedId into the following data.
1032 DeclarationName Name;
1033 SourceLocation NameLoc;
1034 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00001035 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1036 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001037
Douglas Gregor4ea80432008-11-18 15:03:34 +00001038 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001039
John McCalle66edc12009-11-24 19:00:30 +00001040 // C++ [temp.dep.expr]p3:
1041 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001042 // -- an identifier that was declared with a dependent type,
1043 // (note: handled after lookup)
1044 // -- a template-id that is dependent,
1045 // (note: handled in BuildTemplateIdExpr)
1046 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001047 // -- a nested-name-specifier that contains a class-name that
1048 // names a dependent type.
1049 // Determine whether this is a member of an unknown specialization;
1050 // we need to handle these differently.
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001051 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1052 Name.getCXXNameType()->isDependentType()) ||
1053 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001054 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001055 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001056 TemplateArgs);
1057 }
John McCalld14a8642009-11-21 08:51:07 +00001058
John McCalle66edc12009-11-24 19:00:30 +00001059 // Perform the required lookup.
1060 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1061 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001062 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001063 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001064 } else {
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001065 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1066 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001067
John McCalle66edc12009-11-24 19:00:30 +00001068 // If this reference is in an Objective-C method, then we need to do
1069 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001070 if (IvarLookupFollowUp) {
1071 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001072 if (E.isInvalid())
1073 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001074
John McCalle66edc12009-11-24 19:00:30 +00001075 Expr *Ex = E.takeAs<Expr>();
1076 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001077 }
Chris Lattner59a25942008-03-31 00:36:02 +00001078 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001079
John McCalle66edc12009-11-24 19:00:30 +00001080 if (R.isAmbiguous())
1081 return ExprError();
1082
Douglas Gregor171c45a2009-02-18 21:56:37 +00001083 // Determine whether this name might be a candidate for
1084 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001085 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001086
John McCalle66edc12009-11-24 19:00:30 +00001087 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001088 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001089 // in C90, extension in C99, forbidden in C++).
1090 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1091 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1092 if (D) R.addDecl(D);
1093 }
1094
1095 // If this name wasn't predeclared and if this is not a function
1096 // call, diagnose the problem.
1097 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001098 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001099 return ExprError();
1100
1101 assert(!R.empty() &&
1102 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001103
1104 // If we found an Objective-C instance variable, let
1105 // LookupInObjCMethod build the appropriate expression to
1106 // reference the ivar.
1107 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1108 R.clear();
1109 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1110 assert(E.isInvalid() || E.get());
1111 return move(E);
1112 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001113 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
John McCalle66edc12009-11-24 19:00:30 +00001116 // This is guaranteed from this point on.
1117 assert(!R.empty() || ADL);
1118
1119 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001120 // Warn about constructs like:
1121 // if (void *X = foo()) { ... } else { X }.
1122 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001123
Douglas Gregor3256d042009-06-30 15:47:41 +00001124 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1125 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001126 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001127 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001128 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001129 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001130 << Var->getDeclName()
1131 << (Var->getType()->isPointerType()? 2 :
1132 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001133 break;
1134 }
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregor13a2c032009-11-05 17:49:26 +00001136 // Move to the parent of this scope.
1137 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001138 }
1139 }
John McCalle66edc12009-11-24 19:00:30 +00001140 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001141 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1142 // C99 DR 316 says that, if a function type comes from a
1143 // function definition (without a prototype), that type is only
1144 // used for checking compatibility. Therefore, when referencing
1145 // the function, we pretend that we don't have the full function
1146 // type.
John McCalle66edc12009-11-24 19:00:30 +00001147 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001148 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001149
Douglas Gregor3256d042009-06-30 15:47:41 +00001150 QualType T = Func->getType();
1151 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001152 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001153 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001154 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001155 }
1156 }
Mike Stump11289f42009-09-09 15:08:12 +00001157
John McCall2d74de92009-12-01 22:10:20 +00001158 // Check whether this might be a C++ implicit instance member access.
1159 // C++ [expr.prim.general]p6:
1160 // Within the definition of a non-static member function, an
1161 // identifier that names a non-static member is transformed to a
1162 // class member access expression.
1163 // But note that &SomeClass::foo is grammatically distinct, even
1164 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001165 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001166 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001167 if (!isAbstractMemberPointer)
1168 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001169 }
1170
John McCalle66edc12009-11-24 19:00:30 +00001171 if (TemplateArgs)
1172 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001173
John McCalle66edc12009-11-24 19:00:30 +00001174 return BuildDeclarationNameExpr(SS, R, ADL);
1175}
1176
John McCall57500772009-12-16 12:17:52 +00001177/// Builds an expression which might be an implicit member expression.
1178Sema::OwningExprResult
1179Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1180 LookupResult &R,
1181 const TemplateArgumentListInfo *TemplateArgs) {
1182 switch (ClassifyImplicitMemberAccess(*this, R)) {
1183 case IMA_Instance:
1184 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1185
1186 case IMA_AnonymousMember:
1187 assert(R.isSingleResult());
1188 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1189 R.getAsSingle<FieldDecl>());
1190
1191 case IMA_Mixed:
1192 case IMA_Mixed_Unrelated:
1193 case IMA_Unresolved:
1194 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1195
1196 case IMA_Static:
1197 case IMA_Mixed_StaticContext:
1198 case IMA_Unresolved_StaticContext:
1199 if (TemplateArgs)
1200 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1201 return BuildDeclarationNameExpr(SS, R, false);
1202
1203 case IMA_Error_StaticContext:
1204 case IMA_Error_Unrelated:
1205 DiagnoseInstanceReference(*this, SS, R);
1206 return ExprError();
1207 }
1208
1209 llvm_unreachable("unexpected instance member access kind");
1210 return ExprError();
1211}
1212
John McCall10eae182009-11-30 22:42:35 +00001213/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1214/// declaration name, generally during template instantiation.
1215/// There's a large number of things which don't need to be done along
1216/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001217Sema::OwningExprResult
1218Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1219 DeclarationName Name,
1220 SourceLocation NameLoc) {
1221 DeclContext *DC;
1222 if (!(DC = computeDeclContext(SS, false)) ||
1223 DC->isDependentContext() ||
1224 RequireCompleteDeclContext(SS))
1225 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1226
1227 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1228 LookupQualifiedName(R, DC);
1229
1230 if (R.isAmbiguous())
1231 return ExprError();
1232
1233 if (R.empty()) {
1234 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1235 return ExprError();
1236 }
1237
1238 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1239}
1240
1241/// LookupInObjCMethod - The parser has read a name in, and Sema has
1242/// detected that we're currently inside an ObjC method. Perform some
1243/// additional lookup.
1244///
1245/// Ideally, most of this would be done by lookup, but there's
1246/// actually quite a lot of extra work involved.
1247///
1248/// Returns a null sentinel to indicate trivial success.
1249Sema::OwningExprResult
1250Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001251 IdentifierInfo *II,
1252 bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001253 SourceLocation Loc = Lookup.getNameLoc();
1254
1255 // There are two cases to handle here. 1) scoped lookup could have failed,
1256 // in which case we should look for an ivar. 2) scoped lookup could have
1257 // found a decl, but that decl is outside the current instance method (i.e.
1258 // a global variable). In these two cases, we do a lookup for an ivar with
1259 // this name, if the lookup sucedes, we replace it our current decl.
1260
1261 // If we're in a class method, we don't normally want to look for
1262 // ivars. But if we don't find anything else, and there's an
1263 // ivar, that's an error.
1264 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1265
1266 bool LookForIvars;
1267 if (Lookup.empty())
1268 LookForIvars = true;
1269 else if (IsClassMethod)
1270 LookForIvars = false;
1271 else
1272 LookForIvars = (Lookup.isSingleResult() &&
1273 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001274 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001275 if (LookForIvars) {
Fariborz Jahanian45878032010-02-09 19:31:38 +00001276 IFace = getCurMethodDecl()->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001277 ObjCInterfaceDecl *ClassDeclared;
1278 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1279 // Diagnose using an ivar in a class method.
1280 if (IsClassMethod)
1281 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1282 << IV->getDeclName());
1283
1284 // If we're referencing an invalid decl, just return this as a silent
1285 // error node. The error diagnostic was already emitted on the decl.
1286 if (IV->isInvalidDecl())
1287 return ExprError();
1288
1289 // Check if referencing a field with __attribute__((deprecated)).
1290 if (DiagnoseUseOfDecl(IV, Loc))
1291 return ExprError();
1292
1293 // Diagnose the use of an ivar outside of the declaring class.
1294 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1295 ClassDeclared != IFace)
1296 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1297
1298 // FIXME: This should use a new expr for a direct reference, don't
1299 // turn this into Self->ivar, just return a BareIVarExpr or something.
1300 IdentifierInfo &II = Context.Idents.get("self");
1301 UnqualifiedId SelfName;
1302 SelfName.setIdentifier(&II, SourceLocation());
1303 CXXScopeSpec SelfScopeSpec;
1304 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1305 SelfName, false, false);
1306 MarkDeclarationReferenced(Loc, IV);
1307 return Owned(new (Context)
1308 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1309 SelfExpr.takeAs<Expr>(), true, true));
1310 }
1311 } else if (getCurMethodDecl()->isInstanceMethod()) {
1312 // We should warn if a local variable hides an ivar.
1313 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1314 ObjCInterfaceDecl *ClassDeclared;
1315 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1316 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1317 IFace == ClassDeclared)
1318 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1319 }
1320 }
1321
1322 // Needed to implement property "super.method" notation.
1323 if (Lookup.empty() && II->isStr("super")) {
1324 QualType T;
1325
1326 if (getCurMethodDecl()->isInstanceMethod())
1327 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1328 getCurMethodDecl()->getClassInterface()));
1329 else
1330 T = Context.getObjCClassType();
1331 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1332 }
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001333 if (Lookup.empty() && II && AllowBuiltinCreation) {
1334 // FIXME. Consolidate this with similar code in LookupName.
1335 if (unsigned BuiltinID = II->getBuiltinID()) {
1336 if (!(getLangOptions().CPlusPlus &&
1337 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1338 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1339 S, Lookup.isForRedeclaration(),
1340 Lookup.getNameLoc());
1341 if (D) Lookup.addDecl(D);
1342 }
1343 }
1344 }
Fariborz Jahanian45878032010-02-09 19:31:38 +00001345 if (LangOpts.ObjCNonFragileABI2 && LookForIvars && Lookup.empty()) {
Fariborz Jahanian5db52812010-02-09 21:49:50 +00001346 ObjCIvarDecl *Ivar = SynthesizeNewPropertyIvar(IFace, II);
1347 if (Ivar)
Fariborz Jahanian45878032010-02-09 19:31:38 +00001348 return LookupInObjCMethod(Lookup, S, II, AllowBuiltinCreation);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001349 }
John McCalle66edc12009-11-24 19:00:30 +00001350 // Sentinel value saying that we didn't do anything special.
1351 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001352}
John McCalld14a8642009-11-21 08:51:07 +00001353
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001354/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001355bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001356Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1357 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001358 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001359 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001360 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001361 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001362 if (DestType->isDependentType() || From->getType()->isDependentType())
1363 return false;
1364 QualType FromRecordType = From->getType();
1365 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001367 DestType = Context.getPointerType(DestType);
1368 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001369 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001370 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1371 CheckDerivedToBaseConversion(FromRecordType,
1372 DestRecordType,
1373 From->getSourceRange().getBegin(),
1374 From->getSourceRange()))
1375 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001376 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1377 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001378 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001379 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001380}
Douglas Gregor3256d042009-06-30 15:47:41 +00001381
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001382/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001383static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001384 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001385 SourceLocation Loc, QualType Ty,
1386 const TemplateArgumentListInfo *TemplateArgs = 0) {
1387 NestedNameSpecifier *Qualifier = 0;
1388 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001389 if (SS.isSet()) {
1390 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1391 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
John McCalle66edc12009-11-24 19:00:30 +00001394 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1395 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001396}
1397
John McCall2d74de92009-12-01 22:10:20 +00001398/// Builds an implicit member access expression. The current context
1399/// is known to be an instance method, and the given unqualified lookup
1400/// set is known to contain only instance members, at least one of which
1401/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001402Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001403Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1404 LookupResult &R,
1405 const TemplateArgumentListInfo *TemplateArgs,
1406 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001407 assert(!R.empty() && !R.isAmbiguous());
1408
John McCalld14a8642009-11-21 08:51:07 +00001409 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001410
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001411 // We may have found a field within an anonymous union or struct
1412 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001413 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001414 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001415 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001416 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001417 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001418
John McCall2d74de92009-12-01 22:10:20 +00001419 // If this is known to be an instance access, go ahead and build a
1420 // 'this' expression now.
1421 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1422 Expr *This = 0; // null signifies implicit access
1423 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001424 SourceLocation Loc = R.getNameLoc();
1425 if (SS.getRange().isValid())
1426 Loc = SS.getRange().getBegin();
1427 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001428 }
1429
John McCall2d74de92009-12-01 22:10:20 +00001430 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1431 /*OpLoc*/ SourceLocation(),
1432 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001433 SS,
1434 /*FirstQualifierInScope*/ 0,
1435 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001436}
1437
John McCalle66edc12009-11-24 19:00:30 +00001438bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001439 const LookupResult &R,
1440 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001441 // Only when used directly as the postfix-expression of a call.
1442 if (!HasTrailingLParen)
1443 return false;
1444
1445 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001446 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001447 return false;
1448
1449 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001450 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001451 return false;
1452
1453 // Turn off ADL when we find certain kinds of declarations during
1454 // normal lookup:
1455 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1456 NamedDecl *D = *I;
1457
1458 // C++0x [basic.lookup.argdep]p3:
1459 // -- a declaration of a class member
1460 // Since using decls preserve this property, we check this on the
1461 // original decl.
John McCall57500772009-12-16 12:17:52 +00001462 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001463 return false;
1464
1465 // C++0x [basic.lookup.argdep]p3:
1466 // -- a block-scope function declaration that is not a
1467 // using-declaration
1468 // NOTE: we also trigger this for function templates (in fact, we
1469 // don't check the decl type at all, since all other decl types
1470 // turn off ADL anyway).
1471 if (isa<UsingShadowDecl>(D))
1472 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1473 else if (D->getDeclContext()->isFunctionOrMethod())
1474 return false;
1475
1476 // C++0x [basic.lookup.argdep]p3:
1477 // -- a declaration that is neither a function or a function
1478 // template
1479 // And also for builtin functions.
1480 if (isa<FunctionDecl>(D)) {
1481 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1482
1483 // But also builtin functions.
1484 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1485 return false;
1486 } else if (!isa<FunctionTemplateDecl>(D))
1487 return false;
1488 }
1489
1490 return true;
1491}
1492
1493
John McCalld14a8642009-11-21 08:51:07 +00001494/// Diagnoses obvious problems with the use of the given declaration
1495/// as an expression. This is only actually called for lookups that
1496/// were not overloaded, and it doesn't promise that the declaration
1497/// will in fact be used.
1498static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1499 if (isa<TypedefDecl>(D)) {
1500 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1501 return true;
1502 }
1503
1504 if (isa<ObjCInterfaceDecl>(D)) {
1505 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1506 return true;
1507 }
1508
1509 if (isa<NamespaceDecl>(D)) {
1510 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1511 return true;
1512 }
1513
1514 return false;
1515}
1516
1517Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001518Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001519 LookupResult &R,
1520 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001521 // If this is a single, fully-resolved result and we don't need ADL,
1522 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00001523 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCallb53bbd42009-11-22 01:44:31 +00001524 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001525
1526 // We only need to check the declaration if there's exactly one
1527 // result, because in the overloaded case the results can only be
1528 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001529 if (R.isSingleResult() &&
1530 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001531 return ExprError();
1532
John McCall58cc69d2010-01-27 01:50:18 +00001533 // Otherwise, just build an unresolved lookup expression. Suppress
1534 // any lookup-related diagnostics; we'll hash these out later, when
1535 // we've picked a target.
1536 R.suppressDiagnostics();
1537
John McCalle66edc12009-11-24 19:00:30 +00001538 bool Dependent
1539 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001540 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001541 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001542 (NestedNameSpecifier*) SS.getScopeRep(),
1543 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001544 R.getLookupName(), R.getNameLoc(),
1545 NeedsADL, R.isOverloadedResult());
John McCall58cc69d2010-01-27 01:50:18 +00001546 ULE->addDecls(R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001547
1548 return Owned(ULE);
1549}
1550
1551
1552/// \brief Complete semantic analysis for a reference to the given declaration.
1553Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001554Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001555 SourceLocation Loc, NamedDecl *D) {
1556 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001557 assert(!isa<FunctionTemplateDecl>(D) &&
1558 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001559
1560 if (CheckDeclInExpr(*this, Loc, D))
1561 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001562
Douglas Gregore7488b92009-12-01 16:58:18 +00001563 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1564 // Specifically diagnose references to class templates that are missing
1565 // a template argument list.
1566 Diag(Loc, diag::err_template_decl_ref)
1567 << Template << SS.getRange();
1568 Diag(Template->getLocation(), diag::note_template_decl_here);
1569 return ExprError();
1570 }
1571
1572 // Make sure that we're referring to a value.
1573 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1574 if (!VD) {
1575 Diag(Loc, diag::err_ref_non_value)
1576 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001577 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001578 return ExprError();
1579 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001580
Douglas Gregor171c45a2009-02-18 21:56:37 +00001581 // Check whether this declaration can be used. Note that we suppress
1582 // this check when we're going to perform argument-dependent lookup
1583 // on this function name, because this might not be the function
1584 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001585 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001586 return ExprError();
1587
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001588 // Only create DeclRefExpr's for valid Decl's.
1589 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001590 return ExprError();
1591
Chris Lattner2a9d9892008-10-20 05:16:36 +00001592 // If the identifier reference is inside a block, and it refers to a value
1593 // that is outside the block, create a BlockDeclRefExpr instead of a
1594 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1595 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001596 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001597 // We do not do this for things like enum constants, global variables, etc,
1598 // as they do not get snapshotted.
1599 //
1600 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001601 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1602 Diag(Loc, diag::err_ref_vm_type);
1603 Diag(D->getLocation(), diag::note_declared_at);
1604 return ExprError();
1605 }
1606
Mike Stump8971a862010-01-05 03:10:36 +00001607 if (VD->getType()->isArrayType()) {
1608 Diag(Loc, diag::err_ref_array_type);
1609 Diag(D->getLocation(), diag::note_declared_at);
1610 return ExprError();
1611 }
1612
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001613 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001614 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001615 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001616 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001617 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001618 // This is to record that a 'const' was actually synthesize and added.
1619 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001620 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001621
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001622 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001623 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001624 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001625 }
1626 // If this reference is not in a block or if the referenced variable is
1627 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001628
John McCalle66edc12009-11-24 19:00:30 +00001629 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001630}
Chris Lattnere168f762006-11-10 05:29:30 +00001631
Sebastian Redlffbcf962009-01-18 18:53:16 +00001632Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1633 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001634 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001635
Chris Lattnere168f762006-11-10 05:29:30 +00001636 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001637 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001638 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1639 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1640 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001641 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001642
Chris Lattnera81a0272008-01-12 08:14:25 +00001643 // Pre-defined identifiers are of type char[x], where x is the length of the
1644 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001645
Anders Carlsson2fb08242009-09-08 18:24:21 +00001646 Decl *currentDecl = getCurFunctionOrMethodDecl();
1647 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001648 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001649 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001650 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001651
Anders Carlsson0b209a82009-09-11 01:22:35 +00001652 QualType ResTy;
1653 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1654 ResTy = Context.DependentTy;
1655 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001656 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001657
Anders Carlsson0b209a82009-09-11 01:22:35 +00001658 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001659 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001660 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1661 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001662 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001663}
1664
Sebastian Redlffbcf962009-01-18 18:53:16 +00001665Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001666 llvm::SmallString<16> CharBuffer;
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001667 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001668
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001669 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1670 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00001671 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001672 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001673
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001674 QualType Ty;
1675 if (!getLangOptions().CPlusPlus)
1676 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1677 else if (Literal.isWide())
1678 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00001679 else if (Literal.isMultiChar())
1680 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001681 else
1682 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001683
Sebastian Redl20614a72009-01-20 22:23:13 +00001684 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1685 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001686 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001687}
1688
Sebastian Redlffbcf962009-01-18 18:53:16 +00001689Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1690 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001691 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1692 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001693 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001694 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001695 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001696 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001697 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001698
Chris Lattner23b7eb62007-06-15 23:05:46 +00001699 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001700 // Add padding so that NumericLiteralParser can overread by one character.
1701 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001702 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001703
Chris Lattner67ca9252007-05-21 01:08:44 +00001704 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001705 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001706
Mike Stump11289f42009-09-09 15:08:12 +00001707 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001708 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001709 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001710 return ExprError();
1711
Chris Lattner1c20a172007-08-26 03:42:43 +00001712 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001713
Chris Lattner1c20a172007-08-26 03:42:43 +00001714 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001715 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001716 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001717 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001718 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001719 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001720 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001721 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001722
1723 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1724
John McCall53b93a02009-12-24 09:08:04 +00001725 using llvm::APFloat;
1726 APFloat Val(Format);
1727
1728 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001729
1730 // Overflow is always an error, but underflow is only an error if
1731 // we underflowed to zero (APFloat reports denormals as underflow).
1732 if ((result & APFloat::opOverflow) ||
1733 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001734 unsigned diagnostic;
1735 llvm::SmallVector<char, 20> buffer;
1736 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00001737 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00001738 APFloat::getLargest(Format).toString(buffer);
1739 } else {
John McCall62abc942010-02-26 23:35:57 +00001740 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00001741 APFloat::getSmallest(Format).toString(buffer);
1742 }
1743
1744 Diag(Tok.getLocation(), diagnostic)
1745 << Ty
1746 << llvm::StringRef(buffer.data(), buffer.size());
1747 }
1748
1749 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001750 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001751
Chris Lattner1c20a172007-08-26 03:42:43 +00001752 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001753 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001754 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001755 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001756
Neil Boothac582c52007-08-29 22:00:19 +00001757 // long long is a C99 feature.
1758 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001759 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001760 Diag(Tok.getLocation(), diag::ext_longlong);
1761
Chris Lattner67ca9252007-05-21 01:08:44 +00001762 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001763 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001764
Chris Lattner67ca9252007-05-21 01:08:44 +00001765 if (Literal.GetIntegerValue(ResultVal)) {
1766 // If this value didn't fit into uintmax_t, warn and force to ull.
1767 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001768 Ty = Context.UnsignedLongLongTy;
1769 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001770 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001771 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001772 // If this value fits into a ULL, try to figure out what else it fits into
1773 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001774
Chris Lattner67ca9252007-05-21 01:08:44 +00001775 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1776 // be an unsigned int.
1777 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1778
1779 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001780 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001781 if (!Literal.isLong && !Literal.isLongLong) {
1782 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001783 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001784
Chris Lattner67ca9252007-05-21 01:08:44 +00001785 // Does it fit in a unsigned int?
1786 if (ResultVal.isIntN(IntSize)) {
1787 // Does it fit in a signed int?
1788 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001789 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001790 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001791 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001792 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001793 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001794 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001795
Chris Lattner67ca9252007-05-21 01:08:44 +00001796 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001797 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001798 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001799
Chris Lattner67ca9252007-05-21 01:08:44 +00001800 // Does it fit in a unsigned long?
1801 if (ResultVal.isIntN(LongSize)) {
1802 // Does it fit in a signed long?
1803 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001804 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001805 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001806 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001807 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001808 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001809 }
1810
Chris Lattner67ca9252007-05-21 01:08:44 +00001811 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001812 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001813 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001814
Chris Lattner67ca9252007-05-21 01:08:44 +00001815 // Does it fit in a unsigned long long?
1816 if (ResultVal.isIntN(LongLongSize)) {
1817 // Does it fit in a signed long long?
1818 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001819 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001820 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001821 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001822 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001823 }
1824 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001825
Chris Lattner67ca9252007-05-21 01:08:44 +00001826 // If we still couldn't decide a type, we probably have something that
1827 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001828 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001829 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001830 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001831 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001832 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001833
Chris Lattner55258cf2008-05-09 05:59:00 +00001834 if (ResultVal.getBitWidth() != Width)
1835 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001836 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001837 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001838 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001839
Chris Lattner1c20a172007-08-26 03:42:43 +00001840 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1841 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001842 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001843 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001844
1845 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001846}
1847
Sebastian Redlffbcf962009-01-18 18:53:16 +00001848Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1849 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001850 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001851 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001852 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001853}
1854
Steve Naroff71b59a92007-06-04 22:22:31 +00001855/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001856/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001857bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001858 SourceLocation OpLoc,
1859 const SourceRange &ExprRange,
1860 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001861 if (exprType->isDependentType())
1862 return false;
1863
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001864 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1865 // the result is the size of the referenced type."
1866 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1867 // result shall be the alignment of the referenced type."
1868 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1869 exprType = Ref->getPointeeType();
1870
Steve Naroff043d45d2007-05-15 02:32:35 +00001871 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001872 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001873 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001874 if (isSizeof)
1875 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1876 return false;
1877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattner62975a72009-04-24 00:30:45 +00001879 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001880 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001881 Diag(OpLoc, diag::ext_sizeof_void_type)
1882 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001883 return false;
1884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattner62975a72009-04-24 00:30:45 +00001886 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001887 PDiag(diag::err_sizeof_alignof_incomplete_type)
1888 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001889 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001890
Chris Lattner62975a72009-04-24 00:30:45 +00001891 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001892 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001893 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001894 << exprType << isSizeof << ExprRange;
1895 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
Chris Lattner62975a72009-04-24 00:30:45 +00001898 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001899}
1900
Chris Lattner8dff0172009-01-24 20:17:12 +00001901bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1902 const SourceRange &ExprRange) {
1903 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001904
Mike Stump11289f42009-09-09 15:08:12 +00001905 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001906 if (isa<DeclRefExpr>(E))
1907 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001908
1909 // Cannot know anything else if the expression is dependent.
1910 if (E->isTypeDependent())
1911 return false;
1912
Douglas Gregor71235ec2009-05-02 02:18:30 +00001913 if (E->getBitField()) {
1914 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1915 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001916 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001917
1918 // Alignment of a field access is always okay, so long as it isn't a
1919 // bit-field.
1920 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001921 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001922 return false;
1923
Chris Lattner8dff0172009-01-24 20:17:12 +00001924 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1925}
1926
Douglas Gregor0950e412009-03-13 21:01:28 +00001927/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001928Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001929Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001930 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001931 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001932 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001933 return ExprError();
1934
John McCallbcd03502009-12-07 02:54:59 +00001935 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001936
Douglas Gregor0950e412009-03-13 21:01:28 +00001937 if (!T->isDependentType() &&
1938 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1939 return ExprError();
1940
1941 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001942 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001943 Context.getSizeType(), OpLoc,
1944 R.getEnd()));
1945}
1946
1947/// \brief Build a sizeof or alignof expression given an expression
1948/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001949Action::OwningExprResult
1950Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001951 bool isSizeOf, SourceRange R) {
1952 // Verify that the operand is valid.
1953 bool isInvalid = false;
1954 if (E->isTypeDependent()) {
1955 // Delay type-checking for type-dependent expressions.
1956 } else if (!isSizeOf) {
1957 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001958 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001959 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1960 isInvalid = true;
1961 } else {
1962 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1963 }
1964
1965 if (isInvalid)
1966 return ExprError();
1967
1968 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1969 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1970 Context.getSizeType(), OpLoc,
1971 R.getEnd()));
1972}
1973
Sebastian Redl6f282892008-11-11 17:56:53 +00001974/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1975/// the same for @c alignof and @c __alignof
1976/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001977Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001978Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1979 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001980 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001981 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001982
Sebastian Redl6f282892008-11-11 17:56:53 +00001983 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001984 TypeSourceInfo *TInfo;
1985 (void) GetTypeFromParser(TyOrEx, &TInfo);
1986 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001987 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001988
Douglas Gregor0950e412009-03-13 21:01:28 +00001989 Expr *ArgEx = (Expr *)TyOrEx;
1990 Action::OwningExprResult Result
1991 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1992
1993 if (Result.isInvalid())
1994 DeleteExpr(ArgEx);
1995
1996 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001997}
1998
Chris Lattner709322b2009-02-17 08:12:06 +00001999QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002000 if (V->isTypeDependent())
2001 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Chris Lattnere267f5d2007-08-26 05:39:26 +00002003 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002004 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002005 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002006
Chris Lattnere267f5d2007-08-26 05:39:26 +00002007 // Otherwise they pass through real integer and floating point types here.
2008 if (V->getType()->isArithmeticType())
2009 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattnere267f5d2007-08-26 05:39:26 +00002011 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00002012 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2013 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002014 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002015}
2016
2017
Chris Lattnere168f762006-11-10 05:29:30 +00002018
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002019Action::OwningExprResult
2020Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2021 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00002022 UnaryOperator::Opcode Opc;
2023 switch (Kind) {
2024 default: assert(0 && "Unknown unary op!");
2025 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2026 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2027 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002028
Eli Friedmancfdd40c2009-11-18 03:38:04 +00002029 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00002030}
2031
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002032Action::OwningExprResult
2033Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2034 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002035 // Since this might be a postfix expression, get rid of ParenListExprs.
2036 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2037
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002038 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2039 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregor40412ac2008-11-19 17:17:41 +00002041 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002042 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2043 Base.release();
2044 Idx.release();
2045 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2046 Context.DependentTy, RLoc));
2047 }
2048
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002050 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002051 LHSExp->getType()->isEnumeralType() ||
2052 RHSExp->getType()->isRecordType() ||
2053 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002054 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002055 }
2056
Sebastian Redladba46e2009-10-29 20:17:01 +00002057 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2058}
2059
2060
2061Action::OwningExprResult
2062Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2063 ExprArg Idx, SourceLocation RLoc) {
2064 Expr *LHSExp = static_cast<Expr*>(Base.get());
2065 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2066
Chris Lattner36d572b2007-07-16 00:14:47 +00002067 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002068 if (!LHSExp->getType()->getAs<VectorType>())
2069 DefaultFunctionArrayLvalueConversion(LHSExp);
2070 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002071
Chris Lattner36d572b2007-07-16 00:14:47 +00002072 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002073
Steve Naroffc1aadb12007-03-28 21:49:40 +00002074 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002075 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002076 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002077 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002078 Expr *BaseExpr, *IndexExpr;
2079 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002080 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2081 BaseExpr = LHSExp;
2082 IndexExpr = RHSExp;
2083 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002085 BaseExpr = LHSExp;
2086 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002087 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002088 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002089 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002090 BaseExpr = RHSExp;
2091 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002092 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002093 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002094 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002095 BaseExpr = LHSExp;
2096 IndexExpr = RHSExp;
2097 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002098 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002099 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002100 // Handle the uncommon case of "123[Ptr]".
2101 BaseExpr = RHSExp;
2102 IndexExpr = LHSExp;
2103 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002104 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002105 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002106 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002107
Chris Lattner36d572b2007-07-16 00:14:47 +00002108 // FIXME: need to deal with const...
2109 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002110 } else if (LHSTy->isArrayType()) {
2111 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002112 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002113 // wasn't promoted because of the C90 rule that doesn't
2114 // allow promoting non-lvalue arrays. Warn, then
2115 // force the promotion here.
2116 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2117 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002118 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2119 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002120 LHSTy = LHSExp->getType();
2121
2122 BaseExpr = LHSExp;
2123 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002124 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002125 } else if (RHSTy->isArrayType()) {
2126 // Same as previous, except for 123[f().a] case
2127 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2128 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002129 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2130 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002131 RHSTy = RHSExp->getType();
2132
2133 BaseExpr = RHSExp;
2134 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002135 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002136 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002137 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2138 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002139 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002140 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002141 if (!(IndexExpr->getType()->isIntegerType() &&
2142 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002143 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2144 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002145
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002146 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002147 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2148 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002149 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2150
Douglas Gregorac1fb652009-03-24 19:52:54 +00002151 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002152 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2153 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002154 // incomplete types are not object types.
2155 if (ResultType->isFunctionType()) {
2156 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2157 << ResultType << BaseExpr->getSourceRange();
2158 return ExprError();
2159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregorac1fb652009-03-24 19:52:54 +00002161 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002162 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002163 PDiag(diag::err_subscript_incomplete_type)
2164 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002165 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattner62975a72009-04-24 00:30:45 +00002167 // Diagnose bad cases where we step over interface counts.
2168 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2169 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2170 << ResultType << BaseExpr->getSourceRange();
2171 return ExprError();
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002174 Base.release();
2175 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002176 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002177 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002178}
2179
Steve Narofff8fd09e2007-07-27 22:15:19 +00002180QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002181CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002182 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002183 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002184 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2185 // see FIXME there.
2186 //
2187 // FIXME: This logic can be greatly simplified by splitting it along
2188 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002189 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002190
Steve Narofff8fd09e2007-07-27 22:15:19 +00002191 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002192 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002193
Mike Stump4e1f26a2009-02-19 03:04:26 +00002194 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002195 // special names that indicate a subset of exactly half the elements are
2196 // to be selected.
2197 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002198
Nate Begemanbb70bf62009-01-18 01:47:54 +00002199 // This flag determines whether or not CompName has an 's' char prefix,
2200 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002201 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002202
2203 // Check that we've found one of the special components, or that the component
2204 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002205 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002206 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2207 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002208 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002209 do
2210 compStr++;
2211 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002212 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002213 do
2214 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002215 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002216 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002217
Mike Stump4e1f26a2009-02-19 03:04:26 +00002218 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002219 // We didn't get to the end of the string. This means the component names
2220 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002221 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2222 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002223 return QualType();
2224 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002225
Nate Begemanbb70bf62009-01-18 01:47:54 +00002226 // Ensure no component accessor exceeds the width of the vector type it
2227 // operates on.
2228 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002229 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002230
2231 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002232 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002233
2234 while (*compStr) {
2235 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2236 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2237 << baseType << SourceRange(CompLoc);
2238 return QualType();
2239 }
2240 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002241 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002242
Steve Narofff8fd09e2007-07-27 22:15:19 +00002243 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002244 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002245 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002246 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002247 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002248 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002249 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002250 if (HexSwizzle)
2251 CompSize--;
2252
Steve Narofff8fd09e2007-07-27 22:15:19 +00002253 if (CompSize == 1)
2254 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002255
Nate Begemance4d7fc2008-04-18 23:10:10 +00002256 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002257 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002258 // diagostics look bad. We want extended vector types to appear built-in.
2259 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2260 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2261 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002262 }
2263 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002264}
2265
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002266static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002267 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002268 const Selector &Sel,
2269 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002270
Anders Carlssonf571c112009-08-26 18:25:21 +00002271 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002272 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002273 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002274 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002275
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002276 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2277 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002278 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002279 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002280 return D;
2281 }
2282 return 0;
2283}
2284
Steve Narofffb4330f2009-06-17 22:40:22 +00002285static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002286 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002287 const Selector &Sel,
2288 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002289 // Check protocols on qualified interfaces.
2290 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002291 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002292 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002293 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002294 GDecl = PD;
2295 break;
2296 }
2297 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002298 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002299 GDecl = OMD;
2300 break;
2301 }
2302 }
2303 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002304 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002305 E = QIdTy->qual_end(); I != E; ++I) {
2306 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002307 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002308 if (GDecl)
2309 return GDecl;
2310 }
2311 }
2312 return GDecl;
2313}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002314
John McCall10eae182009-11-30 22:42:35 +00002315Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002316Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2317 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002318 const CXXScopeSpec &SS,
2319 NamedDecl *FirstQualifierInScope,
2320 DeclarationName Name, SourceLocation NameLoc,
2321 const TemplateArgumentListInfo *TemplateArgs) {
2322 Expr *BaseExpr = Base.takeAs<Expr>();
2323
2324 // Even in dependent contexts, try to diagnose base expressions with
2325 // obviously wrong types, e.g.:
2326 //
2327 // T* t;
2328 // t.f;
2329 //
2330 // In Obj-C++, however, the above expression is valid, since it could be
2331 // accessing the 'f' property if T is an Obj-C interface. The extra check
2332 // allows this, while still reporting an error if T is a struct pointer.
2333 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002334 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002335 if (PT && (!getLangOptions().ObjC1 ||
2336 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002337 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002338 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002339 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002340 return ExprError();
2341 }
2342 }
2343
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002344 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall10eae182009-11-30 22:42:35 +00002345
2346 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2347 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002348 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002349 IsArrow, OpLoc,
2350 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2351 SS.getRange(),
2352 FirstQualifierInScope,
2353 Name, NameLoc,
2354 TemplateArgs));
2355}
2356
2357/// We know that the given qualified member reference points only to
2358/// declarations which do not belong to the static type of the base
2359/// expression. Diagnose the problem.
2360static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2361 Expr *BaseExpr,
2362 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002363 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002364 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002365 // If this is an implicit member access, use a different set of
2366 // diagnostics.
2367 if (!BaseExpr)
2368 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002369
2370 // FIXME: this is an exceedingly lame diagnostic for some of the more
2371 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002372 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002373 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002374 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002375}
2376
2377// Check whether the declarations we found through a nested-name
2378// specifier in a member expression are actually members of the base
2379// type. The restriction here is:
2380//
2381// C++ [expr.ref]p2:
2382// ... In these cases, the id-expression shall name a
2383// member of the class or of one of its base classes.
2384//
2385// So it's perfectly legitimate for the nested-name specifier to name
2386// an unrelated class, and for us to find an overload set including
2387// decls from classes which are not superclasses, as long as the decl
2388// we actually pick through overload resolution is from a superclass.
2389bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2390 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002391 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002392 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002393 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2394 if (!BaseRT) {
2395 // We can't check this yet because the base type is still
2396 // dependent.
2397 assert(BaseType->isDependentType());
2398 return false;
2399 }
2400 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002401
2402 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002403 // If this is an implicit member reference and we find a
2404 // non-instance member, it's not an error.
2405 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2406 return false;
John McCall10eae182009-11-30 22:42:35 +00002407
John McCall2d74de92009-12-01 22:10:20 +00002408 // Note that we use the DC of the decl, not the underlying decl.
2409 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2410 while (RecordD->isAnonymousStructOrUnion())
2411 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2412
2413 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2414 MemberRecord.insert(RecordD->getCanonicalDecl());
2415
2416 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2417 return false;
2418 }
2419
John McCallcd4b4772009-12-02 03:53:29 +00002420 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002421 return true;
2422}
2423
2424static bool
2425LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2426 SourceRange BaseRange, const RecordType *RTy,
2427 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2428 RecordDecl *RDecl = RTy->getDecl();
2429 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2430 PDiag(diag::err_typecheck_incomplete_tag)
2431 << BaseRange))
2432 return true;
2433
2434 DeclContext *DC = RDecl;
2435 if (SS.isSet()) {
2436 // If the member name was a qualified-id, look into the
2437 // nested-name-specifier.
2438 DC = SemaRef.computeDeclContext(SS, false);
2439
John McCallcd4b4772009-12-02 03:53:29 +00002440 if (SemaRef.RequireCompleteDeclContext(SS)) {
2441 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2442 << SS.getRange() << DC;
2443 return true;
2444 }
2445
John McCall2d74de92009-12-01 22:10:20 +00002446 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2447
2448 if (!isa<TypeDecl>(DC)) {
2449 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2450 << DC << SS.getRange();
2451 return true;
John McCall10eae182009-11-30 22:42:35 +00002452 }
2453 }
2454
John McCall2d74de92009-12-01 22:10:20 +00002455 // The record definition is complete, now look up the member.
2456 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002457
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002458 if (!R.empty())
2459 return false;
2460
2461 // We didn't find anything with the given name, so try to correct
2462 // for typos.
2463 DeclarationName Name = R.getLookupName();
2464 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2465 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2466 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2467 << Name << DC << R.getLookupName() << SS.getRange()
2468 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2469 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002470 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2471 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2472 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002473 return false;
2474 } else {
2475 R.clear();
2476 }
2477
John McCall10eae182009-11-30 22:42:35 +00002478 return false;
2479}
2480
2481Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002482Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002483 SourceLocation OpLoc, bool IsArrow,
2484 const CXXScopeSpec &SS,
2485 NamedDecl *FirstQualifierInScope,
2486 DeclarationName Name, SourceLocation NameLoc,
2487 const TemplateArgumentListInfo *TemplateArgs) {
2488 Expr *Base = BaseArg.takeAs<Expr>();
2489
John McCallcd4b4772009-12-02 03:53:29 +00002490 if (BaseType->isDependentType() ||
2491 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002492 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002493 IsArrow, OpLoc,
2494 SS, FirstQualifierInScope,
2495 Name, NameLoc,
2496 TemplateArgs);
2497
2498 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002499
John McCall2d74de92009-12-01 22:10:20 +00002500 // Implicit member accesses.
2501 if (!Base) {
2502 QualType RecordTy = BaseType;
2503 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2504 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2505 RecordTy->getAs<RecordType>(),
2506 OpLoc, SS))
2507 return ExprError();
2508
2509 // Explicit member accesses.
2510 } else {
2511 OwningExprResult Result =
2512 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00002513 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCall2d74de92009-12-01 22:10:20 +00002514
2515 if (Result.isInvalid()) {
2516 Owned(Base);
2517 return ExprError();
2518 }
2519
2520 if (Result.get())
2521 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002522 }
2523
John McCall2d74de92009-12-01 22:10:20 +00002524 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCall38836f02010-01-15 08:34:02 +00002525 OpLoc, IsArrow, SS, FirstQualifierInScope,
2526 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002527}
2528
2529Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002530Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2531 SourceLocation OpLoc, bool IsArrow,
2532 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002533 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002534 LookupResult &R,
2535 const TemplateArgumentListInfo *TemplateArgs) {
2536 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002537 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002538 if (IsArrow) {
2539 assert(BaseType->isPointerType());
2540 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2541 }
2542
2543 NestedNameSpecifier *Qualifier =
2544 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2545 DeclarationName MemberName = R.getLookupName();
2546 SourceLocation MemberLoc = R.getNameLoc();
2547
2548 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002549 return ExprError();
2550
John McCall10eae182009-11-30 22:42:35 +00002551 if (R.empty()) {
2552 // Rederive where we looked up.
2553 DeclContext *DC = (SS.isSet()
2554 ? computeDeclContext(SS, false)
2555 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002556
John McCall10eae182009-11-30 22:42:35 +00002557 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002558 << MemberName << DC
2559 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002560 return ExprError();
2561 }
2562
John McCall38836f02010-01-15 08:34:02 +00002563 // Diagnose lookups that find only declarations from a non-base
2564 // type. This is possible for either qualified lookups (which may
2565 // have been qualified with an unrelated type) or implicit member
2566 // expressions (which were found with unqualified lookup and thus
2567 // may have come from an enclosing scope). Note that it's okay for
2568 // lookup to find declarations from a non-base type as long as those
2569 // aren't the ones picked by overload resolution.
2570 if ((SS.isSet() || !BaseExpr ||
2571 (isa<CXXThisExpr>(BaseExpr) &&
2572 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2573 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002574 return ExprError();
2575
2576 // Construct an unresolved result if we in fact got an unresolved
2577 // result.
2578 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002579 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002580 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002581 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00002582 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002583
John McCall58cc69d2010-01-27 01:50:18 +00002584 // Suppress any lookup-related diagnostics; we'll do these when we
2585 // pick a member.
2586 R.suppressDiagnostics();
2587
John McCall10eae182009-11-30 22:42:35 +00002588 UnresolvedMemberExpr *MemExpr
2589 = UnresolvedMemberExpr::Create(Context, Dependent,
2590 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002591 BaseExpr, BaseExprType,
2592 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002593 Qualifier, SS.getRange(),
2594 MemberName, MemberLoc,
2595 TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00002596 MemExpr->addDecls(R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002597
2598 return Owned(MemExpr);
2599 }
2600
2601 assert(R.isSingleResult());
2602 NamedDecl *MemberDecl = R.getFoundDecl();
2603
2604 // FIXME: diagnose the presence of template arguments now.
2605
2606 // If the decl being referenced had an error, return an error for this
2607 // sub-expr without emitting another error, in order to avoid cascading
2608 // error cases.
2609 if (MemberDecl->isInvalidDecl())
2610 return ExprError();
2611
John McCall2d74de92009-12-01 22:10:20 +00002612 // Handle the implicit-member-access case.
2613 if (!BaseExpr) {
2614 // If this is not an instance member, convert to a non-member access.
2615 if (!IsInstanceMember(MemberDecl))
2616 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2617
Douglas Gregorb15af892010-01-07 23:12:05 +00002618 SourceLocation Loc = R.getNameLoc();
2619 if (SS.getRange().isValid())
2620 Loc = SS.getRange().getBegin();
2621 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002622 }
2623
John McCall10eae182009-11-30 22:42:35 +00002624 bool ShouldCheckUse = true;
2625 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2626 // Don't diagnose the use of a virtual member function unless it's
2627 // explicitly qualified.
2628 if (MD->isVirtual() && !SS.isSet())
2629 ShouldCheckUse = false;
2630 }
2631
2632 // Check the use of this member.
2633 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2634 Owned(BaseExpr);
2635 return ExprError();
2636 }
2637
2638 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2639 // We may have found a field within an anonymous union or struct
2640 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002641 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2642 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002643 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2644 BaseExpr, OpLoc);
2645
2646 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2647 QualType MemberType = FD->getType();
2648 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2649 MemberType = Ref->getPointeeType();
2650 else {
2651 Qualifiers BaseQuals = BaseType.getQualifiers();
2652 BaseQuals.removeObjCGCAttr();
2653 if (FD->isMutable()) BaseQuals.removeConst();
2654
2655 Qualifiers MemberQuals
2656 = Context.getCanonicalType(MemberType).getQualifiers();
2657
2658 Qualifiers Combined = BaseQuals + MemberQuals;
2659 if (Combined != MemberQuals)
2660 MemberType = Context.getQualifiedType(MemberType, Combined);
2661 }
2662
2663 MarkDeclarationReferenced(MemberLoc, FD);
2664 if (PerformObjectMemberConversion(BaseExpr, FD))
2665 return ExprError();
2666 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2667 FD, MemberLoc, MemberType));
2668 }
2669
2670 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2671 MarkDeclarationReferenced(MemberLoc, Var);
2672 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2673 Var, MemberLoc,
2674 Var->getType().getNonReferenceType()));
2675 }
2676
2677 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2678 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2679 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2680 MemberFn, MemberLoc,
2681 MemberFn->getType()));
2682 }
2683
2684 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2685 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2686 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2687 Enum, MemberLoc, Enum->getType()));
2688 }
2689
2690 Owned(BaseExpr);
2691
2692 if (isa<TypeDecl>(MemberDecl))
2693 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2694 << MemberName << int(IsArrow));
2695
2696 // We found a declaration kind that we didn't expect. This is a
2697 // generic error message that tells the user that she can't refer
2698 // to this member with '.' or '->'.
2699 return ExprError(Diag(MemberLoc,
2700 diag::err_typecheck_member_reference_unknown)
2701 << MemberName << int(IsArrow));
2702}
2703
2704/// Look up the given member of the given non-type-dependent
2705/// expression. This can return in one of two ways:
2706/// * If it returns a sentinel null-but-valid result, the caller will
2707/// assume that lookup was performed and the results written into
2708/// the provided structure. It will take over from there.
2709/// * Otherwise, the returned expression will be produced in place of
2710/// an ordinary member expression.
2711///
2712/// The ObjCImpDecl bit is a gross hack that will need to be properly
2713/// fixed for ObjC++.
2714Sema::OwningExprResult
2715Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002716 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002717 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002718 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002719 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002720
Steve Naroffeaaae462007-12-16 21:42:28 +00002721 // Perform default conversions.
2722 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002723
Steve Naroff185616f2007-07-26 03:11:44 +00002724 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002725 assert(!BaseType->isDependentType());
2726
2727 DeclarationName MemberName = R.getLookupName();
2728 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002729
2730 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002731 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002732 // function. Suggest the addition of those parentheses, build the
2733 // call, and continue on.
2734 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2735 if (const FunctionProtoType *Fun
2736 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2737 QualType ResultTy = Fun->getResultType();
2738 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002739 ((!IsArrow && ResultTy->isRecordType()) ||
2740 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002741 ResultTy->getAs<PointerType>()->getPointeeType()
2742 ->isRecordType()))) {
2743 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2744 Diag(Loc, diag::err_member_reference_needs_call)
2745 << QualType(Fun, 0)
2746 << CodeModificationHint::CreateInsertion(Loc, "()");
2747
2748 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002749 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002750 MultiExprArg(*this, 0, 0), 0, Loc);
2751 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002752 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002753
2754 BaseExpr = NewBase.takeAs<Expr>();
2755 DefaultFunctionArrayConversion(BaseExpr);
2756 BaseType = BaseExpr->getType();
2757 }
2758 }
2759 }
2760
David Chisnall9f57c292009-08-17 16:35:33 +00002761 // If this is an Objective-C pseudo-builtin and a definition is provided then
2762 // use that.
2763 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002764 if (IsArrow) {
2765 // Handle the following exceptional case PObj->isa.
2766 if (const ObjCObjectPointerType *OPT =
2767 BaseType->getAs<ObjCObjectPointerType>()) {
2768 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2769 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002770 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2771 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002772 }
2773 }
David Chisnall9f57c292009-08-17 16:35:33 +00002774 // We have an 'id' type. Rather than fall through, we check if this
2775 // is a reference to 'isa'.
2776 if (BaseType != Context.ObjCIdRedefinitionType) {
2777 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002778 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002779 }
David Chisnall9f57c292009-08-17 16:35:33 +00002780 }
John McCall10eae182009-11-30 22:42:35 +00002781
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002782 // If this is an Objective-C pseudo-builtin and a definition is provided then
2783 // use that.
2784 if (Context.isObjCSelType(BaseType)) {
2785 // We have an 'SEL' type. Rather than fall through, we check if this
2786 // is a reference to 'sel_id'.
2787 if (BaseType != Context.ObjCSelRedefinitionType) {
2788 BaseType = Context.ObjCSelRedefinitionType;
2789 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2790 }
2791 }
John McCall10eae182009-11-30 22:42:35 +00002792
Steve Naroff185616f2007-07-26 03:11:44 +00002793 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002794
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002795 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002796 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002797 // Also must look for a getter name which uses property syntax.
2798 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2799 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2800 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2801 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2802 ObjCMethodDecl *Getter;
2803 // FIXME: need to also look locally in the implementation.
2804 if ((Getter = IFace->lookupClassMethod(Sel))) {
2805 // Check the use of this method.
2806 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2807 return ExprError();
2808 }
2809 // If we found a getter then this may be a valid dot-reference, we
2810 // will look for the matching setter, in case it is needed.
2811 Selector SetterSel =
2812 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2813 PP.getSelectorTable(), Member);
2814 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2815 if (!Setter) {
2816 // If this reference is in an @implementation, also check for 'private'
2817 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002818 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002819 }
2820 // Look through local category implementations associated with the class.
2821 if (!Setter)
2822 Setter = IFace->getCategoryClassMethod(SetterSel);
2823
2824 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2825 return ExprError();
2826
2827 if (Getter || Setter) {
2828 QualType PType;
2829
2830 if (Getter)
2831 PType = Getter->getResultType();
2832 else
2833 // Get the expression type from Setter's incoming parameter.
2834 PType = (*(Setter->param_end() -1))->getType();
2835 // FIXME: we must check that the setter has property type.
2836 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2837 PType,
2838 Setter, MemberLoc, BaseExpr));
2839 }
2840 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2841 << MemberName << BaseType);
2842 }
2843 }
2844
2845 if (BaseType->isObjCClassType() &&
2846 BaseType != Context.ObjCClassRedefinitionType) {
2847 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002848 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002849 }
Mike Stump11289f42009-09-09 15:08:12 +00002850
John McCall10eae182009-11-30 22:42:35 +00002851 if (IsArrow) {
2852 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002853 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002854 else if (BaseType->isObjCObjectPointerType())
2855 ;
John McCalla928c652009-12-07 22:46:59 +00002856 else if (BaseType->isRecordType()) {
2857 // Recover from arrow accesses to records, e.g.:
2858 // struct MyRecord foo;
2859 // foo->bar
2860 // This is actually well-formed in C++ if MyRecord has an
2861 // overloaded operator->, but that should have been dealt with
2862 // by now.
2863 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2864 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2865 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2866 IsArrow = false;
2867 } else {
John McCall10eae182009-11-30 22:42:35 +00002868 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2869 << BaseType << BaseExpr->getSourceRange();
2870 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002871 }
John McCalla928c652009-12-07 22:46:59 +00002872 } else {
2873 // Recover from dot accesses to pointers, e.g.:
2874 // type *foo;
2875 // foo.bar
2876 // This is actually well-formed in two cases:
2877 // - 'type' is an Objective C type
2878 // - 'bar' is a pseudo-destructor name which happens to refer to
2879 // the appropriate pointer type
2880 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2881 const PointerType *PT = BaseType->getAs<PointerType>();
2882 if (PT && PT->getPointeeType()->isRecordType()) {
2883 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2884 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2885 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2886 BaseType = PT->getPointeeType();
2887 IsArrow = true;
2888 }
2889 }
John McCall10eae182009-11-30 22:42:35 +00002890 }
John McCalla928c652009-12-07 22:46:59 +00002891
John McCall10eae182009-11-30 22:42:35 +00002892 // Handle field access to simple records. This also handles access
2893 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002894 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002895 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2896 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002897 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002898 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002899 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002900
Chris Lattnerdc420f42008-07-21 04:59:05 +00002901 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2902 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002903 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2904 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002905 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002906 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002907 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002908 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002909 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2910
Steve Naroffa057ba92009-07-16 00:25:06 +00002911 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2912 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002913 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002914
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002915 if (!IV) {
2916 // Attempt to correct for typos in ivar names.
2917 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2918 LookupMemberName);
2919 if (CorrectTypo(Res, 0, 0, IDecl) &&
2920 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2921 Diag(R.getNameLoc(),
2922 diag::err_typecheck_member_reference_ivar_suggest)
2923 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2924 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2925 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002926 Diag(IV->getLocation(), diag::note_previous_decl)
2927 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002928 }
2929 }
2930
Steve Naroffa057ba92009-07-16 00:25:06 +00002931 if (IV) {
2932 // If the decl being referenced had an error, return an error for this
2933 // sub-expr without emitting another error, in order to avoid cascading
2934 // error cases.
2935 if (IV->isInvalidDecl())
2936 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002937
Steve Naroffa057ba92009-07-16 00:25:06 +00002938 // Check whether we can reference this field.
2939 if (DiagnoseUseOfDecl(IV, MemberLoc))
2940 return ExprError();
2941 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2942 IV->getAccessControl() != ObjCIvarDecl::Package) {
2943 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2944 if (ObjCMethodDecl *MD = getCurMethodDecl())
2945 ClassOfMethodDecl = MD->getClassInterface();
2946 else if (ObjCImpDecl && getCurFunctionDecl()) {
2947 // Case of a c-function declared inside an objc implementation.
2948 // FIXME: For a c-style function nested inside an objc implementation
2949 // class, there is no implementation context available, so we pass
2950 // down the context as argument to this routine. Ideally, this context
2951 // need be passed down in the AST node and somehow calculated from the
2952 // AST for a function decl.
2953 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002954 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002955 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2956 ClassOfMethodDecl = IMPD->getClassInterface();
2957 else if (ObjCCategoryImplDecl* CatImplClass =
2958 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2959 ClassOfMethodDecl = CatImplClass->getClassInterface();
2960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961
2962 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2963 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002964 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002965 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002966 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002967 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2968 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002969 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002970 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002971 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002972
2973 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2974 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002975 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002976 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002977 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002978 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002979 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002980 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002981 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002982 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002983 if (!IsArrow && (BaseType->isObjCIdType() ||
2984 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002985 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002986 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002987
Steve Naroff7cae42b2009-07-10 23:34:53 +00002988 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002989 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002990 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2991 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2992 // Check the use of this declaration
2993 if (DiagnoseUseOfDecl(PD, MemberLoc))
2994 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002995
Steve Naroff7cae42b2009-07-10 23:34:53 +00002996 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2997 MemberLoc, BaseExpr));
2998 }
2999 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3000 // Check the use of this method.
3001 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3002 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003003
Ted Kremenek2c809302010-02-11 22:41:21 +00003004 return Owned(new (Context) ObjCMessageExpr(Context, BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00003005 OMD->getResultType(),
3006 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003007 NULL, 0));
3008 }
3009 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010
Steve Naroff7cae42b2009-07-10 23:34:53 +00003011 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003012 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003013 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00003014 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3015 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003016 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00003017 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003018 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3019 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00003020 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003021
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003022 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00003023 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003024 // Check whether we can reference this property.
3025 if (DiagnoseUseOfDecl(PD, MemberLoc))
3026 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003027 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00003028 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003029 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003030 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3031 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003032 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003033 MemberLoc, BaseExpr));
3034 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003035 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003036 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3037 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003038 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003039 // Check whether we can reference this property.
3040 if (DiagnoseUseOfDecl(PD, MemberLoc))
3041 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003042
Steve Narofff6009ed2009-01-21 00:14:39 +00003043 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003044 MemberLoc, BaseExpr));
3045 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003046 // If that failed, look for an "implicit" property by seeing if the nullary
3047 // selector is implemented.
3048
3049 // FIXME: The logic for looking up nullary and unary selectors should be
3050 // shared with the code in ActOnInstanceMessage.
3051
Anders Carlssonf571c112009-08-26 18:25:21 +00003052 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003053 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003054
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003055 // If this reference is in an @implementation, check for 'private' methods.
3056 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003057 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003058
Steve Naroff1df62692008-10-22 19:16:27 +00003059 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003060 if (!Getter)
3061 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003062 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003063 // Check if we can reference this property.
3064 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3065 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003066 }
3067 // If we found a getter then this may be a valid dot-reference, we
3068 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00003069 Selector SetterSel =
3070 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003071 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003073 if (!Setter) {
3074 // If this reference is in an @implementation, also check for 'private'
3075 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003076 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003077 }
3078 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003079 if (!Setter)
3080 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003081
Steve Naroff1d984fe2009-03-11 13:48:17 +00003082 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3083 return ExprError();
3084
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003085 if (Getter) {
Steve Naroff1d984fe2009-03-11 13:48:17 +00003086 QualType PType;
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003087 PType = Getter->getResultType();
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003088 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003089 Setter, MemberLoc, BaseExpr));
3090 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003091
3092 // Attempt to correct for typos in property names.
3093 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3094 LookupOrdinaryName);
3095 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3096 Res.getAsSingle<ObjCPropertyDecl>()) {
3097 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3098 << MemberName << BaseType << Res.getLookupName()
3099 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3100 Res.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003101 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3102 Diag(Property->getLocation(), diag::note_previous_decl)
3103 << Property->getDeclName();
3104
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003105 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCall38836f02010-01-15 08:34:02 +00003106 ObjCImpDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003107 }
Fariborz Jahanianc5d61df2010-02-19 18:30:30 +00003108 Diag(MemberLoc, diag::err_property_not_found)
3109 << MemberName << BaseType;
3110 if (Setter && !Getter)
3111 Diag(Setter->getLocation(), diag::note_getter_unavailable)
3112 << MemberName << BaseExpr->getSourceRange();
3113 return ExprError();
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003114 }
Mike Stump11289f42009-09-09 15:08:12 +00003115
Steve Naroffe87026a2009-07-24 17:54:45 +00003116 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003117 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003118 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003119 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003120 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003121 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003122
Chris Lattnerb63a7452008-07-21 04:28:12 +00003123 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003124 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003125 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003126 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3127 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003128 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003129 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003130 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003131 }
Fariborz Jahanianc5d61df2010-02-19 18:30:30 +00003132
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003133 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3134 << BaseType << BaseExpr->getSourceRange();
3135
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003136 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003137}
3138
John McCall10eae182009-11-30 22:42:35 +00003139/// The main callback when the parser finds something like
3140/// expression . [nested-name-specifier] identifier
3141/// expression -> [nested-name-specifier] identifier
3142/// where 'identifier' encompasses a fairly broad spectrum of
3143/// possibilities, including destructor and operator references.
3144///
3145/// \param OpKind either tok::arrow or tok::period
3146/// \param HasTrailingLParen whether the next token is '(', which
3147/// is used to diagnose mis-uses of special members that can
3148/// only be called
3149/// \param ObjCImpDecl the current ObjC @implementation decl;
3150/// this is an ugly hack around the fact that ObjC @implementations
3151/// aren't properly put in the context chain
3152Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3153 SourceLocation OpLoc,
3154 tok::TokenKind OpKind,
3155 const CXXScopeSpec &SS,
3156 UnqualifiedId &Id,
3157 DeclPtrTy ObjCImpDecl,
3158 bool HasTrailingLParen) {
3159 if (SS.isSet() && SS.isInvalid())
3160 return ExprError();
3161
3162 TemplateArgumentListInfo TemplateArgsBuffer;
3163
3164 // Decompose the name into its component parts.
3165 DeclarationName Name;
3166 SourceLocation NameLoc;
3167 const TemplateArgumentListInfo *TemplateArgs;
3168 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3169 Name, NameLoc, TemplateArgs);
3170
3171 bool IsArrow = (OpKind == tok::arrow);
3172
3173 NamedDecl *FirstQualifierInScope
3174 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3175 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3176
3177 // This is a postfix expression, so get rid of ParenListExprs.
3178 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3179
3180 Expr *Base = BaseArg.takeAs<Expr>();
3181 OwningExprResult Result(*this);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003182 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCall2d74de92009-12-01 22:10:20 +00003183 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003184 IsArrow, OpLoc,
3185 SS, FirstQualifierInScope,
3186 Name, NameLoc,
3187 TemplateArgs);
3188 } else {
3189 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3190 if (TemplateArgs) {
3191 // Re-use the lookup done for the template name.
3192 DecomposeTemplateName(R, Id);
3193 } else {
3194 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00003195 SS, ObjCImpDecl);
John McCall10eae182009-11-30 22:42:35 +00003196
3197 if (Result.isInvalid()) {
3198 Owned(Base);
3199 return ExprError();
3200 }
3201
3202 if (Result.get()) {
3203 // The only way a reference to a destructor can be used is to
3204 // immediately call it, which falls into this case. If the
3205 // next token is not a '(', produce a diagnostic and build the
3206 // call now.
3207 if (!HasTrailingLParen &&
3208 Id.getKind() == UnqualifiedId::IK_DestructorName)
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003209 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall10eae182009-11-30 22:42:35 +00003210
3211 return move(Result);
3212 }
3213 }
3214
John McCall2d74de92009-12-01 22:10:20 +00003215 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003216 OpLoc, IsArrow, SS, FirstQualifierInScope,
3217 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003218 }
3219
3220 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003221}
3222
Anders Carlsson355933d2009-08-25 03:49:14 +00003223Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3224 FunctionDecl *FD,
3225 ParmVarDecl *Param) {
3226 if (Param->hasUnparsedDefaultArg()) {
3227 Diag (CallLoc,
3228 diag::err_use_of_default_argument_to_function_declared_later) <<
3229 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003230 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003231 diag::note_default_argument_declared_here);
3232 } else {
3233 if (Param->hasUninstantiatedDefaultArg()) {
3234 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3235
3236 // Instantiate the expression.
Douglas Gregor8c702532010-02-05 07:33:43 +00003237 MultiLevelTemplateArgumentList ArgList
3238 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003239
Mike Stump11289f42009-09-09 15:08:12 +00003240 InstantiatingTemplate Inst(*this, CallLoc, Param,
3241 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003242 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003243
John McCall76d824f2009-08-25 22:02:44 +00003244 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003245 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003246 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003247
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003248 // Check the expression as an initializer for the parameter.
3249 InitializedEntity Entity
3250 = InitializedEntity::InitializeParameter(Param);
3251 InitializationKind Kind
3252 = InitializationKind::CreateCopy(Param->getLocation(),
3253 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3254 Expr *ResultE = Result.takeAs<Expr>();
3255
3256 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3257 Result = InitSeq.Perform(*this, Entity, Kind,
3258 MultiExprArg(*this, (void**)&ResultE, 1));
3259 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003260 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003261
3262 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003263 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003264 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003265 }
Mike Stump11289f42009-09-09 15:08:12 +00003266
Anders Carlsson355933d2009-08-25 03:49:14 +00003267 // If the default expression creates temporaries, we need to
3268 // push them to the current stack of expression temporaries so they'll
3269 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003270 // FIXME: We should really be rebuilding the default argument with new
3271 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003272 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3273 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003274 }
3275
3276 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003277 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003278}
3279
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003280/// ConvertArgumentsForCall - Converts the arguments specified in
3281/// Args/NumArgs to the parameter types of the function FDecl with
3282/// function prototype Proto. Call is the call expression itself, and
3283/// Fn is the function expression. For a C++ member function, this
3284/// routine does not attempt to convert the object argument. Returns
3285/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003286bool
3287Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003288 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003289 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003290 Expr **Args, unsigned NumArgs,
3291 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003292 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003293 // assignment, to the types of the corresponding parameter, ...
3294 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003295 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003296
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003297 // If too few arguments are available (and we don't have default
3298 // arguments for the remaining parameters), don't make the call.
3299 if (NumArgs < NumArgsInProto) {
3300 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3301 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3302 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003303 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003304 }
3305
3306 // If too many are passed and not variadic, error on the extras and drop
3307 // them.
3308 if (NumArgs > NumArgsInProto) {
3309 if (!Proto->isVariadic()) {
3310 Diag(Args[NumArgsInProto]->getLocStart(),
3311 diag::err_typecheck_call_too_many_args)
3312 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3313 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3314 Args[NumArgs-1]->getLocEnd());
3315 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003316 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003317 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003318 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003319 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003320 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003321 VariadicCallType CallType =
3322 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3323 if (Fn->getType()->isBlockPointerType())
3324 CallType = VariadicBlock; // Block
3325 else if (isa<MemberExpr>(Fn))
3326 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003327 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003328 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003329 if (Invalid)
3330 return true;
3331 unsigned TotalNumArgs = AllArgs.size();
3332 for (unsigned i = 0; i < TotalNumArgs; ++i)
3333 Call->setArg(i, AllArgs[i]);
3334
3335 return false;
3336}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003337
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003338bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3339 FunctionDecl *FDecl,
3340 const FunctionProtoType *Proto,
3341 unsigned FirstProtoArg,
3342 Expr **Args, unsigned NumArgs,
3343 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003344 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003345 unsigned NumArgsInProto = Proto->getNumArgs();
3346 unsigned NumArgsToCheck = NumArgs;
3347 bool Invalid = false;
3348 if (NumArgs != NumArgsInProto)
3349 // Use default arguments for missing arguments
3350 NumArgsToCheck = NumArgsInProto;
3351 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003352 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003353 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003354 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003355
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003356 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357 if (ArgIx < NumArgs) {
3358 Arg = Args[ArgIx++];
3359
Eli Friedman3164fb12009-03-22 22:00:50 +00003360 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3361 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003362 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003363 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003364 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003365
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003366 // Pass the argument
3367 ParmVarDecl *Param = 0;
3368 if (FDecl && i < FDecl->getNumParams())
3369 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003370
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003371
3372 InitializedEntity Entity =
3373 Param? InitializedEntity::InitializeParameter(Param)
3374 : InitializedEntity::InitializeParameter(ProtoArgType);
3375 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3376 SourceLocation(),
3377 Owned(Arg));
3378 if (ArgE.isInvalid())
3379 return true;
3380
3381 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003382 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003383 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003384
Mike Stump11289f42009-09-09 15:08:12 +00003385 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003386 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003387 if (ArgExpr.isInvalid())
3388 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003389
Anders Carlsson355933d2009-08-25 03:49:14 +00003390 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003391 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003392 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003393 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003394
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003395 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003396 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003397 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003398 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003399 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003400 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003401 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003402 }
3403 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003404 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405}
3406
Steve Naroff83895f72007-09-16 03:34:24 +00003407/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003408/// This provides the location of the left/right parens and a list of comma
3409/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003410Action::OwningExprResult
3411Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3412 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003413 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003414 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003415
3416 // Since this might be a postfix expression, get rid of ParenListExprs.
3417 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003418
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003419 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003420 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003421 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003422
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003423 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003424 // If this is a pseudo-destructor expression, build the call immediately.
3425 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3426 if (NumArgs > 0) {
3427 // Pseudo-destructor calls should not have any arguments.
3428 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3429 << CodeModificationHint::CreateRemoval(
3430 SourceRange(Args[0]->getLocStart(),
3431 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregorad8a3362009-09-04 17:36:40 +00003433 for (unsigned I = 0; I != NumArgs; ++I)
3434 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregorad8a3362009-09-04 17:36:40 +00003436 NumArgs = 0;
3437 }
Mike Stump11289f42009-09-09 15:08:12 +00003438
Douglas Gregorad8a3362009-09-04 17:36:40 +00003439 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3440 RParenLoc));
3441 }
Mike Stump11289f42009-09-09 15:08:12 +00003442
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003443 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003444 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003445 // FIXME: Will need to cache the results of name lookup (including ADL) in
3446 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003447 bool Dependent = false;
3448 if (Fn->isTypeDependent())
3449 Dependent = true;
3450 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3451 Dependent = true;
3452
3453 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003454 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003455 Context.DependentTy, RParenLoc));
3456
3457 // Determine whether this is a call to an object (C++ [over.call.object]).
3458 if (Fn->getType()->isRecordType())
3459 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3460 CommaLocs, RParenLoc));
3461
John McCall10eae182009-11-30 22:42:35 +00003462 Expr *NakedFn = Fn->IgnoreParens();
3463
3464 // Determine whether this is a call to an unresolved member function.
3465 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3466 // If lookup was unresolved but not dependent (i.e. didn't find
3467 // an unresolved using declaration), it has to be an overloaded
3468 // function set, which means it must contain either multiple
3469 // declarations (all methods or method templates) or a single
3470 // method template.
3471 assert((MemE->getNumDecls() > 1) ||
3472 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003473 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003474
John McCall2d74de92009-12-01 22:10:20 +00003475 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3476 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003477 }
3478
Douglas Gregore254f902009-02-04 00:32:51 +00003479 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003480 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003481 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003482 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003483 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3484 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003485 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003486
3487 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003489 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3490 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003491 if (const FunctionProtoType *FPT =
3492 dyn_cast<FunctionProtoType>(BO->getType())) {
3493 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003494
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003495 ExprOwningPtr<CXXMemberCallExpr>
3496 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3497 NumArgs, ResultTy,
3498 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003499
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003500 if (CheckCallReturnType(FPT->getResultType(),
3501 BO->getRHS()->getSourceRange().getBegin(),
3502 TheCall.get(), 0))
3503 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003504
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003505 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3506 RParenLoc))
3507 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003508
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003509 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3510 }
3511 return ExprError(Diag(Fn->getLocStart(),
3512 diag::err_typecheck_call_not_function)
3513 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003514 }
3515 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003516 }
3517
Douglas Gregore254f902009-02-04 00:32:51 +00003518 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003519 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003520 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003521
Eli Friedmane14b1992009-12-26 03:35:45 +00003522 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003523 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3524 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3525 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3526 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003527 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003528
John McCall57500772009-12-16 12:17:52 +00003529 NamedDecl *NDecl = 0;
3530 if (isa<DeclRefExpr>(NakedFn))
3531 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3532
John McCall2d74de92009-12-01 22:10:20 +00003533 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3534}
3535
John McCall57500772009-12-16 12:17:52 +00003536/// BuildResolvedCallExpr - Build a call to a resolved expression,
3537/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003538/// unary-convert to an expression of function-pointer or
3539/// block-pointer type.
3540///
3541/// \param NDecl the declaration being called, if available
3542Sema::OwningExprResult
3543Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3544 SourceLocation LParenLoc,
3545 Expr **Args, unsigned NumArgs,
3546 SourceLocation RParenLoc) {
3547 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3548
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003549 // Promote the function operand.
3550 UsualUnaryConversions(Fn);
3551
Chris Lattner08464942007-12-28 05:29:59 +00003552 // Make the call expr early, before semantic checks. This guarantees cleanup
3553 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003554 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3555 Args, NumArgs,
3556 Context.BoolTy,
3557 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003558
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003559 const FunctionType *FuncT;
3560 if (!Fn->getType()->isBlockPointerType()) {
3561 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3562 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003563 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003564 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003565 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3566 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003567 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003568 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003569 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003570 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003571 }
Chris Lattner08464942007-12-28 05:29:59 +00003572 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003573 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3574 << Fn->getType() << Fn->getSourceRange());
3575
Eli Friedman3164fb12009-03-22 22:00:50 +00003576 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003577 if (CheckCallReturnType(FuncT->getResultType(),
3578 Fn->getSourceRange().getBegin(), TheCall.get(),
3579 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003580 return ExprError();
3581
Chris Lattner08464942007-12-28 05:29:59 +00003582 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003583 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003584
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003585 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003586 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003587 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003588 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003589 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003590 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003591
Douglas Gregord8e97de2009-04-02 15:37:10 +00003592 if (FDecl) {
3593 // Check if we have too few/too many template arguments, based
3594 // on our knowledge of the function definition.
3595 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003596 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003597 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003598 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003599 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3600 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3601 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3602 }
3603 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003604 }
3605
Steve Naroff0b661582007-08-28 23:30:39 +00003606 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003607 for (unsigned i = 0; i != NumArgs; i++) {
3608 Expr *Arg = Args[i];
3609 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003610 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3611 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003612 PDiag(diag::err_call_incomplete_argument)
3613 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003614 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003615 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003616 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003617 }
Chris Lattner08464942007-12-28 05:29:59 +00003618
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003619 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3620 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003621 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3622 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003623
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003624 // Check for sentinels
3625 if (NDecl)
3626 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003627
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003628 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003629 if (FDecl) {
3630 if (CheckFunctionCall(FDecl, TheCall.get()))
3631 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregor15fc9562009-09-12 00:22:50 +00003633 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003634 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3635 } else if (NDecl) {
3636 if (CheckBlockCall(NDecl, TheCall.get()))
3637 return ExprError();
3638 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003639
Anders Carlssonf8984012009-08-16 03:06:32 +00003640 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003641}
3642
Sebastian Redlb5d49352009-01-19 22:31:54 +00003643Action::OwningExprResult
3644Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3645 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003646 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003647 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003648 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003649
3650 TypeSourceInfo *TInfo;
3651 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3652 if (!TInfo)
3653 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3654
3655 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3656}
3657
3658Action::OwningExprResult
3659Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3660 SourceLocation RParenLoc, ExprArg InitExpr) {
3661 QualType literalType = TInfo->getType();
Sebastian Redlb5d49352009-01-19 22:31:54 +00003662 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003663
Eli Friedman37a186d2008-05-20 05:22:08 +00003664 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003665 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003666 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3667 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003668 } else if (!literalType->isDependentType() &&
3669 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003670 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003671 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003672 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003673 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003674
Douglas Gregor85dabae2009-12-16 01:38:02 +00003675 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003676 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003677 InitializationKind Kind
3678 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3679 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003680 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3681 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3682 MultiExprArg(*this, (void**)&literalExpr, 1),
3683 &literalType);
3684 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003685 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003686 InitExpr.release();
3687 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003688
Chris Lattner79413952008-12-04 23:50:19 +00003689 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003690 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003691 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003692 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003693 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003694
3695 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003696
John McCall5d7aa7f2010-01-19 22:33:45 +00003697 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003698 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003699}
3700
Sebastian Redlb5d49352009-01-19 22:31:54 +00003701Action::OwningExprResult
3702Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003703 SourceLocation RBraceLoc) {
3704 unsigned NumInit = initlist.size();
3705 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003706
Steve Naroff30d242c2007-09-15 18:49:24 +00003707 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003708 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003709
Ted Kremenek013041e2010-02-19 01:50:18 +00003710 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3711 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003712 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003713 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003714}
3715
Anders Carlsson094c4592009-10-18 18:12:03 +00003716static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3717 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003718 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003719 return CastExpr::CK_NoOp;
3720
3721 if (SrcTy->hasPointerRepresentation()) {
3722 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003723 return DestTy->isObjCObjectPointerType() ?
3724 CastExpr::CK_AnyPointerToObjCPointerCast :
3725 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003726 if (DestTy->isIntegerType())
3727 return CastExpr::CK_PointerToIntegral;
3728 }
3729
3730 if (SrcTy->isIntegerType()) {
3731 if (DestTy->isIntegerType())
3732 return CastExpr::CK_IntegralCast;
3733 if (DestTy->hasPointerRepresentation())
3734 return CastExpr::CK_IntegralToPointer;
3735 if (DestTy->isRealFloatingType())
3736 return CastExpr::CK_IntegralToFloating;
3737 }
3738
3739 if (SrcTy->isRealFloatingType()) {
3740 if (DestTy->isRealFloatingType())
3741 return CastExpr::CK_FloatingCast;
3742 if (DestTy->isIntegerType())
3743 return CastExpr::CK_FloatingToIntegral;
3744 }
3745
3746 // FIXME: Assert here.
3747 // assert(false && "Unhandled cast combination!");
3748 return CastExpr::CK_Unknown;
3749}
3750
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003751/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003752bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003753 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003754 CXXMethodDecl *& ConversionDecl,
3755 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003756 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003757 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3758 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003759
Douglas Gregorb92a1562010-02-03 00:27:59 +00003760 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003761
3762 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3763 // type needs to be scalar.
3764 if (castType->isVoidType()) {
3765 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003766 Kind = CastExpr::CK_ToVoid;
3767 return false;
3768 }
3769
3770 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003771 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003772 (castType->isStructureType() || castType->isUnionType())) {
3773 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003774 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003775 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3776 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003777 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003778 return false;
3779 }
3780
3781 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003782 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003783 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003784 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003785 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003786 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003787 if (Context.hasSameUnqualifiedType(Field->getType(),
3788 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003789 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3790 << castExpr->getSourceRange();
3791 break;
3792 }
3793 }
3794 if (Field == FieldEnd)
3795 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3796 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003797 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003798 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003799 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003800
3801 // Reject any other conversions to non-scalar types.
3802 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3803 << castType << castExpr->getSourceRange();
3804 }
3805
3806 if (!castExpr->getType()->isScalarType() &&
3807 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003808 return Diag(castExpr->getLocStart(),
3809 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003810 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003811 }
3812
Anders Carlsson43d70f82009-10-16 05:23:41 +00003813 if (castType->isExtVectorType())
3814 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3815
Anders Carlsson525b76b2009-10-16 02:48:28 +00003816 if (castType->isVectorType())
3817 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3818 if (castExpr->getType()->isVectorType())
3819 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3820
3821 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003822 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003823
Anders Carlsson43d70f82009-10-16 05:23:41 +00003824 if (isa<ObjCSelectorExpr>(castExpr))
3825 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3826
Anders Carlsson525b76b2009-10-16 02:48:28 +00003827 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003828 QualType castExprType = castExpr->getType();
3829 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3830 return Diag(castExpr->getLocStart(),
3831 diag::err_cast_pointer_from_non_pointer_int)
3832 << castExprType << castExpr->getSourceRange();
3833 } else if (!castExpr->getType()->isArithmeticType()) {
3834 if (!castType->isIntegralType() && castType->isArithmeticType())
3835 return Diag(castExpr->getLocStart(),
3836 diag::err_cast_pointer_to_non_pointer_int)
3837 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003838 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003839
3840 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003841 return false;
3842}
3843
Anders Carlsson525b76b2009-10-16 02:48:28 +00003844bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3845 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003846 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003847
Anders Carlssonde71adf2007-11-27 05:51:55 +00003848 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003849 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003850 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003851 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003852 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003853 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003854 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003855 } else
3856 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003857 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003858 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003859
Anders Carlsson525b76b2009-10-16 02:48:28 +00003860 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003861 return false;
3862}
3863
Anders Carlsson43d70f82009-10-16 05:23:41 +00003864bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3865 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003866 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003867
3868 QualType SrcTy = CastExpr->getType();
3869
Nate Begemanc8961a42009-06-27 22:05:55 +00003870 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3871 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003872 if (SrcTy->isVectorType()) {
3873 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3874 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3875 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003876 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003877 return false;
3878 }
3879
Nate Begemanbd956c42009-06-28 02:36:38 +00003880 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003881 // conversion will take place first from scalar to elt type, and then
3882 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003883 if (SrcTy->isPointerType())
3884 return Diag(R.getBegin(),
3885 diag::err_invalid_conversion_between_vector_and_scalar)
3886 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003887
3888 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3889 ImpCastExprToType(CastExpr, DestElemTy,
3890 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003891
3892 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003893 return false;
3894}
3895
Sebastian Redlb5d49352009-01-19 22:31:54 +00003896Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003897Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003898 SourceLocation RParenLoc, ExprArg Op) {
3899 assert((Ty != 0) && (Op.get() != 0) &&
3900 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003901
John McCall97513962010-01-15 18:39:57 +00003902 TypeSourceInfo *castTInfo;
3903 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3904 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00003905 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00003906
Nate Begeman5ec4b312009-08-10 23:49:36 +00003907 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallebe54742010-01-15 18:56:44 +00003908 Expr *castExpr = (Expr *)Op.get();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003909 if (isa<ParenListExpr>(castExpr))
John McCalle15bbff2010-01-18 19:35:47 +00003910 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3911 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00003912
3913 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3914}
3915
3916Action::OwningExprResult
3917Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3918 SourceLocation RParenLoc, ExprArg Op) {
3919 Expr *castExpr = static_cast<Expr*>(Op.get());
3920
Anders Carlssone9766d52009-09-09 21:33:21 +00003921 CXXMethodDecl *Method = 0;
John McCallebe54742010-01-15 18:56:44 +00003922 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3923 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003924 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003925 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003926
3927 if (Method) {
John McCallebe54742010-01-15 18:56:44 +00003928 // FIXME: preserve type source info here
3929 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3930 Kind, Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003931
Anders Carlssone9766d52009-09-09 21:33:21 +00003932 if (CastArg.isInvalid())
3933 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003934
Anders Carlssone9766d52009-09-09 21:33:21 +00003935 castExpr = CastArg.takeAs<Expr>();
3936 } else {
3937 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003938 }
Mike Stump11289f42009-09-09 15:08:12 +00003939
John McCallebe54742010-01-15 18:56:44 +00003940 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3941 Kind, castExpr, Ty,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003942 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003943}
3944
Nate Begeman5ec4b312009-08-10 23:49:36 +00003945/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3946/// of comma binary operators.
3947Action::OwningExprResult
3948Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3949 Expr *expr = EA.takeAs<Expr>();
3950 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3951 if (!E)
3952 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003953
Nate Begeman5ec4b312009-08-10 23:49:36 +00003954 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003955
Nate Begeman5ec4b312009-08-10 23:49:36 +00003956 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3957 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3958 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003959
Nate Begeman5ec4b312009-08-10 23:49:36 +00003960 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3961}
3962
3963Action::OwningExprResult
3964Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3965 SourceLocation RParenLoc, ExprArg Op,
John McCalle15bbff2010-01-18 19:35:47 +00003966 TypeSourceInfo *TInfo) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003967 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCalle15bbff2010-01-18 19:35:47 +00003968 QualType Ty = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003969
3970 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003971 // then handle it as such.
3972 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3973 if (PE->getNumExprs() == 0) {
3974 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3975 return ExprError();
3976 }
3977
3978 llvm::SmallVector<Expr *, 8> initExprs;
3979 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3980 initExprs.push_back(PE->getExpr(i));
3981
3982 // FIXME: This means that pretty-printing the final AST will produce curly
3983 // braces instead of the original commas.
3984 Op.release();
Ted Kremenek013041e2010-02-19 01:50:18 +00003985 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003986 initExprs.size(), RParenLoc);
3987 E->setType(Ty);
John McCalle15bbff2010-01-18 19:35:47 +00003988 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman5ec4b312009-08-10 23:49:36 +00003989 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003990 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003991 // sequence of BinOp comma operators.
3992 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCalle15bbff2010-01-18 19:35:47 +00003993 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman5ec4b312009-08-10 23:49:36 +00003994 }
3995}
3996
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003997Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003998 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003999 MultiExprArg Val,
4000 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004001 unsigned nexprs = Val.size();
4002 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004003 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4004 Expr *expr;
4005 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4006 expr = new (Context) ParenExpr(L, R, exprs[0]);
4007 else
4008 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004009 return Owned(expr);
4010}
4011
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004012/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4013/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004014/// C99 6.5.15
4015QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4016 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004017 // C++ is sufficiently different to merit its own checker.
4018 if (getLangOptions().CPlusPlus)
4019 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4020
John McCall1fa36b72009-11-05 09:23:39 +00004021 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4022
Chris Lattner432cff52009-02-18 04:28:32 +00004023 UsualUnaryConversions(Cond);
4024 UsualUnaryConversions(LHS);
4025 UsualUnaryConversions(RHS);
4026 QualType CondTy = Cond->getType();
4027 QualType LHSTy = LHS->getType();
4028 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004029
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004030 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004031 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4032 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4033 << CondTy;
4034 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004035 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004036
Chris Lattnere2949f42008-01-06 22:42:25 +00004037 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004038 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4039 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004040
Chris Lattnere2949f42008-01-06 22:42:25 +00004041 // If both operands have arithmetic type, do the usual arithmetic conversions
4042 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004043 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4044 UsualArithmeticConversions(LHS, RHS);
4045 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004046 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004047
Chris Lattnere2949f42008-01-06 22:42:25 +00004048 // If both operands are the same structure or union type, the result is that
4049 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004050 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4051 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004052 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004053 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004054 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004055 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004056 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004057 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004058
Chris Lattnere2949f42008-01-06 22:42:25 +00004059 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004060 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004061 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4062 if (!LHSTy->isVoidType())
4063 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4064 << RHS->getSourceRange();
4065 if (!RHSTy->isVoidType())
4066 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4067 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004068 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4069 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004070 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004071 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004072 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4073 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004074 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004075 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004076 // promote the null to a pointer.
4077 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004078 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004079 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004080 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004081 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004082 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004083 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004084 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004085
4086 // All objective-c pointer type analysis is done here.
4087 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4088 QuestionLoc);
4089 if (!compositeType.isNull())
4090 return compositeType;
4091
4092
Steve Naroff05efa972009-07-01 14:36:47 +00004093 // Handle block pointer types.
4094 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4095 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4096 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4097 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004098 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4099 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004100 return destType;
4101 }
4102 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004103 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004104 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004105 }
Steve Naroff05efa972009-07-01 14:36:47 +00004106 // We have 2 block pointer types.
4107 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4108 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004109 return LHSTy;
4110 }
Steve Naroff05efa972009-07-01 14:36:47 +00004111 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004112 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4113 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004114
Steve Naroff05efa972009-07-01 14:36:47 +00004115 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4116 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004117 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004118 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004119 // In this situation, we assume void* type. No especially good
4120 // reason, but this is what gcc does, and we do have to pick
4121 // to get a consistent AST.
4122 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004123 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4124 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004125 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004126 }
Steve Naroff05efa972009-07-01 14:36:47 +00004127 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004128 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4129 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004130 return LHSTy;
4131 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004132
Steve Naroff05efa972009-07-01 14:36:47 +00004133 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4134 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4135 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004136 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4137 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004138
4139 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4140 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4141 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004142 QualType destPointee
4143 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004144 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004145 // Add qualifiers if necessary.
4146 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4147 // Promote to void*.
4148 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004149 return destType;
4150 }
4151 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004152 QualType destPointee
4153 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004154 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004155 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004156 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004157 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004158 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004159 return destType;
4160 }
4161
4162 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4163 // Two identical pointer types are always compatible.
4164 return LHSTy;
4165 }
4166 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4167 rhptee.getUnqualifiedType())) {
4168 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4169 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4170 // In this situation, we assume void* type. No especially good
4171 // reason, but this is what gcc does, and we do have to pick
4172 // to get a consistent AST.
4173 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004174 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4175 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004176 return incompatTy;
4177 }
4178 // The pointer types are compatible.
4179 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4180 // differently qualified versions of compatible types, the result type is
4181 // a pointer to an appropriately qualified version of the *composite*
4182 // type.
4183 // FIXME: Need to calculate the composite type.
4184 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004185 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4186 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004187 return LHSTy;
4188 }
Mike Stump11289f42009-09-09 15:08:12 +00004189
Steve Naroff05efa972009-07-01 14:36:47 +00004190 // GCC compatibility: soften pointer/integer mismatch.
4191 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4192 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4193 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004194 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004195 return RHSTy;
4196 }
4197 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4198 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4199 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004200 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004201 return LHSTy;
4202 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004203
Chris Lattnere2949f42008-01-06 22:42:25 +00004204 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004205 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4206 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004207 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004208}
4209
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004210/// FindCompositeObjCPointerType - Helper method to find composite type of
4211/// two objective-c pointer types of the two input expressions.
4212QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4213 SourceLocation QuestionLoc) {
4214 QualType LHSTy = LHS->getType();
4215 QualType RHSTy = RHS->getType();
4216
4217 // Handle things like Class and struct objc_class*. Here we case the result
4218 // to the pseudo-builtin, because that will be implicitly cast back to the
4219 // redefinition type if an attempt is made to access its fields.
4220 if (LHSTy->isObjCClassType() &&
4221 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4222 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4223 return LHSTy;
4224 }
4225 if (RHSTy->isObjCClassType() &&
4226 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4227 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4228 return RHSTy;
4229 }
4230 // And the same for struct objc_object* / id
4231 if (LHSTy->isObjCIdType() &&
4232 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4233 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4234 return LHSTy;
4235 }
4236 if (RHSTy->isObjCIdType() &&
4237 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4238 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4239 return RHSTy;
4240 }
4241 // And the same for struct objc_selector* / SEL
4242 if (Context.isObjCSelType(LHSTy) &&
4243 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4244 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4245 return LHSTy;
4246 }
4247 if (Context.isObjCSelType(RHSTy) &&
4248 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4249 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4250 return RHSTy;
4251 }
4252 // Check constraints for Objective-C object pointers types.
4253 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4254
4255 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4256 // Two identical object pointer types are always compatible.
4257 return LHSTy;
4258 }
4259 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4260 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4261 QualType compositeType = LHSTy;
4262
4263 // If both operands are interfaces and either operand can be
4264 // assigned to the other, use that type as the composite
4265 // type. This allows
4266 // xxx ? (A*) a : (B*) b
4267 // where B is a subclass of A.
4268 //
4269 // Additionally, as for assignment, if either type is 'id'
4270 // allow silent coercion. Finally, if the types are
4271 // incompatible then make sure to use 'id' as the composite
4272 // type so the result is acceptable for sending messages to.
4273
4274 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4275 // It could return the composite type.
4276 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4277 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4278 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4279 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4280 } else if ((LHSTy->isObjCQualifiedIdType() ||
4281 RHSTy->isObjCQualifiedIdType()) &&
4282 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4283 // Need to handle "id<xx>" explicitly.
4284 // GCC allows qualified id and any Objective-C type to devolve to
4285 // id. Currently localizing to here until clear this should be
4286 // part of ObjCQualifiedIdTypesAreCompatible.
4287 compositeType = Context.getObjCIdType();
4288 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4289 compositeType = Context.getObjCIdType();
4290 } else if (!(compositeType =
4291 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4292 ;
4293 else {
4294 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4295 << LHSTy << RHSTy
4296 << LHS->getSourceRange() << RHS->getSourceRange();
4297 QualType incompatTy = Context.getObjCIdType();
4298 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4299 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4300 return incompatTy;
4301 }
4302 // The object pointer types are compatible.
4303 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4304 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4305 return compositeType;
4306 }
4307 // Check Objective-C object pointer types and 'void *'
4308 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4309 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4310 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4311 QualType destPointee
4312 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4313 QualType destType = Context.getPointerType(destPointee);
4314 // Add qualifiers if necessary.
4315 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4316 // Promote to void*.
4317 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4318 return destType;
4319 }
4320 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4321 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4322 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4323 QualType destPointee
4324 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4325 QualType destType = Context.getPointerType(destPointee);
4326 // Add qualifiers if necessary.
4327 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4328 // Promote to void*.
4329 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4330 return destType;
4331 }
4332 return QualType();
4333}
4334
Steve Naroff83895f72007-09-16 03:34:24 +00004335/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004336/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004337Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4338 SourceLocation ColonLoc,
4339 ExprArg Cond, ExprArg LHS,
4340 ExprArg RHS) {
4341 Expr *CondExpr = (Expr *) Cond.get();
4342 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004343
4344 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4345 // was the condition.
4346 bool isLHSNull = LHSExpr == 0;
4347 if (isLHSNull)
4348 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004349
4350 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004351 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004352 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004353 return ExprError();
4354
4355 Cond.release();
4356 LHS.release();
4357 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004358 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004359 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004360 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004361}
4362
Steve Naroff3f597292007-05-11 22:18:03 +00004363// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004364// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004365// routine is it effectively iqnores the qualifiers on the top level pointee.
4366// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4367// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004368Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004369Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004370 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004371
David Chisnall9f57c292009-08-17 16:35:33 +00004372 if ((lhsType->isObjCClassType() &&
4373 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4374 (rhsType->isObjCClassType() &&
4375 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4376 return Compatible;
4377 }
4378
Steve Naroff1f4d7272007-05-11 04:00:31 +00004379 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004380 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4381 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004382
Steve Naroff1f4d7272007-05-11 04:00:31 +00004383 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004384 lhptee = Context.getCanonicalType(lhptee);
4385 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004386
Chris Lattner9bad62c2008-01-04 18:04:52 +00004387 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004388
4389 // C99 6.5.16.1p1: This following citation is common to constraints
4390 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4391 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004392 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004393 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004394 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004395
Mike Stump4e1f26a2009-02-19 03:04:26 +00004396 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4397 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004398 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004399 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004400 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004401 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004402
Chris Lattner0a788432008-01-03 22:56:36 +00004403 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004404 assert(rhptee->isFunctionType());
4405 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004406 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004407
Chris Lattner0a788432008-01-03 22:56:36 +00004408 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004409 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004410 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004411
4412 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004413 assert(lhptee->isFunctionType());
4414 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004415 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004416 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004417 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004418 lhptee = lhptee.getUnqualifiedType();
4419 rhptee = rhptee.getUnqualifiedType();
4420 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4421 // Check if the pointee types are compatible ignoring the sign.
4422 // We explicitly check for char so that we catch "char" vs
4423 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004424 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004425 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004426 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004427 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004428
4429 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004430 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004431 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004432 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004433
Eli Friedman80160bd2009-03-22 23:59:44 +00004434 if (lhptee == rhptee) {
4435 // Types are compatible ignoring the sign. Qualifier incompatibility
4436 // takes priority over sign incompatibility because the sign
4437 // warning can be disabled.
4438 if (ConvTy != Compatible)
4439 return ConvTy;
4440 return IncompatiblePointerSign;
4441 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004442
4443 // If we are a multi-level pointer, it's possible that our issue is simply
4444 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4445 // the eventual target type is the same and the pointers have the same
4446 // level of indirection, this must be the issue.
4447 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4448 do {
4449 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4450 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4451
4452 lhptee = Context.getCanonicalType(lhptee);
4453 rhptee = Context.getCanonicalType(rhptee);
4454 } while (lhptee->isPointerType() && rhptee->isPointerType());
4455
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004456 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004457 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004458 }
4459
Eli Friedman80160bd2009-03-22 23:59:44 +00004460 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004461 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004462 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004463 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004464}
4465
Steve Naroff081c7422008-09-04 15:10:53 +00004466/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4467/// block pointer types are compatible or whether a block and normal pointer
4468/// are compatible. It is more restrict than comparing two function pointer
4469// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004470Sema::AssignConvertType
4471Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004472 QualType rhsType) {
4473 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004474
Steve Naroff081c7422008-09-04 15:10:53 +00004475 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004476 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4477 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004478
Steve Naroff081c7422008-09-04 15:10:53 +00004479 // make sure we operate on the canonical type
4480 lhptee = Context.getCanonicalType(lhptee);
4481 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004482
Steve Naroff081c7422008-09-04 15:10:53 +00004483 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004484
Steve Naroff081c7422008-09-04 15:10:53 +00004485 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004486 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004487 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004488
Eli Friedmana6638ca2009-06-08 05:08:54 +00004489 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004490 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004491 return ConvTy;
4492}
4493
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004494/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4495/// for assignment compatibility.
4496Sema::AssignConvertType
4497Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4498 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4499 return Compatible;
4500 QualType lhptee =
4501 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4502 QualType rhptee =
4503 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4504 // make sure we operate on the canonical type
4505 lhptee = Context.getCanonicalType(lhptee);
4506 rhptee = Context.getCanonicalType(rhptee);
4507 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4508 return CompatiblePointerDiscardsQualifiers;
4509
4510 if (Context.typesAreCompatible(lhsType, rhsType))
4511 return Compatible;
4512 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4513 return IncompatibleObjCQualifiedId;
4514 return IncompatiblePointer;
4515}
4516
Mike Stump4e1f26a2009-02-19 03:04:26 +00004517/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4518/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004519/// pointers. Here are some objectionable examples that GCC considers warnings:
4520///
4521/// int a, *pint;
4522/// short *pshort;
4523/// struct foo *pfoo;
4524///
4525/// pint = pshort; // warning: assignment from incompatible pointer type
4526/// a = pint; // warning: assignment makes integer from pointer without a cast
4527/// pint = a; // warning: assignment makes pointer from integer without a cast
4528/// pint = pfoo; // warning: assignment from incompatible pointer type
4529///
4530/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004531/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004532///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004533Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004534Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004535 // Get canonical types. We're not formatting these types, just comparing
4536 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004537 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4538 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004539
4540 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004541 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004542
David Chisnall9f57c292009-08-17 16:35:33 +00004543 if ((lhsType->isObjCClassType() &&
4544 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4545 (rhsType->isObjCClassType() &&
4546 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4547 return Compatible;
4548 }
4549
Douglas Gregor6b754842008-10-28 00:22:11 +00004550 // If the left-hand side is a reference type, then we are in a
4551 // (rare!) case where we've allowed the use of references in C,
4552 // e.g., as a parameter type in a built-in function. In this case,
4553 // just make sure that the type referenced is compatible with the
4554 // right-hand side type. The caller is responsible for adjusting
4555 // lhsType so that the resulting expression does not have reference
4556 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004557 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004558 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004559 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004560 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004561 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004562 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4563 // to the same ExtVector type.
4564 if (lhsType->isExtVectorType()) {
4565 if (rhsType->isExtVectorType())
4566 return lhsType == rhsType ? Compatible : Incompatible;
4567 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4568 return Compatible;
4569 }
Mike Stump11289f42009-09-09 15:08:12 +00004570
Nate Begeman191a6b12008-07-14 18:02:46 +00004571 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004572 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004573 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004574 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004575 if (getLangOptions().LaxVectorConversions &&
4576 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004577 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004578 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004579 }
4580 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004581 }
Eli Friedman3360d892008-05-30 18:07:22 +00004582
Chris Lattner881a2122008-01-04 23:32:24 +00004583 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004584 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004585
Chris Lattnerec646832008-04-07 06:49:41 +00004586 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004587 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004588 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004589
Chris Lattnerec646832008-04-07 06:49:41 +00004590 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004591 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004592
Steve Naroffaccc4882009-07-20 17:56:53 +00004593 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004594 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004595 if (lhsType->isVoidPointerType()) // an exception to the rule.
4596 return Compatible;
4597 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004598 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004599 if (rhsType->getAs<BlockPointerType>()) {
4600 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004601 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004602
4603 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004604 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004605 return Compatible;
4606 }
Steve Naroff081c7422008-09-04 15:10:53 +00004607 return Incompatible;
4608 }
4609
4610 if (isa<BlockPointerType>(lhsType)) {
4611 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004612 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004613
Steve Naroff32d072c2008-09-29 18:10:17 +00004614 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004615 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004616 return Compatible;
4617
Steve Naroff081c7422008-09-04 15:10:53 +00004618 if (rhsType->isBlockPointerType())
4619 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004620
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004621 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004622 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004623 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004624 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004625 return Incompatible;
4626 }
4627
Steve Naroff7cae42b2009-07-10 23:34:53 +00004628 if (isa<ObjCObjectPointerType>(lhsType)) {
4629 if (rhsType->isIntegerType())
4630 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004631
Steve Naroffaccc4882009-07-20 17:56:53 +00004632 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004633 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004634 if (rhsType->isVoidPointerType()) // an exception to the rule.
4635 return Compatible;
4636 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004637 }
4638 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004639 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004640 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004641 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004642 if (RHSPT->getPointeeType()->isVoidType())
4643 return Compatible;
4644 }
4645 // Treat block pointers as objects.
4646 if (rhsType->isBlockPointerType())
4647 return Compatible;
4648 return Incompatible;
4649 }
Chris Lattnerec646832008-04-07 06:49:41 +00004650 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004651 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004652 if (lhsType == Context.BoolTy)
4653 return Compatible;
4654
4655 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004656 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004657
Mike Stump4e1f26a2009-02-19 03:04:26 +00004658 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004659 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004660
4661 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004662 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004663 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004664 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004665 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004666 if (isa<ObjCObjectPointerType>(rhsType)) {
4667 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4668 if (lhsType == Context.BoolTy)
4669 return Compatible;
4670
4671 if (lhsType->isIntegerType())
4672 return PointerToInt;
4673
Steve Naroffaccc4882009-07-20 17:56:53 +00004674 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004675 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004676 if (lhsType->isVoidPointerType()) // an exception to the rule.
4677 return Compatible;
4678 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004679 }
4680 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004681 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004682 return Compatible;
4683 return Incompatible;
4684 }
Eli Friedman3360d892008-05-30 18:07:22 +00004685
Chris Lattnera52c2f22008-01-04 23:18:45 +00004686 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004687 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004688 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004689 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004690 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004691}
4692
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004693/// \brief Constructs a transparent union from an expression that is
4694/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004695static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004696 QualType UnionType, FieldDecl *Field) {
4697 // Build an initializer list that designates the appropriate member
4698 // of the transparent union.
Ted Kremenek013041e2010-02-19 01:50:18 +00004699 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4700 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004701 SourceLocation());
4702 Initializer->setType(UnionType);
4703 Initializer->setInitializedFieldInUnion(Field);
4704
4705 // Build a compound literal constructing a value of the transparent
4706 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004707 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004708 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004709 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004710}
4711
4712Sema::AssignConvertType
4713Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4714 QualType FromType = rExpr->getType();
4715
Mike Stump11289f42009-09-09 15:08:12 +00004716 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004717 // transparent_union GCC extension.
4718 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004719 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004720 return Incompatible;
4721
4722 // The field to initialize within the transparent union.
4723 RecordDecl *UD = UT->getDecl();
4724 FieldDecl *InitField = 0;
4725 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004726 for (RecordDecl::field_iterator it = UD->field_begin(),
4727 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004728 it != itend; ++it) {
4729 if (it->getType()->isPointerType()) {
4730 // If the transparent union contains a pointer type, we allow:
4731 // 1) void pointer
4732 // 2) null pointer constant
4733 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004734 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004735 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004736 InitField = *it;
4737 break;
4738 }
Mike Stump11289f42009-09-09 15:08:12 +00004739
Douglas Gregor56751b52009-09-25 04:25:58 +00004740 if (rExpr->isNullPointerConstant(Context,
4741 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004742 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004743 InitField = *it;
4744 break;
4745 }
4746 }
4747
4748 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4749 == Compatible) {
4750 InitField = *it;
4751 break;
4752 }
4753 }
4754
4755 if (!InitField)
4756 return Incompatible;
4757
4758 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4759 return Compatible;
4760}
4761
Chris Lattner9bad62c2008-01-04 18:04:52 +00004762Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004763Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004764 if (getLangOptions().CPlusPlus) {
4765 if (!lhsType->isRecordType()) {
4766 // C++ 5.17p3: If the left operand is not of class type, the
4767 // expression is implicitly converted (C++ 4) to the
4768 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004769 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004770 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004771 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004772 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004773 }
4774
4775 // FIXME: Currently, we fall through and treat C++ classes like C
4776 // structures.
4777 }
4778
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004779 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4780 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004781 if ((lhsType->isPointerType() ||
4782 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004783 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004784 && rExpr->isNullPointerConstant(Context,
4785 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004786 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004787 return Compatible;
4788 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004789
Chris Lattnere6dcd502007-10-16 02:55:40 +00004790 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004791 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004792 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004793 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004794 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004795 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004796 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00004797 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004798
Chris Lattner9bad62c2008-01-04 18:04:52 +00004799 Sema::AssignConvertType result =
4800 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004801
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004802 // C99 6.5.16.1p2: The value of the right operand is converted to the
4803 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004804 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4805 // so that we can use references in built-in functions even in C.
4806 // The getNonReferenceType() call makes sure that the resulting expression
4807 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004808 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004809 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4810 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004811 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004812}
4813
Chris Lattner326f7572008-11-18 01:30:42 +00004814QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004815 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004816 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004817 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004818 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004819}
4820
Chris Lattnerfaa54172010-01-12 21:23:57 +00004821QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004822 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004823 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004824 QualType lhsType =
4825 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4826 QualType rhsType =
4827 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004828
Nate Begeman191a6b12008-07-14 18:02:46 +00004829 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004830 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004831 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004832
Nate Begeman191a6b12008-07-14 18:02:46 +00004833 // Handle the case of a vector & extvector type of the same size and element
4834 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004835 if (getLangOptions().LaxVectorConversions) {
4836 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004837 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4838 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004839 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004840 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004841 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004842 }
4843 }
4844 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004845
Nate Begemanbd956c42009-06-28 02:36:38 +00004846 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4847 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4848 bool swapped = false;
4849 if (rhsType->isExtVectorType()) {
4850 swapped = true;
4851 std::swap(rex, lex);
4852 std::swap(rhsType, lhsType);
4853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
Nate Begeman886448d2009-06-28 19:12:57 +00004855 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004856 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004857 QualType EltTy = LV->getElementType();
4858 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4859 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004860 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004861 if (swapped) std::swap(rex, lex);
4862 return lhsType;
4863 }
4864 }
4865 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4866 rhsType->isRealFloatingType()) {
4867 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004868 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004869 if (swapped) std::swap(rex, lex);
4870 return lhsType;
4871 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004872 }
4873 }
Mike Stump11289f42009-09-09 15:08:12 +00004874
Nate Begeman886448d2009-06-28 19:12:57 +00004875 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004876 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004877 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004878 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004879 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004880}
4881
Chris Lattnerfaa54172010-01-12 21:23:57 +00004882QualType Sema::CheckMultiplyDivideOperands(
4883 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004884 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004885 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004886
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004887 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004888
Chris Lattnerfaa54172010-01-12 21:23:57 +00004889 if (!lex->getType()->isArithmeticType() ||
4890 !rex->getType()->isArithmeticType())
4891 return InvalidOperands(Loc, lex, rex);
4892
4893 // Check for division by zero.
4894 if (isDiv &&
4895 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004896 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4897 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004898
4899 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004900}
4901
Chris Lattnerfaa54172010-01-12 21:23:57 +00004902QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004903 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004904 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4905 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4906 return CheckVectorOperands(Loc, lex, rex);
4907 return InvalidOperands(Loc, lex, rex);
4908 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004909
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004910 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004911
Chris Lattnerfaa54172010-01-12 21:23:57 +00004912 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4913 return InvalidOperands(Loc, lex, rex);
4914
4915 // Check for remainder by zero.
4916 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004917 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4918 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004919
4920 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004921}
4922
Chris Lattnerfaa54172010-01-12 21:23:57 +00004923QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004924 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4926 QualType compType = CheckVectorOperands(Loc, lex, rex);
4927 if (CompLHSTy) *CompLHSTy = compType;
4928 return compType;
4929 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004930
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004931 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004932
Steve Naroffe4718892007-04-27 18:30:00 +00004933 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004934 if (lex->getType()->isArithmeticType() &&
4935 rex->getType()->isArithmeticType()) {
4936 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004937 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004938 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004939
Eli Friedman8e122982008-05-18 18:08:51 +00004940 // Put any potential pointer into PExp
4941 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004942 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004943 std::swap(PExp, IExp);
4944
Steve Naroff6b712a72009-07-14 18:25:06 +00004945 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004946
Eli Friedman8e122982008-05-18 18:08:51 +00004947 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004948 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004949
Chris Lattner12bdebb2009-04-24 23:50:08 +00004950 // Check for arithmetic on pointers to incomplete types.
4951 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004952 if (getLangOptions().CPlusPlus) {
4953 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004954 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004955 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004956 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004957
4958 // GNU extension: arithmetic on pointer to void
4959 Diag(Loc, diag::ext_gnu_void_ptr)
4960 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004961 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004962 if (getLangOptions().CPlusPlus) {
4963 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4964 << lex->getType() << lex->getSourceRange();
4965 return QualType();
4966 }
4967
4968 // GNU extension: arithmetic on pointer to function
4969 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4970 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004971 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004972 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004973 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004974 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004975 PExp->getType()->isObjCObjectPointerType()) &&
4976 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004977 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4978 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004979 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004980 return QualType();
4981 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004982 // Diagnose bad cases where we step over interface counts.
4983 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4984 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4985 << PointeeTy << PExp->getSourceRange();
4986 return QualType();
4987 }
Mike Stump11289f42009-09-09 15:08:12 +00004988
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004989 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004990 QualType LHSTy = Context.isPromotableBitField(lex);
4991 if (LHSTy.isNull()) {
4992 LHSTy = lex->getType();
4993 if (LHSTy->isPromotableIntegerType())
4994 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004995 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004996 *CompLHSTy = LHSTy;
4997 }
Eli Friedman8e122982008-05-18 18:08:51 +00004998 return PExp->getType();
4999 }
5000 }
5001
Chris Lattner326f7572008-11-18 01:30:42 +00005002 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005003}
5004
Chris Lattner2a3569b2008-04-07 05:30:13 +00005005// C99 6.5.6
5006QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005007 SourceLocation Loc, QualType* CompLHSTy) {
5008 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5009 QualType compType = CheckVectorOperands(Loc, lex, rex);
5010 if (CompLHSTy) *CompLHSTy = compType;
5011 return compType;
5012 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005013
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005014 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005015
Chris Lattner4d62f422007-12-09 21:53:25 +00005016 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005017
Chris Lattner4d62f422007-12-09 21:53:25 +00005018 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005019 if (lex->getType()->isArithmeticType()
5020 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005021 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005022 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005023 }
Mike Stump11289f42009-09-09 15:08:12 +00005024
Chris Lattner4d62f422007-12-09 21:53:25 +00005025 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005026 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005027 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005028
Douglas Gregorac1fb652009-03-24 19:52:54 +00005029 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005030
Douglas Gregorac1fb652009-03-24 19:52:54 +00005031 bool ComplainAboutVoid = false;
5032 Expr *ComplainAboutFunc = 0;
5033 if (lpointee->isVoidType()) {
5034 if (getLangOptions().CPlusPlus) {
5035 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5036 << lex->getSourceRange() << rex->getSourceRange();
5037 return QualType();
5038 }
5039
5040 // GNU C extension: arithmetic on pointer to void
5041 ComplainAboutVoid = true;
5042 } else if (lpointee->isFunctionType()) {
5043 if (getLangOptions().CPlusPlus) {
5044 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005045 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005046 return QualType();
5047 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005048
5049 // GNU C extension: arithmetic on pointer to function
5050 ComplainAboutFunc = lex;
5051 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005052 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005053 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005054 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005055 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005056 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005057
Chris Lattner12bdebb2009-04-24 23:50:08 +00005058 // Diagnose bad cases where we step over interface counts.
5059 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5060 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5061 << lpointee << lex->getSourceRange();
5062 return QualType();
5063 }
Mike Stump11289f42009-09-09 15:08:12 +00005064
Chris Lattner4d62f422007-12-09 21:53:25 +00005065 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005066 if (rex->getType()->isIntegerType()) {
5067 if (ComplainAboutVoid)
5068 Diag(Loc, diag::ext_gnu_void_ptr)
5069 << lex->getSourceRange() << rex->getSourceRange();
5070 if (ComplainAboutFunc)
5071 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005072 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005073 << ComplainAboutFunc->getSourceRange();
5074
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005075 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005076 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005077 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005078
Chris Lattner4d62f422007-12-09 21:53:25 +00005079 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005080 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005081 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005082
Douglas Gregorac1fb652009-03-24 19:52:54 +00005083 // RHS must be a completely-type object type.
5084 // Handle the GNU void* extension.
5085 if (rpointee->isVoidType()) {
5086 if (getLangOptions().CPlusPlus) {
5087 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5088 << lex->getSourceRange() << rex->getSourceRange();
5089 return QualType();
5090 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005091
Douglas Gregorac1fb652009-03-24 19:52:54 +00005092 ComplainAboutVoid = true;
5093 } else if (rpointee->isFunctionType()) {
5094 if (getLangOptions().CPlusPlus) {
5095 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005096 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005097 return QualType();
5098 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005099
5100 // GNU extension: arithmetic on pointer to function
5101 if (!ComplainAboutFunc)
5102 ComplainAboutFunc = rex;
5103 } else if (!rpointee->isDependentType() &&
5104 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005105 PDiag(diag::err_typecheck_sub_ptr_object)
5106 << rex->getSourceRange()
5107 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005108 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005109
Eli Friedman168fe152009-05-16 13:54:38 +00005110 if (getLangOptions().CPlusPlus) {
5111 // Pointee types must be the same: C++ [expr.add]
5112 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5113 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5114 << lex->getType() << rex->getType()
5115 << lex->getSourceRange() << rex->getSourceRange();
5116 return QualType();
5117 }
5118 } else {
5119 // Pointee types must be compatible C99 6.5.6p3
5120 if (!Context.typesAreCompatible(
5121 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5122 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5123 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5124 << lex->getType() << rex->getType()
5125 << lex->getSourceRange() << rex->getSourceRange();
5126 return QualType();
5127 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005128 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005129
Douglas Gregorac1fb652009-03-24 19:52:54 +00005130 if (ComplainAboutVoid)
5131 Diag(Loc, diag::ext_gnu_void_ptr)
5132 << lex->getSourceRange() << rex->getSourceRange();
5133 if (ComplainAboutFunc)
5134 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005135 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005136 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005137
5138 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005139 return Context.getPointerDiffType();
5140 }
5141 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005142
Chris Lattner326f7572008-11-18 01:30:42 +00005143 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005144}
5145
Chris Lattner2a3569b2008-04-07 05:30:13 +00005146// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005147QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005148 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005149 // C99 6.5.7p2: Each of the operands shall have integer type.
5150 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005151 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
Nate Begemane46ee9a2009-10-25 02:26:48 +00005153 // Vector shifts promote their scalar inputs to vector type.
5154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5155 return CheckVectorOperands(Loc, lex, rex);
5156
Chris Lattner5c11c412007-12-12 05:47:28 +00005157 // Shifts don't perform usual arithmetic conversions, they just do integer
5158 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005159 QualType LHSTy = Context.isPromotableBitField(lex);
5160 if (LHSTy.isNull()) {
5161 LHSTy = lex->getType();
5162 if (LHSTy->isPromotableIntegerType())
5163 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005164 }
Chris Lattner3c133402007-12-13 07:28:16 +00005165 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005166 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005167
Chris Lattner5c11c412007-12-12 05:47:28 +00005168 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005169
Ryan Flynnf53fab82009-08-07 16:20:20 +00005170 // Sanity-check shift operands
5171 llvm::APSInt Right;
5172 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005173 if (!rex->isValueDependent() &&
5174 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005175 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005176 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5177 else {
5178 llvm::APInt LeftBits(Right.getBitWidth(),
5179 Context.getTypeSize(lex->getType()));
5180 if (Right.uge(LeftBits))
5181 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5182 }
5183 }
5184
Chris Lattner5c11c412007-12-12 05:47:28 +00005185 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005186 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005187}
5188
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005189// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005190QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005191 unsigned OpaqueOpc, bool isRelational) {
5192 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5193
Chris Lattner9a152e22009-12-05 05:40:13 +00005194 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005195 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005196 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005197
John McCall99ce6bf2009-11-06 08:49:08 +00005198 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5199 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005200
Chris Lattnerb620c342007-08-26 01:18:55 +00005201 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005202 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5203 UsualArithmeticConversions(lex, rex);
5204 else {
5205 UsualUnaryConversions(lex);
5206 UsualUnaryConversions(rex);
5207 }
Steve Naroff31090012007-07-16 21:54:35 +00005208 QualType lType = lex->getType();
5209 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005210
Mike Stumpf70bcf72009-05-07 18:43:07 +00005211 if (!lType->isFloatingType()
5212 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005213 // For non-floating point types, check for self-comparisons of the form
5214 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5215 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005216 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005217 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005218 Expr *LHSStripped = lex->IgnoreParens();
5219 Expr *RHSStripped = rex->IgnoreParens();
5220 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5221 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005222 if (DRL->getDecl() == DRR->getDecl() &&
5223 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregor49862b82010-01-12 23:18:54 +00005224 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump11289f42009-09-09 15:08:12 +00005225
Chris Lattner222b8bd2009-03-08 19:39:53 +00005226 if (isa<CastExpr>(LHSStripped))
5227 LHSStripped = LHSStripped->IgnoreParenCasts();
5228 if (isa<CastExpr>(RHSStripped))
5229 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005230
Chris Lattner222b8bd2009-03-08 19:39:53 +00005231 // Warn about comparisons against a string constant (unless the other
5232 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005233 Expr *literalString = 0;
5234 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005235 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005236 !RHSStripped->isNullPointerConstant(Context,
5237 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005238 literalString = lex;
5239 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005240 } else if ((isa<StringLiteral>(RHSStripped) ||
5241 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005242 !LHSStripped->isNullPointerConstant(Context,
5243 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005244 literalString = rex;
5245 literalStringStripped = RHSStripped;
5246 }
5247
5248 if (literalString) {
5249 std::string resultComparison;
5250 switch (Opc) {
5251 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5252 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5253 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5254 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5255 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5256 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5257 default: assert(false && "Invalid comparison operator");
5258 }
Douglas Gregor49862b82010-01-12 23:18:54 +00005259
5260 DiagRuntimeBehavior(Loc,
5261 PDiag(diag::warn_stringcompare)
5262 << isa<ObjCEncodeExpr>(literalStringStripped)
5263 << literalString->getSourceRange()
5264 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5265 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5266 "strcmp(")
5267 << CodeModificationHint::CreateInsertion(
5268 PP.getLocForEndOfToken(rex->getLocEnd()),
5269 resultComparison));
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005270 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005271 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005272
Douglas Gregorca63811b2008-11-19 03:25:36 +00005273 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005274 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005275
Chris Lattnerb620c342007-08-26 01:18:55 +00005276 if (isRelational) {
5277 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005278 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005279 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005280 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005281 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005282 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005283
Chris Lattnerb620c342007-08-26 01:18:55 +00005284 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005285 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005286 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005287
Douglas Gregor56751b52009-09-25 04:25:58 +00005288 bool LHSIsNull = lex->isNullPointerConstant(Context,
5289 Expr::NPC_ValueDependentIsNull);
5290 bool RHSIsNull = rex->isNullPointerConstant(Context,
5291 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005292
Chris Lattnerb620c342007-08-26 01:18:55 +00005293 // All of the following pointer related warnings are GCC extensions, except
5294 // when handling null pointer constants. One day, we can consider making them
5295 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005296 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005297 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005298 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005299 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005300 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005301
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005302 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005303 if (LCanPointeeTy == RCanPointeeTy)
5304 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005305 if (!isRelational &&
5306 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5307 // Valid unless comparison between non-null pointer and function pointer
5308 // This is a gcc extension compatibility comparison.
5309 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5310 && !LHSIsNull && !RHSIsNull) {
5311 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5312 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5313 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5314 return ResultTy;
5315 }
5316 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005317 // C++ [expr.rel]p2:
5318 // [...] Pointer conversions (4.10) and qualification
5319 // conversions (4.4) are performed on pointer operands (or on
5320 // a pointer operand and a null pointer constant) to bring
5321 // them to their composite pointer type. [...]
5322 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005323 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005324 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005325 bool NonStandardCompositeType = false;
5326 QualType T = FindCompositePointerType(lex, rex,
5327 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005328 if (T.isNull()) {
5329 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5330 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5331 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005332 } else if (NonStandardCompositeType) {
5333 Diag(Loc,
5334 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5335 << lType << rType << T
5336 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005337 }
5338
Eli Friedman06ed2a52009-10-20 08:27:19 +00005339 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5340 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005341 return ResultTy;
5342 }
Eli Friedman16c209612009-08-23 00:27:47 +00005343 // C99 6.5.9p2 and C99 6.5.8p2
5344 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5345 RCanPointeeTy.getUnqualifiedType())) {
5346 // Valid unless a relational comparison of function pointers
5347 if (isRelational && LCanPointeeTy->isFunctionType()) {
5348 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5349 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5350 }
5351 } else if (!isRelational &&
5352 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5353 // Valid unless comparison between non-null pointer and function pointer
5354 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5355 && !LHSIsNull && !RHSIsNull) {
5356 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5357 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5358 }
5359 } else {
5360 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005361 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005362 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005363 }
Eli Friedman16c209612009-08-23 00:27:47 +00005364 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005365 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005366 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005367 }
Mike Stump11289f42009-09-09 15:08:12 +00005368
Sebastian Redl576fd422009-05-10 18:38:11 +00005369 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005370 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005371 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005372 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005373 (lType->isPointerType() ||
5374 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005375 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005376 return ResultTy;
5377 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005378 if (LHSIsNull &&
5379 (rType->isPointerType() ||
5380 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005381 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005382 return ResultTy;
5383 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005384
5385 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005386 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005387 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5388 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005389 // In addition, pointers to members can be compared, or a pointer to
5390 // member and a null pointer constant. Pointer to member conversions
5391 // (4.11) and qualification conversions (4.4) are performed to bring
5392 // them to a common type. If one operand is a null pointer constant,
5393 // the common type is the type of the other operand. Otherwise, the
5394 // common type is a pointer to member type similar (4.4) to the type
5395 // of one of the operands, with a cv-qualification signature (4.4)
5396 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005397 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005398 bool NonStandardCompositeType = false;
5399 QualType T = FindCompositePointerType(lex, rex,
5400 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005401 if (T.isNull()) {
5402 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005403 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005404 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005405 } else if (NonStandardCompositeType) {
5406 Diag(Loc,
5407 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5408 << lType << rType << T
5409 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Eli Friedman06ed2a52009-10-20 08:27:19 +00005412 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5413 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005414 return ResultTy;
5415 }
Mike Stump11289f42009-09-09 15:08:12 +00005416
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005417 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005418 if (lType->isNullPtrType() && rType->isNullPtrType())
5419 return ResultTy;
5420 }
Mike Stump11289f42009-09-09 15:08:12 +00005421
Steve Naroff081c7422008-09-04 15:10:53 +00005422 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005423 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005424 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5425 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005426
Steve Naroff081c7422008-09-04 15:10:53 +00005427 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005428 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005429 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005430 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005431 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005432 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005433 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005434 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005435 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005436 if (!isRelational
5437 && ((lType->isBlockPointerType() && rType->isPointerType())
5438 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005439 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005440 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005441 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005442 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005443 ->getPointeeType()->isVoidType())))
5444 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5445 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005446 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005447 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005448 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005449 }
Steve Naroff081c7422008-09-04 15:10:53 +00005450
Steve Naroff7cae42b2009-07-10 23:34:53 +00005451 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005452 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005453 const PointerType *LPT = lType->getAs<PointerType>();
5454 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005455 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005456 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005457 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005458 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005459
Steve Naroff753567f2008-11-17 19:49:16 +00005460 if (!LPtrToVoid && !RPtrToVoid &&
5461 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005462 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005463 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005464 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005465 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005466 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005467 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005468 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005469 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5471 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005472 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005473 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005474 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005475 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005476 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005477 unsigned DiagID = 0;
5478 if (RHSIsNull) {
5479 if (isRelational)
5480 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5481 } else if (isRelational)
5482 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5483 else
5484 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005485
Chris Lattnerd99bd522009-08-23 00:03:44 +00005486 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005487 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005488 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005489 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005490 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005491 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005492 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005493 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005494 unsigned DiagID = 0;
5495 if (LHSIsNull) {
5496 if (isRelational)
5497 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5498 } else if (isRelational)
5499 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5500 else
5501 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005502
Chris Lattnerd99bd522009-08-23 00:03:44 +00005503 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005504 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005505 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005506 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005507 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005508 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005509 }
Steve Naroff4b191572008-09-04 16:56:14 +00005510 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005511 if (!isRelational && RHSIsNull
5512 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005513 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005514 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005515 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005516 if (!isRelational && LHSIsNull
5517 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005518 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005519 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005520 }
Chris Lattner326f7572008-11-18 01:30:42 +00005521 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005522}
5523
Nate Begeman191a6b12008-07-14 18:02:46 +00005524/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005525/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005526/// like a scalar comparison, a vector comparison produces a vector of integer
5527/// types.
5528QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005529 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005530 bool isRelational) {
5531 // Check to make sure we're operating on vectors of the same type and width,
5532 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005533 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005534 if (vType.isNull())
5535 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005536
Nate Begeman191a6b12008-07-14 18:02:46 +00005537 QualType lType = lex->getType();
5538 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005539
Nate Begeman191a6b12008-07-14 18:02:46 +00005540 // For non-floating point types, check for self-comparisons of the form
5541 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5542 // often indicate logic errors in the program.
5543 if (!lType->isFloatingType()) {
5544 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5545 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5546 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregor49862b82010-01-12 23:18:54 +00005547 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begeman191a6b12008-07-14 18:02:46 +00005548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005549
Nate Begeman191a6b12008-07-14 18:02:46 +00005550 // Check for comparisons of floating point operands using != and ==.
5551 if (!isRelational && lType->isFloatingType()) {
5552 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005553 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005554 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005555
Nate Begeman191a6b12008-07-14 18:02:46 +00005556 // Return the type for the comparison, which is the same as vector type for
5557 // integer vectors, or an integer type of identical size and number of
5558 // elements for floating point vectors.
5559 if (lType->isIntegerType())
5560 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005561
John McCall9dd450b2009-09-21 23:43:11 +00005562 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005563 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005564 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005565 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005566 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005567 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5568
Mike Stump4e1f26a2009-02-19 03:04:26 +00005569 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005570 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005571 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5572}
5573
Steve Naroff218bc2b2007-05-04 21:54:46 +00005574inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005575 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005576 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005577 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005578
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005579 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005580
Steve Naroffdbd9e892007-07-17 00:58:39 +00005581 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005582 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005583 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005584}
5585
Steve Naroff218bc2b2007-05-04 21:54:46 +00005586inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005587 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005588 if (!Context.getLangOptions().CPlusPlus) {
5589 UsualUnaryConversions(lex);
5590 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005591
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005592 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5593 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005594
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005595 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005596 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005597
5598 // C++ [expr.log.and]p1
5599 // C++ [expr.log.or]p1
5600 // The operands are both implicitly converted to type bool (clause 4).
5601 StandardConversionSequence LHS;
5602 if (!IsStandardConversion(lex, Context.BoolTy,
5603 /*InOverloadResolution=*/false, LHS))
5604 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005605
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005606 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005607 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005608 return InvalidOperands(Loc, lex, rex);
5609
5610 StandardConversionSequence RHS;
5611 if (!IsStandardConversion(rex, Context.BoolTy,
5612 /*InOverloadResolution=*/false, RHS))
5613 return InvalidOperands(Loc, lex, rex);
5614
5615 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005616 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005617 return InvalidOperands(Loc, lex, rex);
5618
5619 // C++ [expr.log.and]p2
5620 // C++ [expr.log.or]p2
5621 // The result is a bool.
5622 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005623}
5624
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005625/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5626/// is a read-only property; return true if so. A readonly property expression
5627/// depends on various declarations and thus must be treated specially.
5628///
Mike Stump11289f42009-09-09 15:08:12 +00005629static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005630 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5631 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5632 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5633 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005634 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005635 BaseType->getAsObjCInterfacePointerType())
5636 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5637 if (S.isPropertyReadonly(PDecl, IFace))
5638 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005639 }
5640 }
5641 return false;
5642}
5643
Chris Lattner30bd3272008-11-18 01:22:49 +00005644/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5645/// emit an error and return true. If so, return false.
5646static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005647 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005648 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005649 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005650 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5651 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005652 if (IsLV == Expr::MLV_Valid)
5653 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005654
Chris Lattner30bd3272008-11-18 01:22:49 +00005655 unsigned Diag = 0;
5656 bool NeedType = false;
5657 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00005658 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005659 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005660 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5661 NeedType = true;
5662 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005663 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005664 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5665 NeedType = true;
5666 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005667 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005668 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5669 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005670 case Expr::MLV_Valid:
5671 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00005672 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005673 case Expr::MLV_MemberFunction:
5674 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00005675 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5676 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005677 case Expr::MLV_IncompleteType:
5678 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005679 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005680 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5681 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005682 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005683 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5684 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005685 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005686 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5687 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005688 case Expr::MLV_ReadonlyProperty:
5689 Diag = diag::error_readonly_property_assignment;
5690 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005691 case Expr::MLV_NoSetterProperty:
5692 Diag = diag::error_nosetter_property_assignment;
5693 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005694 case Expr::MLV_SubObjCPropertySetting:
5695 Diag = diag::error_no_subobject_property_setting;
5696 break;
Fariborz Jahanian13b97822010-02-11 01:11:34 +00005697 case Expr::MLV_SubObjCPropertyGetterSetting:
5698 Diag = diag::error_no_subobject_property_getter_setting;
5699 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005700 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005701
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005702 SourceRange Assign;
5703 if (Loc != OrigLoc)
5704 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005705 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005706 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005707 else
Mike Stump11289f42009-09-09 15:08:12 +00005708 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005709 return true;
5710}
5711
5712
5713
5714// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005715QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5716 SourceLocation Loc,
5717 QualType CompoundType) {
5718 // Verify that LHS is a modifiable lvalue, and emit error if not.
5719 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005720 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005721
5722 QualType LHSType = LHS->getType();
5723 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005724
Chris Lattner9bad62c2008-01-04 18:04:52 +00005725 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005726 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005727 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005728 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005729 // Special case of NSObject attributes on c-style pointer types.
5730 if (ConvTy == IncompatiblePointer &&
5731 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005732 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005733 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005734 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005735 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005736
Chris Lattnerea714382008-08-21 18:04:13 +00005737 // If the RHS is a unary plus or minus, check to see if they = and + are
5738 // right next to each other. If so, the user may have typo'd "x =+ 4"
5739 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005740 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5742 RHSCheck = ICE->getSubExpr();
5743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5744 if ((UO->getOpcode() == UnaryOperator::Plus ||
5745 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005746 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005747 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005748 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5749 // And there is a space or other character before the subexpr of the
5750 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005751 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5752 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005753 Diag(Loc, diag::warn_not_compound_assign)
5754 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5755 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005756 }
Chris Lattnerea714382008-08-21 18:04:13 +00005757 }
5758 } else {
5759 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005760 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005761 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005762
Chris Lattner326f7572008-11-18 01:30:42 +00005763 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005764 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005765 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005766
Steve Naroff98cf3e92007-06-06 18:38:38 +00005767 // C99 6.5.16p3: The type of an assignment expression is the type of the
5768 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005769 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005770 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5771 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005772 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005773 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005774 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005775}
5776
Chris Lattner326f7572008-11-18 01:30:42 +00005777// C99 6.5.17
5778QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005779 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00005780 // C++ does not perform this conversion (C++ [expr.comma]p1).
5781 if (!getLangOptions().CPlusPlus)
5782 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005783
5784 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5785 // incomplete in C++).
5786
Chris Lattner326f7572008-11-18 01:30:42 +00005787 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005788}
5789
Steve Naroff7a5af782007-07-13 16:58:59 +00005790/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5791/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005792QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5793 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005794 if (Op->isTypeDependent())
5795 return Context.DependentTy;
5796
Chris Lattner6b0cf142008-11-21 07:05:48 +00005797 QualType ResType = Op->getType();
5798 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005799
Sebastian Redle10c2c32008-12-20 09:35:34 +00005800 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5801 // Decrement of bool is not allowed.
5802 if (!isInc) {
5803 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5804 return QualType();
5805 }
5806 // Increment of bool sets it to true, but is deprecated.
5807 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5808 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005809 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005810 } else if (ResType->isAnyPointerType()) {
5811 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005812
Chris Lattner6b0cf142008-11-21 07:05:48 +00005813 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005814 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005815 if (getLangOptions().CPlusPlus) {
5816 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5817 << Op->getSourceRange();
5818 return QualType();
5819 }
5820
5821 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005822 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005823 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005824 if (getLangOptions().CPlusPlus) {
5825 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5826 << Op->getType() << Op->getSourceRange();
5827 return QualType();
5828 }
5829
5830 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005831 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005832 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005833 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005834 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005835 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005836 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005837 // Diagnose bad cases where we step over interface counts.
5838 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5839 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5840 << PointeeTy << Op->getSourceRange();
5841 return QualType();
5842 }
Eli Friedman090addd2010-01-03 00:20:48 +00005843 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005844 // C99 does not support ++/-- on complex types, we allow as an extension.
5845 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005846 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005847 } else {
5848 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005849 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005850 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005851 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005852 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005853 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005854 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005855 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005856 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005857}
5858
Anders Carlsson806700f2008-02-01 07:15:58 +00005859/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005860/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005861/// where the declaration is needed for type checking. We only need to
5862/// handle cases when the expression references a function designator
5863/// or is an lvalue. Here are some examples:
5864/// - &(x) => x
5865/// - &*****f => f for f a function designator.
5866/// - &s.xx => s
5867/// - &s.zz[1].yy -> s, if zz is an array
5868/// - *(x + 1) -> x, if x is an array
5869/// - &"123"[2] -> 0
5870/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005871static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005872 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005873 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005874 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005875 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005876 // If this is an arrow operator, the address is an offset from
5877 // the base's value, so the object the base refers to is
5878 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005879 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005880 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005881 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005882 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005883 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005884 // FIXME: This code shouldn't be necessary! We should catch the implicit
5885 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005886 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5887 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5888 if (ICE->getSubExpr()->getType()->isArrayType())
5889 return getPrimaryDecl(ICE->getSubExpr());
5890 }
5891 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005892 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005893 case Stmt::UnaryOperatorClass: {
5894 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005895
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005896 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005897 case UnaryOperator::Real:
5898 case UnaryOperator::Imag:
5899 case UnaryOperator::Extension:
5900 return getPrimaryDecl(UO->getSubExpr());
5901 default:
5902 return 0;
5903 }
5904 }
Steve Naroff47500512007-04-19 23:00:49 +00005905 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005906 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005907 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005908 // If the result of an implicit cast is an l-value, we care about
5909 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005910 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005911 default:
5912 return 0;
5913 }
5914}
5915
5916/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005917/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005918/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005919/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005920/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005921/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005922/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005923QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005924 // Make sure to ignore parentheses in subsequent checks
5925 op = op->IgnoreParens();
5926
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005927 if (op->isTypeDependent())
5928 return Context.DependentTy;
5929
Steve Naroff826e91a2008-01-13 17:10:08 +00005930 if (getLangOptions().C99) {
5931 // Implement C99-only parts of addressof rules.
5932 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5933 if (uOp->getOpcode() == UnaryOperator::Deref)
5934 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5935 // (assuming the deref expression is valid).
5936 return uOp->getSubExpr()->getType();
5937 }
5938 // Technically, there should be a check for array subscript
5939 // expressions here, but the result of one is always an lvalue anyway.
5940 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005941 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005942 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005943
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005944 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5945 if (lval == Expr::LV_MemberFunction && ME &&
5946 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5947 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5948 // &f where f is a member of the current object, or &o.f, or &p->f
5949 // All these are not allowed, and we need to catch them before the dcl
5950 // branch of the if, below.
5951 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5952 << dcl;
5953 // FIXME: Improve this diagnostic and provide a fixit.
5954
5955 // Now recover by acting as if the function had been accessed qualified.
5956 return Context.getMemberPointerType(op->getType(),
5957 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5958 .getTypePtr());
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005959 } else if (lval == Expr::LV_ClassTemporary) {
5960 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
5961 : diag::ext_typecheck_addrof_class_temporary)
5962 << op->getType() << op->getSourceRange();
5963 if (isSFINAEContext())
5964 return QualType();
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005965 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005966 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005967 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005968 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005969 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005970 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5971 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005972 return QualType();
5973 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005974 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005975 // The operand cannot be a bit-field
5976 Diag(OpLoc, diag::err_typecheck_address_of)
5977 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005978 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005979 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005980 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005981 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005982 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005983 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005984 } else if (isa<ObjCPropertyRefExpr>(op)) {
5985 // cannot take address of a property expression.
5986 Diag(OpLoc, diag::err_typecheck_address_of)
5987 << "property expression" << op->getSourceRange();
5988 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005989 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5990 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005991 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5992 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005993 } else if (isa<UnresolvedLookupExpr>(op)) {
5994 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005995 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005996 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005997 // with the register storage-class specifier.
5998 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005999 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006000 Diag(OpLoc, diag::err_typecheck_address_of)
6001 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006002 return QualType();
6003 }
John McCalld14a8642009-11-21 08:51:07 +00006004 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006005 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00006006 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006007 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006008 // Could be a pointer to member, though, if there is an explicit
6009 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006010 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006011 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006012 if (Ctx && Ctx->isRecord()) {
6013 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006014 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006015 diag::err_cannot_form_pointer_to_member_of_reference_type)
6016 << FD->getDeclName() << FD->getType();
6017 return QualType();
6018 }
Mike Stump11289f42009-09-09 15:08:12 +00006019
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006020 return Context.getMemberPointerType(op->getType(),
6021 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006022 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006023 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006024 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006025 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006026 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006027 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6028 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006029 return Context.getMemberPointerType(op->getType(),
6030 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6031 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006032 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006033 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006034
Eli Friedmance7f9002009-05-16 23:27:50 +00006035 if (lval == Expr::LV_IncompleteVoidType) {
6036 // Taking the address of a void variable is technically illegal, but we
6037 // allow it in cases which are otherwise valid.
6038 // Example: "extern void x; void* y = &x;".
6039 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6040 }
6041
Steve Naroff47500512007-04-19 23:00:49 +00006042 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00006043 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006044}
6045
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006046QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006047 if (Op->isTypeDependent())
6048 return Context.DependentTy;
6049
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006050 UsualUnaryConversions(Op);
6051 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006052
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006053 // Note that per both C89 and C99, this is always legal, even if ptype is an
6054 // incomplete type or void. It would be possible to warn about dereferencing
6055 // a void pointer, but it's completely well-defined, and such a warning is
6056 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006057 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00006058 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006059
John McCall9dd450b2009-09-21 23:43:11 +00006060 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00006061 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006062
Chris Lattner29e812b2008-11-20 06:06:08 +00006063 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006064 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006065 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00006066}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006067
6068static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6069 tok::TokenKind Kind) {
6070 BinaryOperator::Opcode Opc;
6071 switch (Kind) {
6072 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006073 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6074 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006075 case tok::star: Opc = BinaryOperator::Mul; break;
6076 case tok::slash: Opc = BinaryOperator::Div; break;
6077 case tok::percent: Opc = BinaryOperator::Rem; break;
6078 case tok::plus: Opc = BinaryOperator::Add; break;
6079 case tok::minus: Opc = BinaryOperator::Sub; break;
6080 case tok::lessless: Opc = BinaryOperator::Shl; break;
6081 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6082 case tok::lessequal: Opc = BinaryOperator::LE; break;
6083 case tok::less: Opc = BinaryOperator::LT; break;
6084 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6085 case tok::greater: Opc = BinaryOperator::GT; break;
6086 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6087 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6088 case tok::amp: Opc = BinaryOperator::And; break;
6089 case tok::caret: Opc = BinaryOperator::Xor; break;
6090 case tok::pipe: Opc = BinaryOperator::Or; break;
6091 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6092 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6093 case tok::equal: Opc = BinaryOperator::Assign; break;
6094 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6095 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6096 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6097 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6098 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6099 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6100 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6101 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6102 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6103 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6104 case tok::comma: Opc = BinaryOperator::Comma; break;
6105 }
6106 return Opc;
6107}
6108
Steve Naroff35d85152007-05-07 00:24:15 +00006109static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6110 tok::TokenKind Kind) {
6111 UnaryOperator::Opcode Opc;
6112 switch (Kind) {
6113 default: assert(0 && "Unknown unary op!");
6114 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6115 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6116 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6117 case tok::star: Opc = UnaryOperator::Deref; break;
6118 case tok::plus: Opc = UnaryOperator::Plus; break;
6119 case tok::minus: Opc = UnaryOperator::Minus; break;
6120 case tok::tilde: Opc = UnaryOperator::Not; break;
6121 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006122 case tok::kw___real: Opc = UnaryOperator::Real; break;
6123 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006124 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006125 }
6126 return Opc;
6127}
6128
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006129/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6130/// operator @p Opc at location @c TokLoc. This routine only supports
6131/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006132Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6133 unsigned Op,
6134 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006135 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006136 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006137 // The following two variables are used for compound assignment operators
6138 QualType CompLHSTy; // Type of LHS after promotions for computation
6139 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006140
6141 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006142 case BinaryOperator::Assign:
6143 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6144 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006145 case BinaryOperator::PtrMemD:
6146 case BinaryOperator::PtrMemI:
6147 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6148 Opc == BinaryOperator::PtrMemI);
6149 break;
6150 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006151 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006152 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6153 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006154 break;
6155 case BinaryOperator::Rem:
6156 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6157 break;
6158 case BinaryOperator::Add:
6159 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6160 break;
6161 case BinaryOperator::Sub:
6162 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6163 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006164 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006165 case BinaryOperator::Shr:
6166 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6167 break;
6168 case BinaryOperator::LE:
6169 case BinaryOperator::LT:
6170 case BinaryOperator::GE:
6171 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006172 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006173 break;
6174 case BinaryOperator::EQ:
6175 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006176 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006177 break;
6178 case BinaryOperator::And:
6179 case BinaryOperator::Xor:
6180 case BinaryOperator::Or:
6181 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6182 break;
6183 case BinaryOperator::LAnd:
6184 case BinaryOperator::LOr:
6185 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6186 break;
6187 case BinaryOperator::MulAssign:
6188 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006189 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6190 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006191 CompLHSTy = CompResultTy;
6192 if (!CompResultTy.isNull())
6193 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006194 break;
6195 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006196 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6197 CompLHSTy = CompResultTy;
6198 if (!CompResultTy.isNull())
6199 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006200 break;
6201 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006202 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6203 if (!CompResultTy.isNull())
6204 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006205 break;
6206 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006207 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6208 if (!CompResultTy.isNull())
6209 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006210 break;
6211 case BinaryOperator::ShlAssign:
6212 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006213 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6214 CompLHSTy = CompResultTy;
6215 if (!CompResultTy.isNull())
6216 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006217 break;
6218 case BinaryOperator::AndAssign:
6219 case BinaryOperator::XorAssign:
6220 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006221 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6222 CompLHSTy = CompResultTy;
6223 if (!CompResultTy.isNull())
6224 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006225 break;
6226 case BinaryOperator::Comma:
6227 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6228 break;
6229 }
6230 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006231 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006232 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006233 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6234 else
6235 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006236 CompLHSTy, CompResultTy,
6237 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006238}
6239
Sebastian Redl44615072009-10-27 12:10:02 +00006240/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6241/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006242static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6243 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006244 SourceRange ParenRange,
6245 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6246 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006247 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6248 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6249 // We can't display the parentheses, so just dig the
6250 // warning/error and return.
6251 Self.Diag(Loc, PD);
6252 return;
6253 }
6254
6255 Self.Diag(Loc, PD)
6256 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6257 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006258
6259 if (!SecondPD.getDiagID())
6260 return;
6261
6262 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6263 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6264 // We can't display the parentheses, so just dig the
6265 // warning/error and return.
6266 Self.Diag(Loc, SecondPD);
6267 return;
6268 }
6269
6270 Self.Diag(Loc, SecondPD)
6271 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6272 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006273}
6274
Sebastian Redl44615072009-10-27 12:10:02 +00006275/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6276/// operators are mixed in a way that suggests that the programmer forgot that
6277/// comparison operators have higher precedence. The most typical example of
6278/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006279static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6280 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006281 typedef BinaryOperator BinOp;
6282 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6283 rhsopc = static_cast<BinOp::Opcode>(-1);
6284 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006285 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006286 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006287 rhsopc = BO->getOpcode();
6288
6289 // Subs are not binary operators.
6290 if (lhsopc == -1 && rhsopc == -1)
6291 return;
6292
6293 // Bitwise operations are sometimes used as eager logical ops.
6294 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006295 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6296 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006297 return;
6298
Sebastian Redl44615072009-10-27 12:10:02 +00006299 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006300 SuggestParentheses(Self, OpLoc,
6301 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006302 << SourceRange(lhs->getLocStart(), OpLoc)
6303 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006304 lhs->getSourceRange(),
6305 PDiag(diag::note_precedence_bitwise_first)
6306 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006307 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6308 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006309 SuggestParentheses(Self, OpLoc,
6310 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006311 << SourceRange(OpLoc, rhs->getLocEnd())
6312 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006313 rhs->getSourceRange(),
6314 PDiag(diag::note_precedence_bitwise_first)
6315 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006316 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006317}
6318
6319/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6320/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6321/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6322static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6323 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006324 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006325 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6326}
6327
Steve Naroff218bc2b2007-05-04 21:54:46 +00006328// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006329Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6330 tok::TokenKind Kind,
6331 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006332 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006333 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006334
Steve Naroff83895f72007-09-16 03:34:24 +00006335 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6336 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006337
Sebastian Redl43028242009-10-26 15:24:15 +00006338 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6339 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6340
Douglas Gregor5287f092009-11-05 00:51:44 +00006341 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6342}
6343
6344Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6345 BinaryOperator::Opcode Opc,
6346 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006347 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006348 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006349 rhs->getType()->isOverloadableType())) {
6350 // Find all of the overloaded operators visible from this
6351 // point. We perform both an operator-name lookup from the local
6352 // scope and an argument-dependent lookup based on the types of
6353 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006354 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006355 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006356 if (S && OverOp != OO_None)
6357 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6358 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006359
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006360 // Build the (potentially-overloaded, potentially-dependent)
6361 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006362 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006363 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006364
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006365 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006366 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006367}
6368
Douglas Gregor084d8552009-03-13 23:49:33 +00006369Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006370 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006371 ExprArg InputArg) {
6372 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006373
Mike Stump87c57ac2009-05-16 07:39:55 +00006374 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006375 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006376 QualType resultType;
6377 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006378 case UnaryOperator::OffsetOf:
6379 assert(false && "Invalid unary operator");
6380 break;
6381
Steve Naroff35d85152007-05-07 00:24:15 +00006382 case UnaryOperator::PreInc:
6383 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006384 case UnaryOperator::PostInc:
6385 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006386 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006387 Opc == UnaryOperator::PreInc ||
6388 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006389 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006390 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006391 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006392 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006393 case UnaryOperator::Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00006394 DefaultFunctionArrayLvalueConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006395 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006396 break;
6397 case UnaryOperator::Plus:
6398 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006399 UsualUnaryConversions(Input);
6400 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006401 if (resultType->isDependentType())
6402 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006403 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6404 break;
6405 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6406 resultType->isEnumeralType())
6407 break;
6408 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6409 Opc == UnaryOperator::Plus &&
6410 resultType->isPointerType())
6411 break;
6412
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006413 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6414 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006415 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006416 UsualUnaryConversions(Input);
6417 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006418 if (resultType->isDependentType())
6419 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006420 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6421 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6422 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006423 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006424 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006425 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006426 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6427 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006428 break;
6429 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006430 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00006431 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00006432 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006433 if (resultType->isDependentType())
6434 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006435 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006436 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6437 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006438 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006439 // In C++, it's bool. C++ 5.3.1p8
6440 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006441 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006442 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006443 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006444 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006445 break;
Chris Lattner86554282007-06-08 22:32:33 +00006446 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006447 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006448 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006449 }
6450 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006451 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006452
6453 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006454 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006455}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006456
Douglas Gregor5287f092009-11-05 00:51:44 +00006457Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6458 UnaryOperator::Opcode Opc,
6459 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006460 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006461 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6462 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006463 // Find all of the overloaded operators visible from this
6464 // point. We perform both an operator-name lookup from the local
6465 // scope and an argument-dependent lookup based on the types of
6466 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006467 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006468 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006469 if (S && OverOp != OO_None)
6470 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6471 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006472
Douglas Gregor084d8552009-03-13 23:49:33 +00006473 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6474 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006475
Douglas Gregor084d8552009-03-13 23:49:33 +00006476 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6477}
6478
Douglas Gregor5287f092009-11-05 00:51:44 +00006479// Unary Operators. 'Tok' is the token for the operator.
6480Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6481 tok::TokenKind Op, ExprArg input) {
6482 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6483}
6484
Steve Naroff66356bd2007-09-16 14:56:35 +00006485/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006486Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6487 SourceLocation LabLoc,
6488 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006489 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006490 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006492 // If we haven't seen this label yet, create a forward reference. It
6493 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006494 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006495 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006496
Chris Lattnereefa10e2007-05-28 06:56:27 +00006497 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006498 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6499 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006500}
6501
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006502Sema::OwningExprResult
6503Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6504 SourceLocation RPLoc) { // "({..})"
6505 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006506 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6507 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6508
Eli Friedman52cc0162009-01-24 23:09:00 +00006509 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006510 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006511 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006512
Chris Lattner366727f2007-07-24 16:58:17 +00006513 // FIXME: there are a variety of strange constraints to enforce here, for
6514 // example, it is not possible to goto into a stmt expression apparently.
6515 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006516
Chris Lattner366727f2007-07-24 16:58:17 +00006517 // If there are sub stmts in the compound stmt, take the type of the last one
6518 // as the type of the stmtexpr.
6519 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006520
Chris Lattner944d3062008-07-26 19:51:01 +00006521 if (!Compound->body_empty()) {
6522 Stmt *LastStmt = Compound->body_back();
6523 // If LastStmt is a label, skip down through into the body.
6524 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6525 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006526
Chris Lattner944d3062008-07-26 19:51:01 +00006527 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006528 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006529 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006530
Eli Friedmanba961a92009-03-23 00:24:07 +00006531 // FIXME: Check that expression type is complete/non-abstract; statement
6532 // expressions are not lvalues.
6533
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006534 substmt.release();
6535 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006536}
Steve Naroff78864672007-08-01 22:05:33 +00006537
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006538Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6539 SourceLocation BuiltinLoc,
6540 SourceLocation TypeLoc,
6541 TypeTy *argty,
6542 OffsetOfComponent *CompPtr,
6543 unsigned NumComponents,
6544 SourceLocation RPLoc) {
6545 // FIXME: This function leaks all expressions in the offset components on
6546 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006547 // FIXME: Preserve type source info.
6548 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006549 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006550
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006551 bool Dependent = ArgTy->isDependentType();
6552
Chris Lattnerf17bd422007-08-30 17:45:32 +00006553 // We must have at least one component that refers to the type, and the first
6554 // one is known to be a field designator. Verify that the ArgTy represents
6555 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006556 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006557 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006558
Eli Friedmanba961a92009-03-23 00:24:07 +00006559 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6560 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006561
Eli Friedman988a16b2009-02-27 06:44:11 +00006562 // Otherwise, create a null pointer as the base, and iteratively process
6563 // the offsetof designators.
6564 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6565 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006566 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006567 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006568
Chris Lattner78502cf2007-08-31 21:49:13 +00006569 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6570 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006571 // FIXME: This diagnostic isn't actually visible because the location is in
6572 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006573 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006574 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6575 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006576
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006577 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006578 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006579
John McCall9eff4e62009-11-04 03:03:43 +00006580 if (RequireCompleteType(TypeLoc, Res->getType(),
6581 diag::err_offsetof_incomplete_type))
6582 return ExprError();
6583
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006584 // FIXME: Dependent case loses a lot of information here. And probably
6585 // leaks like a sieve.
6586 for (unsigned i = 0; i != NumComponents; ++i) {
6587 const OffsetOfComponent &OC = CompPtr[i];
6588 if (OC.isBrackets) {
6589 // Offset of an array sub-field. TODO: Should we allow vector elements?
6590 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6591 if (!AT) {
6592 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006593 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6594 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006595 }
6596
6597 // FIXME: C++: Verify that operator[] isn't overloaded.
6598
Eli Friedman988a16b2009-02-27 06:44:11 +00006599 // Promote the array so it looks more like a normal array subscript
6600 // expression.
Douglas Gregorb92a1562010-02-03 00:27:59 +00006601 DefaultFunctionArrayLvalueConversion(Res);
Eli Friedman988a16b2009-02-27 06:44:11 +00006602
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006603 // C99 6.5.2.1p1
6604 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006605 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006606 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006607 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006608 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006609 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006610
6611 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6612 OC.LocEnd);
6613 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006614 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006615
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006616 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006617 if (!RC) {
6618 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006619 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6620 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006621 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006622
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006623 // Get the decl corresponding to this.
6624 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006625 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006626 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6627 DiagRuntimeBehavior(BuiltinLoc,
6628 PDiag(diag::warn_offsetof_non_pod_type)
6629 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6630 << Res->getType()))
6631 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006632 }
Mike Stump11289f42009-09-09 15:08:12 +00006633
John McCall27b18f82009-11-17 02:14:36 +00006634 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6635 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006636
John McCall67c00872009-12-02 08:25:40 +00006637 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006638 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006639 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006640 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6641 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006642
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006643 // FIXME: C++: Verify that MemberDecl isn't a static field.
6644 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006645 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006646 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006647 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006648 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006649 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006650 // MemberDecl->getType() doesn't get the right qualifiers, but it
6651 // doesn't matter here.
6652 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6653 MemberDecl->getType().getNonReferenceType());
6654 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006655 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006656 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006657
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006658 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6659 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006660}
6661
6662
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006663Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6664 TypeTy *arg1,TypeTy *arg2,
6665 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006666 // FIXME: Preserve type source info.
6667 QualType argT1 = GetTypeFromParser(arg1);
6668 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006669
Steve Naroff78864672007-08-01 22:05:33 +00006670 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006671
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006672 if (getLangOptions().CPlusPlus) {
6673 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6674 << SourceRange(BuiltinLoc, RPLoc);
6675 return ExprError();
6676 }
6677
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006678 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6679 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006680}
6681
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006682Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6683 ExprArg cond,
6684 ExprArg expr1, ExprArg expr2,
6685 SourceLocation RPLoc) {
6686 Expr *CondExpr = static_cast<Expr*>(cond.get());
6687 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6688 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006689
Steve Naroff9efdabc2007-08-03 21:21:27 +00006690 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6691
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006692 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006693 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006694 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006695 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006696 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006697 } else {
6698 // The conditional expression is required to be a constant expression.
6699 llvm::APSInt condEval(32);
6700 SourceLocation ExpLoc;
6701 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006702 return ExprError(Diag(ExpLoc,
6703 diag::err_typecheck_choose_expr_requires_constant)
6704 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006705
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006706 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6707 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006708 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6709 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006710 }
6711
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006712 cond.release(); expr1.release(); expr2.release();
6713 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006714 resType, RPLoc,
6715 resType->isDependentType(),
6716 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006717}
6718
Steve Naroffc540d662008-09-03 18:15:37 +00006719//===----------------------------------------------------------------------===//
6720// Clang Extensions.
6721//===----------------------------------------------------------------------===//
6722
6723/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006724void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006725 // Analyze block parameters.
Douglas Gregor4f13beb2010-03-01 20:44:28 +00006726 BlockScopeInfo *BSI = new BlockScopeInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006727
Steve Naroffc540d662008-09-03 18:15:37 +00006728 // Add BSI to CurBlock.
6729 BSI->PrevBlockInfo = CurBlock;
6730 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006732 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006733 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006734 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006735 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006736 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6737 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006738
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006739 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006740 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006741 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006742}
6743
Mike Stump82f071f2009-02-04 22:31:32 +00006744void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006745 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006746
6747 if (ParamInfo.getNumTypeObjects() == 0
6748 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006749 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006750 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6751
Mike Stumpd456c482009-04-28 01:10:27 +00006752 if (T->isArrayType()) {
6753 Diag(ParamInfo.getSourceRange().getBegin(),
6754 diag::err_block_returns_array);
6755 return;
6756 }
6757
Mike Stump82f071f2009-02-04 22:31:32 +00006758 // The parameter list is optional, if there was none, assume ().
6759 if (!T->isFunctionType())
Douglas Gregor36c569f2010-02-21 22:15:06 +00006760 T = Context.getFunctionType(T, 0, 0, false, 0, false, false, 0, 0, false,
6761 CC_Default);
Mike Stump82f071f2009-02-04 22:31:32 +00006762
6763 CurBlock->hasPrototype = true;
6764 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006765 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006766 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006767 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006768 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006769 // FIXME: remove the attribute.
6770 }
John McCall9dd450b2009-09-21 23:43:11 +00006771 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006772
Chris Lattner6de05082009-04-11 19:27:54 +00006773 // Do not allow returning a objc interface by-value.
6774 if (RetTy->isObjCInterfaceType()) {
6775 Diag(ParamInfo.getSourceRange().getBegin(),
6776 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6777 return;
6778 }
Douglas Gregorb92a1562010-02-03 00:27:59 +00006779
6780 CurBlock->ReturnType = RetTy;
Mike Stump82f071f2009-02-04 22:31:32 +00006781 return;
6782 }
6783
Steve Naroffc540d662008-09-03 18:15:37 +00006784 // Analyze arguments to block.
6785 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6786 "Not a function declarator!");
6787 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006788
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006789 CurBlock->hasPrototype = FTI.hasPrototype;
6790 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006791
Steve Naroffc540d662008-09-03 18:15:37 +00006792 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6793 // no arguments, not a function that takes a single void argument.
6794 if (FTI.hasPrototype &&
6795 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006796 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6797 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006798 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006799 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006800 } else if (FTI.hasPrototype) {
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00006801 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6802 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
6803 if (Param->getIdentifier() == 0 &&
6804 !Param->isImplicit() &&
6805 !Param->isInvalidDecl() &&
6806 !getLangOptions().CPlusPlus)
6807 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6808 CurBlock->Params.push_back(Param);
6809 }
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006810 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006811 }
Douglas Gregord5058122010-02-11 01:19:42 +00006812 CurBlock->TheDecl->setParams(CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006813 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006814 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006815 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006816 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00006817 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6818 (*AI)->setOwningFunction(CurBlock->TheDecl);
6819
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006820 // If this has an identifier, add it to the scope stack.
6821 if ((*AI)->getIdentifier())
6822 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCallf7b2fb52010-01-22 00:28:27 +00006823 }
Chris Lattner6de05082009-04-11 19:27:54 +00006824
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006825 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006826 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006827 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006828 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006829 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006830 // FIXME: remove the attribute.
6831 }
Mike Stump11289f42009-09-09 15:08:12 +00006832
Chris Lattner6de05082009-04-11 19:27:54 +00006833 // Analyze the return type.
6834 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006835 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006836
Chris Lattner6de05082009-04-11 19:27:54 +00006837 // Do not allow returning a objc interface by-value.
6838 if (RetTy->isObjCInterfaceType()) {
6839 Diag(ParamInfo.getSourceRange().getBegin(),
6840 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6841 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006842 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006843}
6844
6845/// ActOnBlockError - If there is an error parsing a block, this callback
6846/// is invoked to pop the information about the block from the action impl.
6847void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6848 // Ensure that CurBlock is deleted.
Douglas Gregor4f13beb2010-03-01 20:44:28 +00006849 llvm::OwningPtr<BlockScopeInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006850
Chris Lattner45542ea2009-04-19 05:28:12 +00006851 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6852
Steve Naroffc540d662008-09-03 18:15:37 +00006853 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006854 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006855 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006856 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006857}
6858
6859/// ActOnBlockStmtExpr - This is called when the body of a block statement
6860/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006861Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6862 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006863 // If blocks are disabled, emit an error.
6864 if (!LangOpts.Blocks)
6865 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006866
Steve Naroffc540d662008-09-03 18:15:37 +00006867 // Ensure that CurBlock is deleted.
Douglas Gregor4f13beb2010-03-01 20:44:28 +00006868 llvm::OwningPtr<BlockScopeInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006869
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006870 PopDeclContext();
6871
Steve Naroffc540d662008-09-03 18:15:37 +00006872 // Pop off CurBlock, handle nested blocks.
6873 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006874
Steve Naroffc540d662008-09-03 18:15:37 +00006875 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006876 if (!BSI->ReturnType.isNull())
6877 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006878
Steve Naroffc540d662008-09-03 18:15:37 +00006879 llvm::SmallVector<QualType, 8> ArgTypes;
6880 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6881 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006882
Mike Stump3bf1ab42009-07-28 22:04:01 +00006883 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006884 QualType BlockTy;
6885 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006886 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
Douglas Gregor36c569f2010-02-21 22:15:06 +00006887 NoReturn, CC_Default);
Steve Naroffc540d662008-09-03 18:15:37 +00006888 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006889 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006890 BSI->isVariadic, 0, false, false, 0, 0,
Douglas Gregor36c569f2010-02-21 22:15:06 +00006891 NoReturn, CC_Default);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006892
Eli Friedmanba961a92009-03-23 00:24:07 +00006893 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006894 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006895 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896
Chris Lattner45542ea2009-04-19 05:28:12 +00006897 // If needed, diagnose invalid gotos and switches in the block.
6898 if (CurFunctionNeedsScopeChecking)
6899 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6900 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006901
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006902 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump314825b2010-01-19 23:08:01 +00006903
6904 bool Good = true;
6905 // Check goto/label use.
6906 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6907 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6908 LabelStmt *L = I->second;
6909
6910 // Verify that we have no forward references left. If so, there was a goto
6911 // or address of a label taken, but no definition of it.
6912 if (L->getSubStmt() != 0)
6913 continue;
6914
6915 // Emit error.
6916 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6917 Good = false;
6918 }
6919 BSI->LabelMap.clear();
6920 if (!Good)
6921 return ExprError();
6922
Mike Stump1bacb812010-01-13 02:59:54 +00006923 AnalysisContext AC(BSI->TheDecl);
6924 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6925 CheckUnreachable(AC);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006926 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6927 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006928}
6929
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006930Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6931 ExprArg expr, TypeTy *type,
6932 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006933 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006934 Expr *E = static_cast<Expr*>(expr.get());
6935 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006936
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006937 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006938
6939 // Get the va_list type
6940 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006941 if (VaListType->isArrayType()) {
6942 // Deal with implicit array decay; for example, on x86-64,
6943 // va_list is an array, but it's supposed to decay to
6944 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006945 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006946 // Make sure the input expression also decays appropriately.
6947 UsualUnaryConversions(E);
6948 } else {
6949 // Otherwise, the va_list argument must be an l-value because
6950 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006951 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006952 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006953 return ExprError();
6954 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006955
Douglas Gregorad3150c2009-05-19 23:10:31 +00006956 if (!E->isTypeDependent() &&
6957 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006958 return ExprError(Diag(E->getLocStart(),
6959 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006960 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006961 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006962
Eli Friedmanba961a92009-03-23 00:24:07 +00006963 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006964 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006965
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006966 expr.release();
6967 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6968 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006969}
6970
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006971Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006972 // The type of __null will be int or long, depending on the size of
6973 // pointers on the target.
6974 QualType Ty;
6975 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6976 Ty = Context.IntTy;
6977 else
6978 Ty = Context.LongTy;
6979
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006980 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006981}
6982
Anders Carlssonace5d072009-11-10 04:46:30 +00006983static void
6984MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6985 QualType DstType,
6986 Expr *SrcExpr,
6987 CodeModificationHint &Hint) {
6988 if (!SemaRef.getLangOptions().ObjC1)
6989 return;
6990
6991 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6992 if (!PT)
6993 return;
6994
6995 // Check if the destination is of type 'id'.
6996 if (!PT->isObjCIdType()) {
6997 // Check if the destination is the 'NSString' interface.
6998 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6999 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7000 return;
7001 }
7002
7003 // Strip off any parens and casts.
7004 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7005 if (!SL || SL->isWide())
7006 return;
7007
7008 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
7009}
7010
Chris Lattner9bad62c2008-01-04 18:04:52 +00007011bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7012 SourceLocation Loc,
7013 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007014 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00007015 // Decode the result (notice that AST's are still created for extensions).
7016 bool isInvalid = false;
7017 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00007018 CodeModificationHint Hint;
7019
Chris Lattner9bad62c2008-01-04 18:04:52 +00007020 switch (ConvTy) {
7021 default: assert(0 && "Unknown conversion type");
7022 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007023 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007024 DiagKind = diag::ext_typecheck_convert_pointer_int;
7025 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007026 case IntToPointer:
7027 DiagKind = diag::ext_typecheck_convert_int_pointer;
7028 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007029 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00007030 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007031 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7032 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007033 case IncompatiblePointerSign:
7034 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7035 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007036 case FunctionVoidPointer:
7037 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7038 break;
7039 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007040 // If the qualifiers lost were because we were applying the
7041 // (deprecated) C++ conversion from a string literal to a char*
7042 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7043 // Ideally, this check would be performed in
7044 // CheckPointerTypesForAssignment. However, that would require a
7045 // bit of refactoring (so that the second argument is an
7046 // expression, rather than a type), which should be done as part
7047 // of a larger effort to fix CheckPointerTypesForAssignment for
7048 // C++ semantics.
7049 if (getLangOptions().CPlusPlus &&
7050 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7051 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007052 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7053 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007054 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007055 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007056 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007057 case IntToBlockPointer:
7058 DiagKind = diag::err_int_to_block_pointer;
7059 break;
7060 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007061 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007062 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007063 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007064 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007065 // it can give a more specific diagnostic.
7066 DiagKind = diag::warn_incompatible_qualified_id;
7067 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007068 case IncompatibleVectors:
7069 DiagKind = diag::warn_incompatible_vectors;
7070 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007071 case Incompatible:
7072 DiagKind = diag::err_typecheck_convert_incompatible;
7073 isInvalid = true;
7074 break;
7075 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007076
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007077 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007078 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007079 return isInvalid;
7080}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007081
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007082bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007083 llvm::APSInt ICEResult;
7084 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7085 if (Result)
7086 *Result = ICEResult;
7087 return false;
7088 }
7089
Anders Carlssone54e8a12008-11-30 19:50:32 +00007090 Expr::EvalResult EvalResult;
7091
Mike Stump4e1f26a2009-02-19 03:04:26 +00007092 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007093 EvalResult.HasSideEffects) {
7094 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7095
7096 if (EvalResult.Diag) {
7097 // We only show the note if it's not the usual "invalid subexpression"
7098 // or if it's actually in a subexpression.
7099 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7100 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7101 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7102 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007103
Anders Carlssone54e8a12008-11-30 19:50:32 +00007104 return true;
7105 }
7106
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007107 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7108 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007109
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007110 if (EvalResult.Diag &&
7111 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7112 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007113
Anders Carlssone54e8a12008-11-30 19:50:32 +00007114 if (Result)
7115 *Result = EvalResult.Val.getInt();
7116 return false;
7117}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007118
Douglas Gregorff790f12009-11-26 00:44:06 +00007119void
Mike Stump11289f42009-09-09 15:08:12 +00007120Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007121 ExprEvalContexts.push_back(
7122 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007123}
7124
Mike Stump11289f42009-09-09 15:08:12 +00007125void
Douglas Gregorff790f12009-11-26 00:44:06 +00007126Sema::PopExpressionEvaluationContext() {
7127 // Pop the current expression evaluation context off the stack.
7128 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7129 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007130
Douglas Gregorfab31f42009-12-12 07:57:52 +00007131 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7132 if (Rec.PotentiallyReferenced) {
7133 // Mark any remaining declarations in the current position of the stack
7134 // as "referenced". If they were not meant to be referenced, semantic
7135 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7136 for (PotentiallyReferencedDecls::iterator
7137 I = Rec.PotentiallyReferenced->begin(),
7138 IEnd = Rec.PotentiallyReferenced->end();
7139 I != IEnd; ++I)
7140 MarkDeclarationReferenced(I->first, I->second);
7141 }
7142
7143 if (Rec.PotentiallyDiagnosed) {
7144 // Emit any pending diagnostics.
7145 for (PotentiallyEmittedDiagnostics::iterator
7146 I = Rec.PotentiallyDiagnosed->begin(),
7147 IEnd = Rec.PotentiallyDiagnosed->end();
7148 I != IEnd; ++I)
7149 Diag(I->first, I->second);
7150 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007151 }
7152
7153 // When are coming out of an unevaluated context, clear out any
7154 // temporaries that we may have created as part of the evaluation of
7155 // the expression in that context: they aren't relevant because they
7156 // will never be constructed.
7157 if (Rec.Context == Unevaluated &&
7158 ExprTemporaries.size() > Rec.NumTemporaries)
7159 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7160 ExprTemporaries.end());
7161
7162 // Destroy the popped expression evaluation record.
7163 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007164}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007165
7166/// \brief Note that the given declaration was referenced in the source code.
7167///
7168/// This routine should be invoke whenever a given declaration is referenced
7169/// in the source code, and where that reference occurred. If this declaration
7170/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7171/// C99 6.9p3), then the declaration will be marked as used.
7172///
7173/// \param Loc the location where the declaration was referenced.
7174///
7175/// \param D the declaration that has been referenced by the source code.
7176void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7177 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007178
Douglas Gregor77b50e12009-06-22 23:06:13 +00007179 if (D->isUsed())
7180 return;
Mike Stump11289f42009-09-09 15:08:12 +00007181
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007182 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7183 // template or not. The reason for this is that unevaluated expressions
7184 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7185 // -Wunused-parameters)
7186 if (isa<ParmVarDecl>(D) ||
7187 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007188 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007189
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007190 // Do not mark anything as "used" within a dependent context; wait for
7191 // an instantiation.
7192 if (CurContext->isDependentContext())
7193 return;
Mike Stump11289f42009-09-09 15:08:12 +00007194
Douglas Gregorff790f12009-11-26 00:44:06 +00007195 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007196 case Unevaluated:
7197 // We are in an expression that is not potentially evaluated; do nothing.
7198 return;
Mike Stump11289f42009-09-09 15:08:12 +00007199
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007200 case PotentiallyEvaluated:
7201 // We are in a potentially-evaluated expression, so this declaration is
7202 // "used"; handle this below.
7203 break;
Mike Stump11289f42009-09-09 15:08:12 +00007204
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007205 case PotentiallyPotentiallyEvaluated:
7206 // We are in an expression that may be potentially evaluated; queue this
7207 // declaration reference until we know whether the expression is
7208 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007209 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007210 return;
7211 }
Mike Stump11289f42009-09-09 15:08:12 +00007212
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007213 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007214 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007215 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007216 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7217 if (!Constructor->isUsed())
7218 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007219 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007220 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007221 if (!Constructor->isUsed())
7222 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7223 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007224
7225 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007226 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7227 if (Destructor->isImplicit() && !Destructor->isUsed())
7228 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007229
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007230 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7231 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7232 MethodDecl->getOverloadedOperator() == OO_Equal) {
7233 if (!MethodDecl->isUsed())
7234 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7235 }
7236 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007237 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007238 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007239 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007240 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007241 bool AlreadyInstantiated = false;
7242 if (FunctionTemplateSpecializationInfo *SpecInfo
7243 = Function->getTemplateSpecializationInfo()) {
7244 if (SpecInfo->getPointOfInstantiation().isInvalid())
7245 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007246 else if (SpecInfo->getTemplateSpecializationKind()
7247 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007248 AlreadyInstantiated = true;
7249 } else if (MemberSpecializationInfo *MSInfo
7250 = Function->getMemberSpecializationInfo()) {
7251 if (MSInfo->getPointOfInstantiation().isInvalid())
7252 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007253 else if (MSInfo->getTemplateSpecializationKind()
7254 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007255 AlreadyInstantiated = true;
7256 }
7257
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007258 if (!AlreadyInstantiated) {
7259 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7260 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7261 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7262 Loc));
7263 else
7264 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7265 Loc));
7266 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007267 }
7268
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007269 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007270 Function->setUsed(true);
Tanya Lattner90073802010-02-12 00:07:30 +00007271
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007272 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007273 }
Mike Stump11289f42009-09-09 15:08:12 +00007274
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007275 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007276 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007277 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007278 Var->getInstantiatedFromStaticDataMember()) {
7279 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7280 assert(MSInfo && "Missing member specialization information?");
7281 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7282 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7283 MSInfo->setPointOfInstantiation(Loc);
7284 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7285 }
7286 }
Mike Stump11289f42009-09-09 15:08:12 +00007287
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007288 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007289
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007290 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007291 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007292 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007293}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007294
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007295/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7296/// of the program being compiled.
7297///
7298/// This routine emits the given diagnostic when the code currently being
7299/// type-checked is "potentially evaluated", meaning that there is a
7300/// possibility that the code will actually be executable. Code in sizeof()
7301/// expressions, code used only during overload resolution, etc., are not
7302/// potentially evaluated. This routine will suppress such diagnostics or,
7303/// in the absolutely nutty case of potentially potentially evaluated
7304/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7305/// later.
7306///
7307/// This routine should be used for all diagnostics that describe the run-time
7308/// behavior of a program, such as passing a non-POD value through an ellipsis.
7309/// Failure to do so will likely result in spurious diagnostics or failures
7310/// during overload resolution or within sizeof/alignof/typeof/typeid.
7311bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7312 const PartialDiagnostic &PD) {
7313 switch (ExprEvalContexts.back().Context ) {
7314 case Unevaluated:
7315 // The argument will never be evaluated, so don't complain.
7316 break;
7317
7318 case PotentiallyEvaluated:
7319 Diag(Loc, PD);
7320 return true;
7321
7322 case PotentiallyPotentiallyEvaluated:
7323 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7324 break;
7325 }
7326
7327 return false;
7328}
7329
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007330bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7331 CallExpr *CE, FunctionDecl *FD) {
7332 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7333 return false;
7334
7335 PartialDiagnostic Note =
7336 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7337 << FD->getDeclName() : PDiag();
7338 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7339
7340 if (RequireCompleteType(Loc, ReturnType,
7341 FD ?
7342 PDiag(diag::err_call_function_incomplete_return)
7343 << CE->getSourceRange() << FD->getDeclName() :
7344 PDiag(diag::err_call_incomplete_return)
7345 << CE->getSourceRange(),
7346 std::make_pair(NoteLoc, Note)))
7347 return true;
7348
7349 return false;
7350}
7351
John McCalld5707ab2009-10-12 21:59:07 +00007352// Diagnose the common s/=/==/ typo. Note that adding parentheses
7353// will prevent this condition from triggering, which is what we want.
7354void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7355 SourceLocation Loc;
7356
John McCall0506e4a2009-11-11 02:41:58 +00007357 unsigned diagnostic = diag::warn_condition_is_assignment;
7358
John McCalld5707ab2009-10-12 21:59:07 +00007359 if (isa<BinaryOperator>(E)) {
7360 BinaryOperator *Op = cast<BinaryOperator>(E);
7361 if (Op->getOpcode() != BinaryOperator::Assign)
7362 return;
7363
John McCallb0e419e2009-11-12 00:06:05 +00007364 // Greylist some idioms by putting them into a warning subcategory.
7365 if (ObjCMessageExpr *ME
7366 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7367 Selector Sel = ME->getSelector();
7368
John McCallb0e419e2009-11-12 00:06:05 +00007369 // self = [<foo> init...]
7370 if (isSelfExpr(Op->getLHS())
7371 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7372 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7373
7374 // <foo> = [<bar> nextObject]
7375 else if (Sel.isUnarySelector() &&
7376 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7377 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7378 }
John McCall0506e4a2009-11-11 02:41:58 +00007379
John McCalld5707ab2009-10-12 21:59:07 +00007380 Loc = Op->getOperatorLoc();
7381 } else if (isa<CXXOperatorCallExpr>(E)) {
7382 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7383 if (Op->getOperator() != OO_Equal)
7384 return;
7385
7386 Loc = Op->getOperatorLoc();
7387 } else {
7388 // Not an assignment.
7389 return;
7390 }
7391
John McCalld5707ab2009-10-12 21:59:07 +00007392 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007393 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007394
John McCall0506e4a2009-11-11 02:41:58 +00007395 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007396 << E->getSourceRange()
7397 << CodeModificationHint::CreateInsertion(Open, "(")
7398 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007399 Diag(Loc, diag::note_condition_assign_to_comparison)
7400 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007401}
7402
7403bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7404 DiagnoseAssignmentAsCondition(E);
7405
7406 if (!E->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +00007407 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00007408
7409 QualType T = E->getType();
7410
7411 if (getLangOptions().CPlusPlus) {
7412 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7413 return true;
7414 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7415 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7416 << T << E->getSourceRange();
7417 return true;
7418 }
7419 }
7420
7421 return false;
7422}