blob: f5ecff818443b7c9703b7df9e21283533830323f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor99a2e602009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000017#include "AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
David Chisnall0f436562009-08-17 16:35:33 +000034
Douglas Gregor48f3bb92009-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 Lattner52338262009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000049///
John McCall54abf7d2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000054 }
55
Chris Lattnerffb93682009-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 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000061
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-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 Gregor25d944a2009-02-24 04:26:15 +000069 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000070
Douglas Gregor48f3bb92009-02-18 21:56:37 +000071 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-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 Stump1eb44332009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000082 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +000083
84 // FIXME: In C++0x, if any of the arguments are parameter pack
85 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 int sentinelPos = attr->getSentinel();
87 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000088
Mike Stump390b4cc2009-05-16 07:39:55 +000089 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
90 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000091 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000092 bool warnNotEnoughArgs = false;
93 int isMethod = 0;
94 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
95 // skip over named parameters.
96 ObjCMethodDecl::param_iterator P, E = MD->param_end();
97 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
98 if (nullPos)
99 --nullPos;
100 else
101 ++i;
102 }
103 warnNotEnoughArgs = (P != E || i >= NumArgs);
104 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000105 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000106 // skip over named parameters.
107 ObjCMethodDecl::param_iterator P, E = FD->param_end();
108 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
109 if (nullPos)
110 --nullPos;
111 else
112 ++i;
113 }
114 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000115 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000116 // block or function pointer call.
117 QualType Ty = V->getType();
118 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000119 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000120 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
121 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000122 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
123 unsigned NumArgsInProto = Proto->getNumArgs();
124 unsigned k;
125 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
126 if (nullPos)
127 --nullPos;
128 else
129 ++i;
130 }
131 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
132 }
133 if (Ty->isBlockPointerType())
134 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000135 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000136 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000137 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000138 return;
139
140 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000141 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000142 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000143 return;
144 }
145 int sentinel = i;
146 while (sentinelPos > 0 && i < NumArgs-1) {
147 --sentinelPos;
148 ++i;
149 }
150 if (sentinelPos > 0) {
151 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000152 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000153 return;
154 }
155 while (i < NumArgs-1) {
156 ++i;
157 ++sentinel;
158 }
159 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000160 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
Douglas Gregor92e986e2010-04-22 16:44:27 +0000161 !sentinelExpr->isTypeDependent() &&
162 !sentinelExpr->isValueDependent() &&
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000163 (!sentinelExpr->getType()->isPointerType() ||
164 !sentinelExpr->isNullPointerConstant(Context,
165 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000166 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000168 }
169 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000170}
171
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000172SourceRange Sema::getExprRange(ExprTy *E) const {
173 Expr *Ex = (Expr *)E;
174 return Ex? Ex->getSourceRange() : SourceRange();
175}
176
Chris Lattnere7a2e912008-07-25 21:10:04 +0000177//===----------------------------------------------------------------------===//
178// Standard Promotions and Conversions
179//===----------------------------------------------------------------------===//
180
Chris Lattnere7a2e912008-07-25 21:10:04 +0000181/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
182void Sema::DefaultFunctionArrayConversion(Expr *&E) {
183 QualType Ty = E->getType();
184 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
185
Chris Lattnere7a2e912008-07-25 21:10:04 +0000186 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000187 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000188 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000189 else if (Ty->isArrayType()) {
190 // In C90 mode, arrays only promote to pointers if the array expression is
191 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
192 // type 'array of type' is converted to an expression that has type 'pointer
193 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
194 // that has type 'array of type' ...". The relevant change is "an lvalue"
195 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000196 //
197 // C++ 4.2p1:
198 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
199 // T" can be converted to an rvalue of type "pointer to T".
200 //
201 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
202 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000203 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
204 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000205 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000206}
207
Douglas Gregora873dfc2010-02-03 00:27:59 +0000208void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
209 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000210
Douglas Gregora873dfc2010-02-03 00:27:59 +0000211 QualType Ty = E->getType();
212 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
213 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
214 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
215 E->isLvalue(Context) == Expr::LV_Valid) {
216 // C++ [conv.lval]p1:
217 // [...] If T is a non-class type, the type of the rvalue is the
218 // cv-unqualified version of T. Otherwise, the type of the
219 // rvalue is T
220 //
221 // C99 6.3.2.1p2:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000222 // If the lvalue has qualified type, the value has the unqualified
223 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregora873dfc2010-02-03 00:27:59 +0000224 // type of the lvalue.
225 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
226 }
227}
228
229
Chris Lattnere7a2e912008-07-25 21:10:04 +0000230/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000231/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000232/// sometimes surpressed. For example, the array->pointer conversion doesn't
233/// apply if the array is an argument to the sizeof or address (&) operators.
234/// In these instances, this routine should *not* be called.
235Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
236 QualType Ty = Expr->getType();
237 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Douglas Gregorfc24e442009-05-01 20:41:21 +0000239 // C99 6.3.1.1p2:
240 //
241 // The following may be used in an expression wherever an int or
242 // unsigned int may be used:
243 // - an object or expression with an integer type whose integer
244 // conversion rank is less than or equal to the rank of int
245 // and unsigned int.
246 // - A bit-field of type _Bool, int, signed int, or unsigned int.
247 //
248 // If an int can represent all values of the original type, the
249 // value is converted to an int; otherwise, it is converted to an
250 // unsigned int. These are called the integer promotions. All
251 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000252 QualType PTy = Context.isPromotableBitField(Expr);
253 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000254 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000255 return Expr;
256 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000257 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000258 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000259 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000260 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000261 }
262
Douglas Gregora873dfc2010-02-03 00:27:59 +0000263 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 return Expr;
265}
266
Chris Lattner05faf172008-07-25 22:25:12 +0000267/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000268/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000269/// double. All other argument types are converted by UsualUnaryConversions().
270void Sema::DefaultArgumentPromotion(Expr *&Expr) {
271 QualType Ty = Expr->getType();
272 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner05faf172008-07-25 22:25:12 +0000274 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000275 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000276 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000277 return ImpCastExprToType(Expr, Context.DoubleTy,
278 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattner05faf172008-07-25 22:25:12 +0000280 UsualUnaryConversions(Expr);
281}
282
Chris Lattner312531a2009-04-12 08:11:20 +0000283/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
284/// will warn if the resulting type is not a POD type, and rejects ObjC
285/// interfaces passed by value. This returns true if the argument type is
286/// completely illegal.
287bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000288 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000290 if (Expr->getType()->isObjCInterfaceType() &&
291 DiagRuntimeBehavior(Expr->getLocStart(),
292 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
293 << Expr->getType() << CT))
294 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000295
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000296 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000297 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000298 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
299 << Expr->getType() << CT))
300 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000301
302 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000303}
304
305
Chris Lattnere7a2e912008-07-25 21:10:04 +0000306/// UsualArithmeticConversions - Performs various conversions that are common to
307/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000308/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000309/// responsible for emitting appropriate error diagnostics.
310/// FIXME: verify the conversion rules for "complex int" are consistent with
311/// GCC.
312QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
313 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000314 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000315 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000316
317 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000318
Mike Stump1eb44332009-09-09 15:08:12 +0000319 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000320 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000321 QualType lhs =
322 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000323 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000324 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000325
326 // If both types are identical, no conversion is needed.
327 if (lhs == rhs)
328 return lhs;
329
330 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
331 // The caller can deal with this (e.g. pointer + int).
332 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
333 return lhs;
334
Douglas Gregor2d833e32009-05-02 00:36:19 +0000335 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000336 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000337 if (!LHSBitfieldPromoteTy.isNull())
338 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000339 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000340 if (!RHSBitfieldPromoteTy.isNull())
341 rhs = RHSBitfieldPromoteTy;
342
Eli Friedmana95d7572009-08-19 07:44:53 +0000343 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000344 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000345 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
346 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000347 return destType;
348}
349
Chris Lattnere7a2e912008-07-25 21:10:04 +0000350//===----------------------------------------------------------------------===//
351// Semantic Analysis for various Expression Types
352//===----------------------------------------------------------------------===//
353
354
Steve Narofff69936d2007-09-16 03:34:24 +0000355/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000356/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
357/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
358/// multiple tokens. However, the common case is that StringToks points to one
359/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000360///
361Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000362Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 assert(NumStringToks && "Must have at least one string!");
364
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000365 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000367 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000368
369 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
370 for (unsigned i = 0; i != NumStringToks; ++i)
371 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000372
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000373 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000374 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000375 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000376
377 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000378 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings )
Douglas Gregor77a52232008-09-12 00:47:35 +0000379 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000380
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000381 // Get an array type for the string, according to C99 6.4.5. This includes
382 // the nul terminator character as well as the string length for pascal
383 // strings.
384 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000385 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000386 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000389 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000390 Literal.GetStringLength(),
391 Literal.AnyWide, StrTy,
392 &StringTokLocs[0],
393 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
Chris Lattner639e2d32008-10-20 05:16:36 +0000396/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
397/// CurBlock to VD should cause it to be snapshotted (as we do for auto
398/// variables defined outside the block) or false if this is not needed (e.g.
399/// for values inside the block or for globals).
400///
Douglas Gregor076ceb02010-03-01 20:44:28 +0000401/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000402/// up-to-date.
403///
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000404static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner639e2d32008-10-20 05:16:36 +0000405 ValueDecl *VD) {
406 // If the value is defined inside the block, we couldn't snapshot it even if
407 // we wanted to.
408 if (CurBlock->TheDecl == VD->getDeclContext())
409 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner639e2d32008-10-20 05:16:36 +0000411 // If this is an enum constant or function, it is constant, don't snapshot.
412 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
413 return false;
414
415 // If this is a reference to an extern, static, or global variable, no need to
416 // snapshot it.
417 // FIXME: What about 'const' variables in C++?
418 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000419 if (!Var->hasLocalStorage())
420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000422 // Blocks that have these can't be constant.
423 CurBlock->hasBlockDeclRefExprs = true;
424
425 // If we have nested blocks, the decl may be declared in an outer block (in
426 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
427 // be defined outside all of the current blocks (in which case the blocks do
428 // all get the bit). Walk the nesting chain.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000429 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
430 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000431
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000432 if (!NextBlock)
433 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // If we found the defining block for the variable, don't mark the block as
436 // having a reference outside it.
437 if (NextBlock->TheDecl == VD->getDeclContext())
438 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000440 // Otherwise, the DeclRef from the inner block causes the outer one to need
441 // a snapshot as well.
442 NextBlock->hasBlockDeclRefExprs = true;
443 }
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner639e2d32008-10-20 05:16:36 +0000445 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000446}
447
Chris Lattner639e2d32008-10-20 05:16:36 +0000448
449
Douglas Gregora2813ce2009-10-23 18:54:35 +0000450/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000451Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000452Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000453 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000456 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000457 << D->getDeclName();
458 return ExprError();
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssone41590d2009-06-24 00:10:43 +0000461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000466 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregore0762c92009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000477 return Owned(DeclRefExpr::Create(Context,
478 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
479 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000480 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000481}
482
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000483/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
484/// variable corresponding to the anonymous union or struct whose type
485/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000486static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
487 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000488 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000489 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Mike Stump390b4cc2009-05-16 07:39:55 +0000491 // FIXME: Once Decls are directly linked together, this will be an O(1)
492 // operation rather than a slow walk through DeclContext's vector (which
493 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000494 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000495 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000497 D != DEnd; ++D) {
498 if (*D == Record) {
499 // The object for the anonymous struct/union directly
500 // follows its type in the list of declarations.
501 ++D;
502 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000503 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000504 return *D;
505 }
506 }
507
508 assert(false && "Missing object for anonymous record");
509 return 0;
510}
511
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000512/// \brief Given a field that represents a member of an anonymous
513/// struct/union, build the path from that field's context to the
514/// actual member.
515///
516/// Construct the sequence of field member references we'll have to
517/// perform to get to the field in the anonymous union/struct. The
518/// list of members is built from the field outward, so traverse it
519/// backwards to go from an object in the current context to the field
520/// we found.
521///
522/// \returns The variable from which the field access should begin,
523/// for an anonymous struct/union that is not a member of another
524/// class. Otherwise, returns NULL.
525VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
526 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 assert(Field->getDeclContext()->isRecord() &&
528 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
529 && "Field must be stored inside an anonymous struct or union");
530
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000531 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 VarDecl *BaseObject = 0;
533 DeclContext *Ctx = Field->getDeclContext();
534 do {
535 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000536 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000537 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000538 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000539 else {
540 BaseObject = cast<VarDecl>(AnonObject);
541 break;
542 }
543 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000544 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000545 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000546
547 return BaseObject;
548}
549
550Sema::OwningExprResult
551Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
552 FieldDecl *Field,
553 Expr *BaseObjectExpr,
554 SourceLocation OpLoc) {
555 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000556 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000557 AnonFields);
558
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000559 // Build the expression that refers to the base object, from
560 // which we will build a sequence of member references to each
561 // of the anonymous union objects and, eventually, the field we
562 // found via name lookup.
563 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000564 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000565 if (BaseObject) {
566 // BaseObject is an anonymous struct/union variable (and is,
567 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000568 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000569 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000570 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000571 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000572 BaseQuals
573 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 } else if (BaseObjectExpr) {
575 // The caller provided the base object expression. Determine
576 // whether its a pointer and whether it adds any qualifiers to the
577 // anonymous struct/union fields we're looking into.
578 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000579 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 BaseObjectIsPointer = true;
581 ObjectType = ObjectPtr->getPointeeType();
582 }
John McCall0953e762009-09-24 19:53:00 +0000583 BaseQuals
584 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 } else {
586 // We've found a member of an anonymous struct/union that is
587 // inside a non-anonymous struct/union, so in a well-formed
588 // program our base object expression is "this".
589 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
590 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000591 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000592 = Context.getTagDeclType(
593 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
594 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000595 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000596 == Context.getCanonicalType(ThisType)) ||
597 IsDerivedFrom(ThisType, AnonFieldType)) {
598 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000599 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000600 MD->getThisType(Context),
601 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000602 BaseObjectIsPointer = true;
603 }
604 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000605 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
606 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000607 }
John McCall0953e762009-09-24 19:53:00 +0000608 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000609 }
610
Mike Stump1eb44332009-09-09 15:08:12 +0000611 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000612 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
613 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 }
615
616 // Build the implicit member references to the field of the
617 // anonymous struct/union.
618 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000619 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000620 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
621 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
622 FI != FIEnd; ++FI) {
623 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000624 Qualifiers MemberTypeQuals =
625 Context.getCanonicalType(MemberType).getQualifiers();
626
627 // CVR attributes from the base are picked up by members,
628 // except that 'mutable' members don't pick up 'const'.
629 if ((*FI)->isMutable())
630 ResultQuals.removeConst();
631
632 // GC attributes are never picked up by members.
633 ResultQuals.removeObjCGCAttr();
634
635 // TR 18037 does not allow fields to be declared with address spaces.
636 assert(!MemberTypeQuals.hasAddressSpace());
637
638 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
639 if (NewQuals != MemberTypeQuals)
640 MemberType = Context.getQualifiedType(MemberType, NewQuals);
641
Douglas Gregore0762c92009-06-19 23:52:42 +0000642 MarkDeclarationReferenced(Loc, *FI);
John McCall6bb80172010-03-30 21:47:33 +0000643 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000644 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000645 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
646 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000647 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000648 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000649 }
650
Sebastian Redlcd965b92009-01-18 18:53:16 +0000651 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000652}
653
John McCall129e2df2009-11-30 22:42:35 +0000654/// Decomposes the given name into a DeclarationName, its location, and
655/// possibly a list of template arguments.
656///
657/// If this produces template arguments, it is permitted to call
658/// DecomposeTemplateName.
659///
660/// This actually loses a lot of source location information for
661/// non-standard name kinds; we should consider preserving that in
662/// some way.
663static void DecomposeUnqualifiedId(Sema &SemaRef,
664 const UnqualifiedId &Id,
665 TemplateArgumentListInfo &Buffer,
666 DeclarationName &Name,
667 SourceLocation &NameLoc,
668 const TemplateArgumentListInfo *&TemplateArgs) {
669 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
670 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
671 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
672
673 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
674 Id.TemplateId->getTemplateArgs(),
675 Id.TemplateId->NumArgs);
676 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
677 TemplateArgsPtr.release();
678
679 TemplateName TName =
680 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
681
682 Name = SemaRef.Context.getNameForTemplate(TName);
683 NameLoc = Id.TemplateId->TemplateNameLoc;
684 TemplateArgs = &Buffer;
685 } else {
686 Name = SemaRef.GetNameFromUnqualifiedId(Id);
687 NameLoc = Id.StartLocation;
688 TemplateArgs = 0;
689 }
690}
691
692/// Decompose the given template name into a list of lookup results.
693///
694/// The unqualified ID must name a non-dependent template, which can
695/// be more easily tested by checking whether DecomposeUnqualifiedId
696/// found template arguments.
697static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
698 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
699 TemplateName TName =
700 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
701
John McCallf7a1a742009-11-24 19:00:30 +0000702 if (TemplateDecl *TD = TName.getAsTemplateDecl())
703 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000704 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
705 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
706 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000707 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000708
John McCallf7a1a742009-11-24 19:00:30 +0000709 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000710}
711
John McCall4c72d3e2010-02-08 19:26:07 +0000712/// Determines whether the given record is "fully-formed" at the given
713/// location, i.e. whether a qualified lookup into it is assured of
714/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000715static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000716 if (!Record->hasDefinition())
717 return false;
718
John McCall129e2df2009-11-30 22:42:35 +0000719 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
720 E = Record->bases_end(); I != E; ++I) {
721 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
722 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
723 if (!BaseRT) return false;
724
725 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000726 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000727 !IsFullyFormedScope(SemaRef, BaseRecord))
728 return false;
729 }
730
731 return true;
732}
733
John McCalle1599ce2009-11-30 23:50:49 +0000734/// Determines whether we can lookup this id-expression now or whether
735/// we have to wait until template instantiation is complete.
736static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000737 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000738
John McCalle1599ce2009-11-30 23:50:49 +0000739 // If the qualifier scope isn't computable, it's definitely dependent.
740 if (!DC) return true;
741
742 // If the qualifier scope doesn't name a record, we can always look into it.
743 if (!isa<CXXRecordDecl>(DC)) return false;
744
745 // We can't look into record types unless they're fully-formed.
746 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
747
John McCallaa81e162009-12-01 22:10:20 +0000748 return false;
749}
John McCalle1599ce2009-11-30 23:50:49 +0000750
John McCallaa81e162009-12-01 22:10:20 +0000751/// Determines if the given class is provably not derived from all of
752/// the prospective base classes.
753static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
754 CXXRecordDecl *Record,
755 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000756 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000757 return false;
758
Douglas Gregor952b0172010-02-11 01:04:33 +0000759 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +0000760 if (!RD) return false;
761 Record = cast<CXXRecordDecl>(RD);
762
John McCallaa81e162009-12-01 22:10:20 +0000763 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
764 E = Record->bases_end(); I != E; ++I) {
765 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
766 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
767 if (!BaseRT) return false;
768
769 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000770 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
771 return false;
772 }
773
774 return true;
775}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000776
John McCallaa81e162009-12-01 22:10:20 +0000777enum IMAKind {
778 /// The reference is definitely not an instance member access.
779 IMA_Static,
780
781 /// The reference may be an implicit instance member access.
782 IMA_Mixed,
783
784 /// The reference may be to an instance member, but it is invalid if
785 /// so, because the context is not an instance method.
786 IMA_Mixed_StaticContext,
787
788 /// The reference may be to an instance member, but it is invalid if
789 /// so, because the context is from an unrelated class.
790 IMA_Mixed_Unrelated,
791
792 /// The reference is definitely an implicit instance member access.
793 IMA_Instance,
794
795 /// The reference may be to an unresolved using declaration.
796 IMA_Unresolved,
797
798 /// The reference may be to an unresolved using declaration and the
799 /// context is not an instance method.
800 IMA_Unresolved_StaticContext,
801
802 /// The reference is to a member of an anonymous structure in a
803 /// non-class context.
804 IMA_AnonymousMember,
805
806 /// All possible referrents are instance members and the current
807 /// context is not an instance method.
808 IMA_Error_StaticContext,
809
810 /// All possible referrents are instance members of an unrelated
811 /// class.
812 IMA_Error_Unrelated
813};
814
815/// The given lookup names class member(s) and is not being used for
816/// an address-of-member expression. Classify the type of access
817/// according to whether it's possible that this reference names an
818/// instance member. This is best-effort; it is okay to
819/// conservatively answer "yes", in which case some errors will simply
820/// not be caught until template-instantiation.
821static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
822 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000823 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000824
825 bool isStaticContext =
826 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
827 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
828
829 if (R.isUnresolvableResult())
830 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
831
832 // Collect all the declaring classes of instance members we find.
833 bool hasNonInstance = false;
834 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
835 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +0000836 NamedDecl *D = *I;
837 if (D->isCXXInstanceMember()) {
John McCallaa81e162009-12-01 22:10:20 +0000838 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
839
840 // If this is a member of an anonymous record, move out to the
841 // innermost non-anonymous struct or union. If there isn't one,
842 // that's a special case.
843 while (R->isAnonymousStructOrUnion()) {
844 R = dyn_cast<CXXRecordDecl>(R->getParent());
845 if (!R) return IMA_AnonymousMember;
846 }
847 Classes.insert(R->getCanonicalDecl());
848 }
849 else
850 hasNonInstance = true;
851 }
852
853 // If we didn't find any instance members, it can't be an implicit
854 // member reference.
855 if (Classes.empty())
856 return IMA_Static;
857
858 // If the current context is not an instance method, it can't be
859 // an implicit member reference.
860 if (isStaticContext)
861 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
862
863 // If we can prove that the current context is unrelated to all the
864 // declaring classes, it can't be an implicit member reference (in
865 // which case it's an error if any of those members are selected).
866 if (IsProvablyNotDerivedFrom(SemaRef,
867 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
868 Classes))
869 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
870
871 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
872}
873
874/// Diagnose a reference to a field with no object available.
875static void DiagnoseInstanceReference(Sema &SemaRef,
876 const CXXScopeSpec &SS,
877 const LookupResult &R) {
878 SourceLocation Loc = R.getNameLoc();
879 SourceRange Range(Loc);
880 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
881
882 if (R.getAsSingle<FieldDecl>()) {
883 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
884 if (MD->isStatic()) {
885 // "invalid use of member 'x' in static member function"
886 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
887 << Range << R.getLookupName();
888 return;
889 }
890 }
891
892 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
893 << R.getLookupName() << Range;
894 return;
895 }
896
897 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000898}
899
John McCall578b69b2009-12-16 08:11:27 +0000900/// Diagnose an empty lookup.
901///
902/// \return false if new lookup candidates were found
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000903bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS,
John McCall578b69b2009-12-16 08:11:27 +0000904 LookupResult &R) {
905 DeclarationName Name = R.getLookupName();
906
John McCall578b69b2009-12-16 08:11:27 +0000907 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000908 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000909 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
910 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000911 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000912 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000913 diagnostic_suggest = diag::err_undeclared_use_suggest;
914 }
John McCall578b69b2009-12-16 08:11:27 +0000915
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000916 // If the original lookup was an unqualified lookup, fake an
917 // unqualified lookup. This is useful when (for example) the
918 // original lookup would not have found something because it was a
919 // dependent name.
920 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
921 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000922 if (isa<CXXRecordDecl>(DC)) {
923 LookupQualifiedName(R, DC);
924
925 if (!R.empty()) {
926 // Don't give errors about ambiguities in this lookup.
927 R.suppressDiagnostics();
928
929 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
930 bool isInstance = CurMethod &&
931 CurMethod->isInstance() &&
932 DC == CurMethod->getParent();
933
934 // Give a code modification hint to insert 'this->'.
935 // TODO: fixit for inserting 'Base<T>::' in the other cases.
936 // Actually quite difficult!
937 if (isInstance)
938 Diag(R.getNameLoc(), diagnostic) << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000939 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
John McCall578b69b2009-12-16 08:11:27 +0000940 else
941 Diag(R.getNameLoc(), diagnostic) << Name;
942
943 // Do we really want to note all of these?
944 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
945 Diag((*I)->getLocation(), diag::note_dependent_var_use);
946
947 // Tell the callee to try to recover.
948 return false;
949 }
950 }
951 }
952
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000953 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000954 DeclarationName Corrected;
955 if (S && (Corrected = CorrectTypo(R, S, &SS))) {
956 if (!R.empty()) {
957 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
958 if (SS.isEmpty())
959 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
960 << FixItHint::CreateReplacement(R.getNameLoc(),
961 R.getLookupName().getAsString());
962 else
963 Diag(R.getNameLoc(), diag::err_no_member_suggest)
964 << Name << computeDeclContext(SS, false) << R.getLookupName()
965 << SS.getRange()
966 << FixItHint::CreateReplacement(R.getNameLoc(),
967 R.getLookupName().getAsString());
968 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
969 Diag(ND->getLocation(), diag::note_previous_decl)
970 << ND->getDeclName();
971
972 // Tell the callee to try to recover.
973 return false;
974 }
975
976 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
977 // FIXME: If we ended up with a typo for a type name or
978 // Objective-C class name, we're in trouble because the parser
979 // is in the wrong place to recover. Suggest the typo
980 // correction, but don't make it a fix-it since we're not going
981 // to recover well anyway.
982 if (SS.isEmpty())
983 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
984 else
985 Diag(R.getNameLoc(), diag::err_no_member_suggest)
986 << Name << computeDeclContext(SS, false) << R.getLookupName()
987 << SS.getRange();
988
989 // Don't try to recover; it won't work.
990 return true;
991 }
992 } else {
993 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
994 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +0000995 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +0000996 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000997 else
Douglas Gregord203a162010-01-01 00:15:04 +0000998 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +0000999 << Name << computeDeclContext(SS, false) << Corrected
1000 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001001 return true;
1002 }
Douglas Gregord203a162010-01-01 00:15:04 +00001003 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001004 }
1005
1006 // Emit a special diagnostic for failed member lookups.
1007 // FIXME: computing the declaration context might fail here (?)
1008 if (!SS.isEmpty()) {
1009 Diag(R.getNameLoc(), diag::err_no_member)
1010 << Name << computeDeclContext(SS, false)
1011 << SS.getRange();
1012 return true;
1013 }
1014
John McCall578b69b2009-12-16 08:11:27 +00001015 // Give up, we can't recover.
1016 Diag(R.getNameLoc(), diagnostic) << Name;
1017 return true;
1018}
1019
John McCallf7a1a742009-11-24 19:00:30 +00001020Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001021 CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001022 UnqualifiedId &Id,
1023 bool HasTrailingLParen,
1024 bool isAddressOfOperand) {
1025 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1026 "cannot be direct & operand and have a trailing lparen");
1027
1028 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001029 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001030
John McCall129e2df2009-11-30 22:42:35 +00001031 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001032
1033 // Decompose the UnqualifiedId into the following data.
1034 DeclarationName Name;
1035 SourceLocation NameLoc;
1036 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001037 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1038 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001039
Douglas Gregor10c42622008-11-18 15:03:34 +00001040 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001041
John McCallf7a1a742009-11-24 19:00:30 +00001042 // C++ [temp.dep.expr]p3:
1043 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001044 // -- an identifier that was declared with a dependent type,
1045 // (note: handled after lookup)
1046 // -- a template-id that is dependent,
1047 // (note: handled in BuildTemplateIdExpr)
1048 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001049 // -- a nested-name-specifier that contains a class-name that
1050 // names a dependent type.
1051 // Determine whether this is a member of an unknown specialization;
1052 // we need to handle these differently.
Douglas Gregor48026d22010-01-11 18:40:55 +00001053 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1054 Name.getCXXNameType()->isDependentType()) ||
1055 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCallf7a1a742009-11-24 19:00:30 +00001056 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001057 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001058 TemplateArgs);
1059 }
John McCallba135432009-11-21 08:51:07 +00001060
John McCallf7a1a742009-11-24 19:00:30 +00001061 // Perform the required lookup.
1062 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1063 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001064 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001065 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001066 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001067 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1068 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001069
John McCallf7a1a742009-11-24 19:00:30 +00001070 // If this reference is in an Objective-C method, then we need to do
1071 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001072 if (IvarLookupFollowUp) {
1073 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001074 if (E.isInvalid())
1075 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001076
John McCallf7a1a742009-11-24 19:00:30 +00001077 Expr *Ex = E.takeAs<Expr>();
1078 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001079 }
Chris Lattner8a934232008-03-31 00:36:02 +00001080 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001081
John McCallf7a1a742009-11-24 19:00:30 +00001082 if (R.isAmbiguous())
1083 return ExprError();
1084
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001085 // Determine whether this name might be a candidate for
1086 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001087 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001088
John McCallf7a1a742009-11-24 19:00:30 +00001089 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001091 // in C90, extension in C99, forbidden in C++).
1092 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1093 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1094 if (D) R.addDecl(D);
1095 }
1096
1097 // If this name wasn't predeclared and if this is not a function
1098 // call, diagnose the problem.
1099 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001100 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001101 return ExprError();
1102
1103 assert(!R.empty() &&
1104 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001105
1106 // If we found an Objective-C instance variable, let
1107 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001108 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001109 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1110 R.clear();
1111 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1112 assert(E.isInvalid() || E.get());
1113 return move(E);
1114 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 }
1116 }
Mike Stump1eb44332009-09-09 15:08:12 +00001117
John McCallf7a1a742009-11-24 19:00:30 +00001118 // This is guaranteed from this point on.
1119 assert(!R.empty() || ADL);
1120
1121 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001122 // Warn about constructs like:
1123 // if (void *X = foo()) { ... } else { X }.
1124 // In the else block, the pointer is always false.
Douglas Gregor751f9a42009-06-30 15:47:41 +00001125 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1126 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001127 while (CheckS && CheckS->getControlParent()) {
Chris Lattner966c78b2010-04-12 06:12:50 +00001128 if ((CheckS->getFlags() & Scope::ElseScope) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001129 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001130 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001131 << Var->getDeclName()
Chris Lattner966c78b2010-04-12 06:12:50 +00001132 << (Var->getType()->isPointerType() ? 2 :
1133 Var->getType()->isBooleanType() ? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001134 break;
1135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001137 // Move to the parent of this scope.
1138 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001139 }
1140 }
John McCallf7a1a742009-11-24 19:00:30 +00001141 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001142 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1143 // C99 DR 316 says that, if a function type comes from a
1144 // function definition (without a prototype), that type is only
1145 // used for checking compatibility. Therefore, when referencing
1146 // the function, we pretend that we don't have the full function
1147 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001148 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001149 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001150
Douglas Gregor751f9a42009-06-30 15:47:41 +00001151 QualType T = Func->getType();
1152 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001153 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001154 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001155 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001156 }
1157 }
Mike Stump1eb44332009-09-09 15:08:12 +00001158
John McCallaa81e162009-12-01 22:10:20 +00001159 // Check whether this might be a C++ implicit instance member access.
1160 // C++ [expr.prim.general]p6:
1161 // Within the definition of a non-static member function, an
1162 // identifier that names a non-static member is transformed to a
1163 // class member access expression.
1164 // But note that &SomeClass::foo is grammatically distinct, even
1165 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001166 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001167 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001168 if (!isAbstractMemberPointer)
1169 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001170 }
1171
John McCallf7a1a742009-11-24 19:00:30 +00001172 if (TemplateArgs)
1173 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001174
John McCallf7a1a742009-11-24 19:00:30 +00001175 return BuildDeclarationNameExpr(SS, R, ADL);
1176}
1177
John McCall3b4294e2009-12-16 12:17:52 +00001178/// Builds an expression which might be an implicit member expression.
1179Sema::OwningExprResult
1180Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1181 LookupResult &R,
1182 const TemplateArgumentListInfo *TemplateArgs) {
1183 switch (ClassifyImplicitMemberAccess(*this, R)) {
1184 case IMA_Instance:
1185 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1186
1187 case IMA_AnonymousMember:
1188 assert(R.isSingleResult());
1189 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1190 R.getAsSingle<FieldDecl>());
1191
1192 case IMA_Mixed:
1193 case IMA_Mixed_Unrelated:
1194 case IMA_Unresolved:
1195 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1196
1197 case IMA_Static:
1198 case IMA_Mixed_StaticContext:
1199 case IMA_Unresolved_StaticContext:
1200 if (TemplateArgs)
1201 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1202 return BuildDeclarationNameExpr(SS, R, false);
1203
1204 case IMA_Error_StaticContext:
1205 case IMA_Error_Unrelated:
1206 DiagnoseInstanceReference(*this, SS, R);
1207 return ExprError();
1208 }
1209
1210 llvm_unreachable("unexpected instance member access kind");
1211 return ExprError();
1212}
1213
John McCall129e2df2009-11-30 22:42:35 +00001214/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1215/// declaration name, generally during template instantiation.
1216/// There's a large number of things which don't need to be done along
1217/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001218Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001219Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001220 DeclarationName Name,
1221 SourceLocation NameLoc) {
1222 DeclContext *DC;
1223 if (!(DC = computeDeclContext(SS, false)) ||
1224 DC->isDependentContext() ||
1225 RequireCompleteDeclContext(SS))
1226 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1227
1228 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1229 LookupQualifiedName(R, DC);
1230
1231 if (R.isAmbiguous())
1232 return ExprError();
1233
1234 if (R.empty()) {
1235 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1236 return ExprError();
1237 }
1238
1239 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1240}
1241
1242/// LookupInObjCMethod - The parser has read a name in, and Sema has
1243/// detected that we're currently inside an ObjC method. Perform some
1244/// additional lookup.
1245///
1246/// Ideally, most of this would be done by lookup, but there's
1247/// actually quite a lot of extra work involved.
1248///
1249/// Returns a null sentinel to indicate trivial success.
1250Sema::OwningExprResult
1251Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001252 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001253 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001254 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Chris Lattnereb483eb2010-04-11 08:28:14 +00001255
John McCallf7a1a742009-11-24 19:00:30 +00001256 // There are two cases to handle here. 1) scoped lookup could have failed,
1257 // in which case we should look for an ivar. 2) scoped lookup could have
1258 // found a decl, but that decl is outside the current instance method (i.e.
1259 // a global variable). In these two cases, we do a lookup for an ivar with
1260 // this name, if the lookup sucedes, we replace it our current decl.
1261
1262 // If we're in a class method, we don't normally want to look for
1263 // ivars. But if we don't find anything else, and there's an
1264 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001265 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001266
1267 bool LookForIvars;
1268 if (Lookup.empty())
1269 LookForIvars = true;
1270 else if (IsClassMethod)
1271 LookForIvars = false;
1272 else
1273 LookForIvars = (Lookup.isSingleResult() &&
1274 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001275 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001276 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001277 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001278 ObjCInterfaceDecl *ClassDeclared;
1279 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1280 // Diagnose using an ivar in a class method.
1281 if (IsClassMethod)
1282 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1283 << IV->getDeclName());
1284
1285 // If we're referencing an invalid decl, just return this as a silent
1286 // error node. The error diagnostic was already emitted on the decl.
1287 if (IV->isInvalidDecl())
1288 return ExprError();
1289
1290 // Check if referencing a field with __attribute__((deprecated)).
1291 if (DiagnoseUseOfDecl(IV, Loc))
1292 return ExprError();
1293
1294 // Diagnose the use of an ivar outside of the declaring class.
1295 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1296 ClassDeclared != IFace)
1297 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1298
1299 // FIXME: This should use a new expr for a direct reference, don't
1300 // turn this into Self->ivar, just return a BareIVarExpr or something.
1301 IdentifierInfo &II = Context.Idents.get("self");
1302 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001303 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001304 CXXScopeSpec SelfScopeSpec;
1305 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1306 SelfName, false, false);
1307 MarkDeclarationReferenced(Loc, IV);
1308 return Owned(new (Context)
1309 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1310 SelfExpr.takeAs<Expr>(), true, true));
1311 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001312 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001313 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001314 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001315 ObjCInterfaceDecl *ClassDeclared;
1316 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1317 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1318 IFace == ClassDeclared)
1319 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1320 }
1321 }
1322
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001323 if (Lookup.empty() && II && AllowBuiltinCreation) {
1324 // FIXME. Consolidate this with similar code in LookupName.
1325 if (unsigned BuiltinID = II->getBuiltinID()) {
1326 if (!(getLangOptions().CPlusPlus &&
1327 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1328 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1329 S, Lookup.isForRedeclaration(),
1330 Lookup.getNameLoc());
1331 if (D) Lookup.addDecl(D);
1332 }
1333 }
1334 }
John McCallf7a1a742009-11-24 19:00:30 +00001335 // Sentinel value saying that we didn't do anything special.
1336 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001337}
John McCallba135432009-11-21 08:51:07 +00001338
John McCall6bb80172010-03-30 21:47:33 +00001339/// \brief Cast a base object to a member's actual type.
1340///
1341/// Logically this happens in three phases:
1342///
1343/// * First we cast from the base type to the naming class.
1344/// The naming class is the class into which we were looking
1345/// when we found the member; it's the qualifier type if a
1346/// qualifier was provided, and otherwise it's the base type.
1347///
1348/// * Next we cast from the naming class to the declaring class.
1349/// If the member we found was brought into a class's scope by
1350/// a using declaration, this is that class; otherwise it's
1351/// the class declaring the member.
1352///
1353/// * Finally we cast from the declaring class to the "true"
1354/// declaring class of the member. This conversion does not
1355/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001356bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001357Sema::PerformObjectMemberConversion(Expr *&From,
1358 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001359 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001360 NamedDecl *Member) {
1361 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1362 if (!RD)
1363 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001364
Douglas Gregor5fccd362010-03-03 23:55:11 +00001365 QualType DestRecordType;
1366 QualType DestType;
1367 QualType FromRecordType;
1368 QualType FromType = From->getType();
1369 bool PointerConversions = false;
1370 if (isa<FieldDecl>(Member)) {
1371 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001372
Douglas Gregor5fccd362010-03-03 23:55:11 +00001373 if (FromType->getAs<PointerType>()) {
1374 DestType = Context.getPointerType(DestRecordType);
1375 FromRecordType = FromType->getPointeeType();
1376 PointerConversions = true;
1377 } else {
1378 DestType = DestRecordType;
1379 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001380 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001381 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1382 if (Method->isStatic())
1383 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001384
Douglas Gregor5fccd362010-03-03 23:55:11 +00001385 DestType = Method->getThisType(Context);
1386 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001387
Douglas Gregor5fccd362010-03-03 23:55:11 +00001388 if (FromType->getAs<PointerType>()) {
1389 FromRecordType = FromType->getPointeeType();
1390 PointerConversions = true;
1391 } else {
1392 FromRecordType = FromType;
1393 DestType = DestRecordType;
1394 }
1395 } else {
1396 // No conversion necessary.
1397 return false;
1398 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001399
Douglas Gregor5fccd362010-03-03 23:55:11 +00001400 if (DestType->isDependentType() || FromType->isDependentType())
1401 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001402
Douglas Gregor5fccd362010-03-03 23:55:11 +00001403 // If the unqualified types are the same, no conversion is necessary.
1404 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1405 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001406
John McCall6bb80172010-03-30 21:47:33 +00001407 SourceRange FromRange = From->getSourceRange();
1408 SourceLocation FromLoc = FromRange.getBegin();
1409
Douglas Gregor5fccd362010-03-03 23:55:11 +00001410 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001411 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001412 // class name.
1413 //
1414 // If the member was a qualified name and the qualified referred to a
1415 // specific base subobject type, we'll cast to that intermediate type
1416 // first and then to the object in which the member is declared. That allows
1417 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1418 //
1419 // class Base { public: int x; };
1420 // class Derived1 : public Base { };
1421 // class Derived2 : public Base { };
1422 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1423 //
1424 // void VeryDerived::f() {
1425 // x = 17; // error: ambiguous base subobjects
1426 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1427 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001428 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001429 QualType QType = QualType(Qualifier->getAsType(), 0);
1430 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1431 assert(QType->isRecordType() && "lookup done with non-record type");
1432
1433 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1434
1435 // In C++98, the qualifier type doesn't actually have to be a base
1436 // type of the object type, in which case we just ignore it.
1437 // Otherwise build the appropriate casts.
1438 if (IsDerivedFrom(FromRecordType, QRecordType)) {
1439 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1440 FromLoc, FromRange))
1441 return true;
1442
Douglas Gregor5fccd362010-03-03 23:55:11 +00001443 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001444 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001445 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00001446 /*FIXME: InheritancePath=*/0,
1447 /*isLvalue=*/!PointerConversions);
John McCall6bb80172010-03-30 21:47:33 +00001448
1449 FromType = QType;
1450 FromRecordType = QRecordType;
1451
1452 // If the qualifier type was the same as the destination type,
1453 // we're done.
1454 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1455 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001456 }
1457 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001458
John McCall6bb80172010-03-30 21:47:33 +00001459 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001460
John McCall6bb80172010-03-30 21:47:33 +00001461 // If we actually found the member through a using declaration, cast
1462 // down to the using declaration's type.
1463 //
1464 // Pointer equality is fine here because only one declaration of a
1465 // class ever has member declarations.
1466 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1467 assert(isa<UsingShadowDecl>(FoundDecl));
1468 QualType URecordType = Context.getTypeDeclType(
1469 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1470
1471 // We only need to do this if the naming-class to declaring-class
1472 // conversion is non-trivial.
1473 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1474 assert(IsDerivedFrom(FromRecordType, URecordType));
1475 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1476 FromLoc, FromRange))
1477 return true;
1478
1479 QualType UType = URecordType;
1480 if (PointerConversions)
1481 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001482 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00001483 /*FIXME: InheritancePath=*/0,
John McCall6bb80172010-03-30 21:47:33 +00001484 /*isLvalue*/ !PointerConversions);
1485 FromType = UType;
1486 FromRecordType = URecordType;
1487 }
1488
1489 // We don't do access control for the conversion from the
1490 // declaring class to the true declaring class.
1491 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001492 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001493
Douglas Gregor5fccd362010-03-03 23:55:11 +00001494 if (CheckDerivedToBaseConversion(FromRecordType,
1495 DestRecordType,
John McCall6bb80172010-03-30 21:47:33 +00001496 FromLoc,
1497 FromRange,
1498 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001499 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001500
John McCall23cba802010-03-30 23:58:03 +00001501 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00001502 /*FIXME: InheritancePath=*/0,
1503 /*isLvalue=*/!PointerConversions);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001504 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001505}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001506
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001507/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001508static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001509 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001510 DeclAccessPair FoundDecl,
1511 SourceLocation Loc, QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001512 const TemplateArgumentListInfo *TemplateArgs = 0) {
1513 NestedNameSpecifier *Qualifier = 0;
1514 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001515 if (SS.isSet()) {
1516 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1517 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
John McCallf7a1a742009-11-24 19:00:30 +00001520 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
John McCall6bb80172010-03-30 21:47:33 +00001521 Member, FoundDecl, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001522}
1523
John McCallaa81e162009-12-01 22:10:20 +00001524/// Builds an implicit member access expression. The current context
1525/// is known to be an instance method, and the given unqualified lookup
1526/// set is known to contain only instance members, at least one of which
1527/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001528Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001529Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1530 LookupResult &R,
1531 const TemplateArgumentListInfo *TemplateArgs,
1532 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001533 assert(!R.empty() && !R.isAmbiguous());
1534
John McCallba135432009-11-21 08:51:07 +00001535 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001536
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001537 // We may have found a field within an anonymous union or struct
1538 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001539 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001540 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001541 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001542 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001543 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001544
John McCallaa81e162009-12-01 22:10:20 +00001545 // If this is known to be an instance access, go ahead and build a
1546 // 'this' expression now.
1547 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1548 Expr *This = 0; // null signifies implicit access
1549 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001550 SourceLocation Loc = R.getNameLoc();
1551 if (SS.getRange().isValid())
1552 Loc = SS.getRange().getBegin();
1553 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001554 }
1555
John McCallaa81e162009-12-01 22:10:20 +00001556 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1557 /*OpLoc*/ SourceLocation(),
1558 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001559 SS,
1560 /*FirstQualifierInScope*/ 0,
1561 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001562}
1563
John McCallf7a1a742009-11-24 19:00:30 +00001564bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001565 const LookupResult &R,
1566 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001567 // Only when used directly as the postfix-expression of a call.
1568 if (!HasTrailingLParen)
1569 return false;
1570
1571 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001572 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001573 return false;
1574
1575 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001576 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001577 return false;
1578
1579 // Turn off ADL when we find certain kinds of declarations during
1580 // normal lookup:
1581 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1582 NamedDecl *D = *I;
1583
1584 // C++0x [basic.lookup.argdep]p3:
1585 // -- a declaration of a class member
1586 // Since using decls preserve this property, we check this on the
1587 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001588 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001589 return false;
1590
1591 // C++0x [basic.lookup.argdep]p3:
1592 // -- a block-scope function declaration that is not a
1593 // using-declaration
1594 // NOTE: we also trigger this for function templates (in fact, we
1595 // don't check the decl type at all, since all other decl types
1596 // turn off ADL anyway).
1597 if (isa<UsingShadowDecl>(D))
1598 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1599 else if (D->getDeclContext()->isFunctionOrMethod())
1600 return false;
1601
1602 // C++0x [basic.lookup.argdep]p3:
1603 // -- a declaration that is neither a function or a function
1604 // template
1605 // And also for builtin functions.
1606 if (isa<FunctionDecl>(D)) {
1607 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1608
1609 // But also builtin functions.
1610 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1611 return false;
1612 } else if (!isa<FunctionTemplateDecl>(D))
1613 return false;
1614 }
1615
1616 return true;
1617}
1618
1619
John McCallba135432009-11-21 08:51:07 +00001620/// Diagnoses obvious problems with the use of the given declaration
1621/// as an expression. This is only actually called for lookups that
1622/// were not overloaded, and it doesn't promise that the declaration
1623/// will in fact be used.
1624static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1625 if (isa<TypedefDecl>(D)) {
1626 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1627 return true;
1628 }
1629
1630 if (isa<ObjCInterfaceDecl>(D)) {
1631 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1632 return true;
1633 }
1634
1635 if (isa<NamespaceDecl>(D)) {
1636 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1637 return true;
1638 }
1639
1640 return false;
1641}
1642
1643Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001644Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001645 LookupResult &R,
1646 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001647 // If this is a single, fully-resolved result and we don't need ADL,
1648 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001649 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCall5b3f9132009-11-22 01:44:31 +00001650 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001651
1652 // We only need to check the declaration if there's exactly one
1653 // result, because in the overloaded case the results can only be
1654 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001655 if (R.isSingleResult() &&
1656 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001657 return ExprError();
1658
John McCallc373d482010-01-27 01:50:18 +00001659 // Otherwise, just build an unresolved lookup expression. Suppress
1660 // any lookup-related diagnostics; we'll hash these out later, when
1661 // we've picked a target.
1662 R.suppressDiagnostics();
1663
John McCallf7a1a742009-11-24 19:00:30 +00001664 bool Dependent
1665 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001666 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001667 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001668 (NestedNameSpecifier*) SS.getScopeRep(),
1669 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001670 R.getLookupName(), R.getNameLoc(),
1671 NeedsADL, R.isOverloadedResult());
John McCallc373d482010-01-27 01:50:18 +00001672 ULE->addDecls(R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001673
1674 return Owned(ULE);
1675}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001676
John McCallba135432009-11-21 08:51:07 +00001677
1678/// \brief Complete semantic analysis for a reference to the given declaration.
1679Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001680Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001681 SourceLocation Loc, NamedDecl *D) {
1682 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001683 assert(!isa<FunctionTemplateDecl>(D) &&
1684 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001685
1686 if (CheckDeclInExpr(*this, Loc, D))
1687 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001688
Douglas Gregor9af2f522009-12-01 16:58:18 +00001689 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1690 // Specifically diagnose references to class templates that are missing
1691 // a template argument list.
1692 Diag(Loc, diag::err_template_decl_ref)
1693 << Template << SS.getRange();
1694 Diag(Template->getLocation(), diag::note_template_decl_here);
1695 return ExprError();
1696 }
1697
1698 // Make sure that we're referring to a value.
1699 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1700 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001701 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001702 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001703 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001704 return ExprError();
1705 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001706
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001707 // Check whether this declaration can be used. Note that we suppress
1708 // this check when we're going to perform argument-dependent lookup
1709 // on this function name, because this might not be the function
1710 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001711 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001712 return ExprError();
1713
Steve Naroffdd972f22008-09-05 22:11:13 +00001714 // Only create DeclRefExpr's for valid Decl's.
1715 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001716 return ExprError();
1717
Chris Lattner639e2d32008-10-20 05:16:36 +00001718 // If the identifier reference is inside a block, and it refers to a value
1719 // that is outside the block, create a BlockDeclRefExpr instead of a
1720 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1721 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001722 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001723 // We do not do this for things like enum constants, global variables, etc,
1724 // as they do not get snapshotted.
1725 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001726 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001727 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001728 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1729 Diag(Loc, diag::err_ref_vm_type);
1730 Diag(D->getLocation(), diag::note_declared_at);
1731 return ExprError();
1732 }
1733
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001734 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001735 Diag(Loc, diag::err_ref_array_type);
1736 Diag(D->getLocation(), diag::note_declared_at);
1737 return ExprError();
1738 }
1739
Douglas Gregore0762c92009-06-19 23:52:42 +00001740 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001741 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001742 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001743 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001744 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001745 // This is to record that a 'const' was actually synthesize and added.
1746 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001747 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Eli Friedman5fdeae12009-03-22 23:00:19 +00001749 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001750 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001751 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001752 }
1753 // If this reference is not in a block or if the referenced variable is
1754 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001755
John McCallf7a1a742009-11-24 19:00:30 +00001756 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001757}
1758
Sebastian Redlcd965b92009-01-18 18:53:16 +00001759Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1760 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001761 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001762
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001764 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001765 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1766 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1767 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001769
Chris Lattnerfa28b302008-01-12 08:14:25 +00001770 // Pre-defined identifiers are of type char[x], where x is the length of the
1771 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Anders Carlsson3a082d82009-09-08 18:24:21 +00001773 Decl *currentDecl = getCurFunctionOrMethodDecl();
1774 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001775 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001776 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001777 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001778
Anders Carlsson773f3972009-09-11 01:22:35 +00001779 QualType ResTy;
1780 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1781 ResTy = Context.DependentTy;
1782 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001783 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001784
Anders Carlsson773f3972009-09-11 01:22:35 +00001785 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001786 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001787 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1788 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001789 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001790}
1791
Sebastian Redlcd965b92009-01-18 18:53:16 +00001792Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001794 bool Invalid = false;
1795 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1796 if (Invalid)
1797 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001798
Benjamin Kramerddeea562010-02-27 13:44:12 +00001799 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1800 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001802 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001803
Chris Lattnere8337df2009-12-30 21:19:39 +00001804 QualType Ty;
1805 if (!getLangOptions().CPlusPlus)
1806 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1807 else if (Literal.isWide())
1808 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001809 else if (Literal.isMultiChar())
1810 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001811 else
1812 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001813
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001814 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1815 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001816 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001817}
1818
Sebastian Redlcd965b92009-01-18 18:53:16 +00001819Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1820 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1822 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001823 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001824 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001825 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001826 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 }
Ted Kremenek28396602009-01-13 23:19:12 +00001828
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001830 // Add padding so that NumericLiteralParser can overread by one character.
1831 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001835 bool Invalid = false;
1836 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1837 if (Invalid)
1838 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001839
Mike Stump1eb44332009-09-09 15:08:12 +00001840 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 Tok.getLocation(), PP);
1842 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001843 return ExprError();
1844
Chris Lattner5d661452007-08-26 03:42:43 +00001845 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001846
Chris Lattner5d661452007-08-26 03:42:43 +00001847 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001848 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001849 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001850 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001851 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001852 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001853 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001854 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001855
1856 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1857
John McCall94c939d2009-12-24 09:08:04 +00001858 using llvm::APFloat;
1859 APFloat Val(Format);
1860
1861 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001862
1863 // Overflow is always an error, but underflow is only an error if
1864 // we underflowed to zero (APFloat reports denormals as underflow).
1865 if ((result & APFloat::opOverflow) ||
1866 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001867 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001868 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001869 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001870 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001871 APFloat::getLargest(Format).toString(buffer);
1872 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001873 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001874 APFloat::getSmallest(Format).toString(buffer);
1875 }
1876
1877 Diag(Tok.getLocation(), diagnostic)
1878 << Ty
1879 << llvm::StringRef(buffer.data(), buffer.size());
1880 }
1881
1882 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001883 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001884
Chris Lattner5d661452007-08-26 03:42:43 +00001885 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001886 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001887 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001888 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001889
Neil Boothb9449512007-08-29 22:00:19 +00001890 // long long is a C99 feature.
1891 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001892 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001893 Diag(Tok.getLocation(), diag::ext_longlong);
1894
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001896 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001897
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 if (Literal.GetIntegerValue(ResultVal)) {
1899 // If this value didn't fit into uintmax_t, warn and force to ull.
1900 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001901 Ty = Context.UnsignedLongLongTy;
1902 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001903 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 } else {
1905 // If this value fits into a ULL, try to figure out what else it fits into
1906 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1909 // be an unsigned int.
1910 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1911
1912 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001913 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001914 if (!Literal.isLong && !Literal.isLongLong) {
1915 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001916 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001917
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 // Does it fit in a unsigned int?
1919 if (ResultVal.isIntN(IntSize)) {
1920 // Does it fit in a signed int?
1921 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001922 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001924 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001925 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001928
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001930 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001931 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 // Does it fit in a unsigned long?
1934 if (ResultVal.isIntN(LongSize)) {
1935 // Does it fit in a signed long?
1936 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001937 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001939 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001940 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001942 }
1943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001945 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001946 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // Does it fit in a unsigned long long?
1949 if (ResultVal.isIntN(LongLongSize)) {
1950 // Does it fit in a signed long long?
1951 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001952 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001954 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001955 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 }
1957 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // If we still couldn't decide a type, we probably have something that
1960 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001961 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001963 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001964 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001966
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001967 if (ResultVal.getBitWidth() != Width)
1968 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001970 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001972
Chris Lattner5d661452007-08-26 03:42:43 +00001973 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1974 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001975 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001976 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001977
1978 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001979}
1980
Sebastian Redlcd965b92009-01-18 18:53:16 +00001981Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1982 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001983 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001984 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001985 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001986}
1987
1988/// The UsualUnaryConversions() function is *not* called by this routine.
1989/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001990bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001991 SourceLocation OpLoc,
1992 const SourceRange &ExprRange,
1993 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001994 if (exprType->isDependentType())
1995 return false;
1996
Sebastian Redl5d484e82009-11-23 17:18:46 +00001997 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1998 // the result is the size of the referenced type."
1999 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2000 // result shall be the alignment of the referenced type."
2001 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2002 exprType = Ref->getPointeeType();
2003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002005 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002006 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002007 if (isSizeof)
2008 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2009 return false;
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Chris Lattner1efaa952009-04-24 00:30:45 +00002012 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002013 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002014 Diag(OpLoc, diag::ext_sizeof_void_type)
2015 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002016 return false;
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Chris Lattner1efaa952009-04-24 00:30:45 +00002019 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002020 PDiag(diag::err_sizeof_alignof_incomplete_type)
2021 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002022 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Chris Lattner1efaa952009-04-24 00:30:45 +00002024 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00002025 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002026 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002027 << exprType << isSizeof << ExprRange;
2028 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Chris Lattner1efaa952009-04-24 00:30:45 +00002031 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002032}
2033
Chris Lattner31e21e02009-01-24 20:17:12 +00002034bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2035 const SourceRange &ExprRange) {
2036 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002037
Mike Stump1eb44332009-09-09 15:08:12 +00002038 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002039 if (isa<DeclRefExpr>(E))
2040 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002041
2042 // Cannot know anything else if the expression is dependent.
2043 if (E->isTypeDependent())
2044 return false;
2045
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002046 if (E->getBitField()) {
2047 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2048 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002049 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002050
2051 // Alignment of a field access is always okay, so long as it isn't a
2052 // bit-field.
2053 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002054 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002055 return false;
2056
Chris Lattner31e21e02009-01-24 20:17:12 +00002057 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2058}
2059
Douglas Gregorba498172009-03-13 21:01:28 +00002060/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002061Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002062Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002063 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002064 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002065 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002066 return ExprError();
2067
John McCalla93c9342009-12-07 02:54:59 +00002068 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002069
Douglas Gregorba498172009-03-13 21:01:28 +00002070 if (!T->isDependentType() &&
2071 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2072 return ExprError();
2073
2074 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002075 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002076 Context.getSizeType(), OpLoc,
2077 R.getEnd()));
2078}
2079
2080/// \brief Build a sizeof or alignof expression given an expression
2081/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002082Action::OwningExprResult
2083Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002084 bool isSizeOf, SourceRange R) {
2085 // Verify that the operand is valid.
2086 bool isInvalid = false;
2087 if (E->isTypeDependent()) {
2088 // Delay type-checking for type-dependent expressions.
2089 } else if (!isSizeOf) {
2090 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002091 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002092 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2093 isInvalid = true;
2094 } else {
2095 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2096 }
2097
2098 if (isInvalid)
2099 return ExprError();
2100
2101 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2102 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2103 Context.getSizeType(), OpLoc,
2104 R.getEnd()));
2105}
2106
Sebastian Redl05189992008-11-11 17:56:53 +00002107/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2108/// the same for @c alignof and @c __alignof
2109/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002110Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002111Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2112 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002114 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002115
Sebastian Redl05189992008-11-11 17:56:53 +00002116 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002117 TypeSourceInfo *TInfo;
2118 (void) GetTypeFromParser(TyOrEx, &TInfo);
2119 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002120 }
Sebastian Redl05189992008-11-11 17:56:53 +00002121
Douglas Gregorba498172009-03-13 21:01:28 +00002122 Expr *ArgEx = (Expr *)TyOrEx;
2123 Action::OwningExprResult Result
2124 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2125
2126 if (Result.isInvalid())
2127 DeleteExpr(ArgEx);
2128
2129 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002130}
2131
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002132QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002133 if (V->isTypeDependent())
2134 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Chris Lattnercc26ed72007-08-26 05:39:26 +00002136 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002137 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002138 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Chris Lattnercc26ed72007-08-26 05:39:26 +00002140 // Otherwise they pass through real integer and floating point types here.
2141 if (V->getType()->isArithmeticType())
2142 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Chris Lattnercc26ed72007-08-26 05:39:26 +00002144 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002145 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2146 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002147 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002148}
2149
2150
Reid Spencer5f016e22007-07-11 17:01:13 +00002151
Sebastian Redl0eb23302009-01-19 00:08:26 +00002152Action::OwningExprResult
2153Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2154 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 UnaryOperator::Opcode Opc;
2156 switch (Kind) {
2157 default: assert(0 && "Unknown unary op!");
2158 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2159 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2160 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002161
Eli Friedmane4216e92009-11-18 03:38:04 +00002162 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00002163}
2164
Sebastian Redl0eb23302009-01-19 00:08:26 +00002165Action::OwningExprResult
2166Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2167 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002168 // Since this might be a postfix expression, get rid of ParenListExprs.
2169 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2170
Sebastian Redl0eb23302009-01-19 00:08:26 +00002171 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2172 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Douglas Gregor337c6b92008-11-19 17:17:41 +00002174 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002175 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2176 Base.release();
2177 Idx.release();
2178 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2179 Context.DependentTy, RLoc));
2180 }
2181
Mike Stump1eb44332009-09-09 15:08:12 +00002182 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002183 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002184 LHSExp->getType()->isEnumeralType() ||
2185 RHSExp->getType()->isRecordType() ||
2186 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002187 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002188 }
2189
Sebastian Redlf322ed62009-10-29 20:17:01 +00002190 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2191}
2192
2193
2194Action::OwningExprResult
2195Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2196 ExprArg Idx, SourceLocation RLoc) {
2197 Expr *LHSExp = static_cast<Expr*>(Base.get());
2198 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2199
Chris Lattner12d9ff62007-07-16 00:14:47 +00002200 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002201 if (!LHSExp->getType()->getAs<VectorType>())
2202 DefaultFunctionArrayLvalueConversion(LHSExp);
2203 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002204
Chris Lattner12d9ff62007-07-16 00:14:47 +00002205 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002206
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002208 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002209 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002211 Expr *BaseExpr, *IndexExpr;
2212 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002213 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2214 BaseExpr = LHSExp;
2215 IndexExpr = RHSExp;
2216 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002217 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002218 BaseExpr = LHSExp;
2219 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002220 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002221 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002222 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002223 BaseExpr = RHSExp;
2224 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002225 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002226 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002227 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002228 BaseExpr = LHSExp;
2229 IndexExpr = RHSExp;
2230 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002231 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002232 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002233 // Handle the uncommon case of "123[Ptr]".
2234 BaseExpr = RHSExp;
2235 IndexExpr = LHSExp;
2236 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002237 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002238 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002239 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002240
Chris Lattner12d9ff62007-07-16 00:14:47 +00002241 // FIXME: need to deal with const...
2242 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002243 } else if (LHSTy->isArrayType()) {
2244 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002245 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002246 // wasn't promoted because of the C90 rule that doesn't
2247 // allow promoting non-lvalue arrays. Warn, then
2248 // force the promotion here.
2249 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2250 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002251 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2252 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002253 LHSTy = LHSExp->getType();
2254
2255 BaseExpr = LHSExp;
2256 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002257 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002258 } else if (RHSTy->isArrayType()) {
2259 // Same as previous, except for 123[f().a] case
2260 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2261 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002262 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2263 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002264 RHSTy = RHSExp->getType();
2265
2266 BaseExpr = RHSExp;
2267 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002268 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002270 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2271 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002272 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002274 if (!(IndexExpr->getType()->isIntegerType() &&
2275 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002276 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2277 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002278
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002279 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002280 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2281 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002282 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2283
Douglas Gregore7450f52009-03-24 19:52:54 +00002284 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002285 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2286 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002287 // incomplete types are not object types.
2288 if (ResultType->isFunctionType()) {
2289 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2290 << ResultType << BaseExpr->getSourceRange();
2291 return ExprError();
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregore7450f52009-03-24 19:52:54 +00002294 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002295 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002296 PDiag(diag::err_subscript_incomplete_type)
2297 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002298 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattner1efaa952009-04-24 00:30:45 +00002300 // Diagnose bad cases where we step over interface counts.
2301 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2302 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2303 << ResultType << BaseExpr->getSourceRange();
2304 return ExprError();
2305 }
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Sebastian Redl0eb23302009-01-19 00:08:26 +00002307 Base.release();
2308 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002309 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002310 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002311}
2312
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002313QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002314CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002315 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002316 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002317 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2318 // see FIXME there.
2319 //
2320 // FIXME: This logic can be greatly simplified by splitting it along
2321 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002322 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002323
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002324 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002325 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002326
Mike Stumpeed9cac2009-02-19 03:04:26 +00002327 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002328 // special names that indicate a subset of exactly half the elements are
2329 // to be selected.
2330 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002331
Nate Begeman353417a2009-01-18 01:47:54 +00002332 // This flag determines whether or not CompName has an 's' char prefix,
2333 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002334 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002335
2336 // Check that we've found one of the special components, or that the component
2337 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002338 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002339 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2340 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002341 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002342 do
2343 compStr++;
2344 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002345 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002346 do
2347 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002348 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002349 }
Nate Begeman353417a2009-01-18 01:47:54 +00002350
Mike Stumpeed9cac2009-02-19 03:04:26 +00002351 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002352 // We didn't get to the end of the string. This means the component names
2353 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002354 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2355 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002356 return QualType();
2357 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002358
Nate Begeman353417a2009-01-18 01:47:54 +00002359 // Ensure no component accessor exceeds the width of the vector type it
2360 // operates on.
2361 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002362 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002363
2364 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002365 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002366
2367 while (*compStr) {
2368 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2369 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2370 << baseType << SourceRange(CompLoc);
2371 return QualType();
2372 }
2373 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002374 }
Nate Begeman8a997642008-05-09 06:41:27 +00002375
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002376 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002377 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002378 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002379 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002380 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002381 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002382 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002383 if (HexSwizzle)
2384 CompSize--;
2385
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002386 if (CompSize == 1)
2387 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002388
Nate Begeman213541a2008-04-18 23:10:10 +00002389 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002390 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002391 // diagostics look bad. We want extended vector types to appear built-in.
2392 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2393 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2394 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002395 }
2396 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002397}
2398
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002399static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002400 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002401 const Selector &Sel,
2402 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Anders Carlsson8f28f992009-08-26 18:25:21 +00002404 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002405 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002406 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002407 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002409 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2410 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002411 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002412 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002413 return D;
2414 }
2415 return 0;
2416}
2417
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002418static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002419 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002420 const Selector &Sel,
2421 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002422 // Check protocols on qualified interfaces.
2423 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002424 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002425 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002426 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002427 GDecl = PD;
2428 break;
2429 }
2430 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002431 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002432 GDecl = OMD;
2433 break;
2434 }
2435 }
2436 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002437 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002438 E = QIdTy->qual_end(); I != E; ++I) {
2439 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002440 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002441 if (GDecl)
2442 return GDecl;
2443 }
2444 }
2445 return GDecl;
2446}
Chris Lattner76a642f2009-02-15 22:43:40 +00002447
John McCall129e2df2009-11-30 22:42:35 +00002448Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002449Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2450 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002451 const CXXScopeSpec &SS,
2452 NamedDecl *FirstQualifierInScope,
2453 DeclarationName Name, SourceLocation NameLoc,
2454 const TemplateArgumentListInfo *TemplateArgs) {
2455 Expr *BaseExpr = Base.takeAs<Expr>();
2456
2457 // Even in dependent contexts, try to diagnose base expressions with
2458 // obviously wrong types, e.g.:
2459 //
2460 // T* t;
2461 // t.f;
2462 //
2463 // In Obj-C++, however, the above expression is valid, since it could be
2464 // accessing the 'f' property if T is an Obj-C interface. The extra check
2465 // allows this, while still reporting an error if T is a struct pointer.
2466 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002467 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002468 if (PT && (!getLangOptions().ObjC1 ||
2469 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002470 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002471 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002472 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002473 return ExprError();
2474 }
2475 }
2476
Douglas Gregor01e56ae2010-04-12 20:54:26 +00002477 assert(BaseType->isDependentType() || Name.isDependentName() ||
2478 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00002479
2480 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2481 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002482 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002483 IsArrow, OpLoc,
2484 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2485 SS.getRange(),
2486 FirstQualifierInScope,
2487 Name, NameLoc,
2488 TemplateArgs));
2489}
2490
2491/// We know that the given qualified member reference points only to
2492/// declarations which do not belong to the static type of the base
2493/// expression. Diagnose the problem.
2494static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2495 Expr *BaseExpr,
2496 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002497 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002498 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002499 // If this is an implicit member access, use a different set of
2500 // diagnostics.
2501 if (!BaseExpr)
2502 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002503
2504 // FIXME: this is an exceedingly lame diagnostic for some of the more
2505 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002506 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002507 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002508 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002509}
2510
2511// Check whether the declarations we found through a nested-name
2512// specifier in a member expression are actually members of the base
2513// type. The restriction here is:
2514//
2515// C++ [expr.ref]p2:
2516// ... In these cases, the id-expression shall name a
2517// member of the class or of one of its base classes.
2518//
2519// So it's perfectly legitimate for the nested-name specifier to name
2520// an unrelated class, and for us to find an overload set including
2521// decls from classes which are not superclasses, as long as the decl
2522// we actually pick through overload resolution is from a superclass.
2523bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2524 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002525 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002526 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002527 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2528 if (!BaseRT) {
2529 // We can't check this yet because the base type is still
2530 // dependent.
2531 assert(BaseType->isDependentType());
2532 return false;
2533 }
2534 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002535
2536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002537 // If this is an implicit member reference and we find a
2538 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00002539 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002540 return false;
John McCall129e2df2009-11-30 22:42:35 +00002541
John McCallaa81e162009-12-01 22:10:20 +00002542 // Note that we use the DC of the decl, not the underlying decl.
2543 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2544 while (RecordD->isAnonymousStructOrUnion())
2545 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2546
2547 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2548 MemberRecord.insert(RecordD->getCanonicalDecl());
2549
2550 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2551 return false;
2552 }
2553
John McCall2f841ba2009-12-02 03:53:29 +00002554 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002555 return true;
2556}
2557
2558static bool
2559LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2560 SourceRange BaseRange, const RecordType *RTy,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002561 SourceLocation OpLoc, CXXScopeSpec &SS) {
John McCallaa81e162009-12-01 22:10:20 +00002562 RecordDecl *RDecl = RTy->getDecl();
2563 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002564 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002565 << BaseRange))
2566 return true;
2567
2568 DeclContext *DC = RDecl;
2569 if (SS.isSet()) {
2570 // If the member name was a qualified-id, look into the
2571 // nested-name-specifier.
2572 DC = SemaRef.computeDeclContext(SS, false);
2573
John McCall2f841ba2009-12-02 03:53:29 +00002574 if (SemaRef.RequireCompleteDeclContext(SS)) {
2575 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2576 << SS.getRange() << DC;
2577 return true;
2578 }
2579
John McCallaa81e162009-12-01 22:10:20 +00002580 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002581
John McCallaa81e162009-12-01 22:10:20 +00002582 if (!isa<TypeDecl>(DC)) {
2583 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2584 << DC << SS.getRange();
2585 return true;
John McCall129e2df2009-11-30 22:42:35 +00002586 }
2587 }
2588
John McCallaa81e162009-12-01 22:10:20 +00002589 // The record definition is complete, now look up the member.
2590 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002591
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002592 if (!R.empty())
2593 return false;
2594
2595 // We didn't find anything with the given name, so try to correct
2596 // for typos.
2597 DeclarationName Name = R.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002598 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
2599 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002600 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2601 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2602 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00002603 << FixItHint::CreateReplacement(R.getNameLoc(),
2604 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002605 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2606 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2607 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002608 return false;
2609 } else {
2610 R.clear();
2611 }
2612
John McCall129e2df2009-11-30 22:42:35 +00002613 return false;
2614}
2615
2616Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002617Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002618 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002619 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002620 NamedDecl *FirstQualifierInScope,
2621 DeclarationName Name, SourceLocation NameLoc,
2622 const TemplateArgumentListInfo *TemplateArgs) {
2623 Expr *Base = BaseArg.takeAs<Expr>();
2624
John McCall2f841ba2009-12-02 03:53:29 +00002625 if (BaseType->isDependentType() ||
2626 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002627 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002628 IsArrow, OpLoc,
2629 SS, FirstQualifierInScope,
2630 Name, NameLoc,
2631 TemplateArgs);
2632
2633 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002634
John McCallaa81e162009-12-01 22:10:20 +00002635 // Implicit member accesses.
2636 if (!Base) {
2637 QualType RecordTy = BaseType;
2638 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2639 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2640 RecordTy->getAs<RecordType>(),
2641 OpLoc, SS))
2642 return ExprError();
2643
2644 // Explicit member accesses.
2645 } else {
2646 OwningExprResult Result =
2647 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00002648 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCallaa81e162009-12-01 22:10:20 +00002649
2650 if (Result.isInvalid()) {
2651 Owned(Base);
2652 return ExprError();
2653 }
2654
2655 if (Result.get())
2656 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002657 }
2658
John McCallaa81e162009-12-01 22:10:20 +00002659 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002660 OpLoc, IsArrow, SS, FirstQualifierInScope,
2661 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002662}
2663
2664Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002665Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2666 SourceLocation OpLoc, bool IsArrow,
2667 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002668 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002669 LookupResult &R,
2670 const TemplateArgumentListInfo *TemplateArgs) {
2671 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002672 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002673 if (IsArrow) {
2674 assert(BaseType->isPointerType());
2675 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2676 }
John McCall161755a2010-04-06 21:38:20 +00002677 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00002678
2679 NestedNameSpecifier *Qualifier =
2680 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2681 DeclarationName MemberName = R.getLookupName();
2682 SourceLocation MemberLoc = R.getNameLoc();
2683
2684 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002685 return ExprError();
2686
John McCall129e2df2009-11-30 22:42:35 +00002687 if (R.empty()) {
2688 // Rederive where we looked up.
2689 DeclContext *DC = (SS.isSet()
2690 ? computeDeclContext(SS, false)
2691 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002692
John McCall129e2df2009-11-30 22:42:35 +00002693 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002694 << MemberName << DC
2695 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002696 return ExprError();
2697 }
2698
John McCallc2233c52010-01-15 08:34:02 +00002699 // Diagnose lookups that find only declarations from a non-base
2700 // type. This is possible for either qualified lookups (which may
2701 // have been qualified with an unrelated type) or implicit member
2702 // expressions (which were found with unqualified lookup and thus
2703 // may have come from an enclosing scope). Note that it's okay for
2704 // lookup to find declarations from a non-base type as long as those
2705 // aren't the ones picked by overload resolution.
2706 if ((SS.isSet() || !BaseExpr ||
2707 (isa<CXXThisExpr>(BaseExpr) &&
2708 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2709 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002710 return ExprError();
2711
2712 // Construct an unresolved result if we in fact got an unresolved
2713 // result.
2714 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002715 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002716 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002717 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002718 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002719
John McCallc373d482010-01-27 01:50:18 +00002720 // Suppress any lookup-related diagnostics; we'll do these when we
2721 // pick a member.
2722 R.suppressDiagnostics();
2723
John McCall129e2df2009-11-30 22:42:35 +00002724 UnresolvedMemberExpr *MemExpr
2725 = UnresolvedMemberExpr::Create(Context, Dependent,
2726 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002727 BaseExpr, BaseExprType,
2728 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002729 Qualifier, SS.getRange(),
2730 MemberName, MemberLoc,
2731 TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00002732 MemExpr->addDecls(R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002733
2734 return Owned(MemExpr);
2735 }
2736
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002737 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00002738 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00002739 NamedDecl *MemberDecl = R.getFoundDecl();
2740
2741 // FIXME: diagnose the presence of template arguments now.
2742
2743 // If the decl being referenced had an error, return an error for this
2744 // sub-expr without emitting another error, in order to avoid cascading
2745 // error cases.
2746 if (MemberDecl->isInvalidDecl())
2747 return ExprError();
2748
John McCallaa81e162009-12-01 22:10:20 +00002749 // Handle the implicit-member-access case.
2750 if (!BaseExpr) {
2751 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00002752 if (!MemberDecl->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002753 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2754
Douglas Gregor828a1972010-01-07 23:12:05 +00002755 SourceLocation Loc = R.getNameLoc();
2756 if (SS.getRange().isValid())
2757 Loc = SS.getRange().getBegin();
2758 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002759 }
2760
John McCall129e2df2009-11-30 22:42:35 +00002761 bool ShouldCheckUse = true;
2762 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2763 // Don't diagnose the use of a virtual member function unless it's
2764 // explicitly qualified.
2765 if (MD->isVirtual() && !SS.isSet())
2766 ShouldCheckUse = false;
2767 }
2768
2769 // Check the use of this member.
2770 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2771 Owned(BaseExpr);
2772 return ExprError();
2773 }
2774
2775 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2776 // We may have found a field within an anonymous union or struct
2777 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002778 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2779 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002780 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2781 BaseExpr, OpLoc);
2782
2783 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2784 QualType MemberType = FD->getType();
2785 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2786 MemberType = Ref->getPointeeType();
2787 else {
2788 Qualifiers BaseQuals = BaseType.getQualifiers();
2789 BaseQuals.removeObjCGCAttr();
2790 if (FD->isMutable()) BaseQuals.removeConst();
2791
2792 Qualifiers MemberQuals
2793 = Context.getCanonicalType(MemberType).getQualifiers();
2794
2795 Qualifiers Combined = BaseQuals + MemberQuals;
2796 if (Combined != MemberQuals)
2797 MemberType = Context.getQualifiedType(MemberType, Combined);
2798 }
2799
2800 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002801 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002802 return ExprError();
2803 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002804 FD, FoundDecl, MemberLoc, MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002805 }
2806
2807 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2808 MarkDeclarationReferenced(MemberLoc, Var);
2809 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002810 Var, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002811 Var->getType().getNonReferenceType()));
2812 }
2813
2814 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2815 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2816 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002817 MemberFn, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002818 MemberFn->getType()));
2819 }
2820
2821 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2822 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2823 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002824 Enum, FoundDecl, MemberLoc, Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002825 }
2826
2827 Owned(BaseExpr);
2828
2829 if (isa<TypeDecl>(MemberDecl))
2830 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2831 << MemberName << int(IsArrow));
2832
2833 // We found a declaration kind that we didn't expect. This is a
2834 // generic error message that tells the user that she can't refer
2835 // to this member with '.' or '->'.
2836 return ExprError(Diag(MemberLoc,
2837 diag::err_typecheck_member_reference_unknown)
2838 << MemberName << int(IsArrow));
2839}
2840
2841/// Look up the given member of the given non-type-dependent
2842/// expression. This can return in one of two ways:
2843/// * If it returns a sentinel null-but-valid result, the caller will
2844/// assume that lookup was performed and the results written into
2845/// the provided structure. It will take over from there.
2846/// * Otherwise, the returned expression will be produced in place of
2847/// an ordinary member expression.
2848///
2849/// The ObjCImpDecl bit is a gross hack that will need to be properly
2850/// fixed for ObjC++.
2851Sema::OwningExprResult
2852Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002853 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002854 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002855 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002856 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002857
Steve Naroff3cc4af82007-12-16 21:42:28 +00002858 // Perform default conversions.
2859 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002860
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002861 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002862 assert(!BaseType->isDependentType());
2863
2864 DeclarationName MemberName = R.getLookupName();
2865 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002866
2867 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002868 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002869 // function. Suggest the addition of those parentheses, build the
2870 // call, and continue on.
2871 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2872 if (const FunctionProtoType *Fun
2873 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2874 QualType ResultTy = Fun->getResultType();
2875 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002876 ((!IsArrow && ResultTy->isRecordType()) ||
2877 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002878 ResultTy->getAs<PointerType>()->getPointeeType()
2879 ->isRecordType()))) {
2880 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2881 Diag(Loc, diag::err_member_reference_needs_call)
2882 << QualType(Fun, 0)
Douglas Gregor849b2432010-03-31 17:46:05 +00002883 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002884
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002885 OwningExprResult NewBase
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002886 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002887 MultiExprArg(*this, 0, 0), 0, Loc);
2888 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002889 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002890
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002891 BaseExpr = NewBase.takeAs<Expr>();
2892 DefaultFunctionArrayConversion(BaseExpr);
2893 BaseType = BaseExpr->getType();
2894 }
2895 }
2896 }
2897
David Chisnall0f436562009-08-17 16:35:33 +00002898 // If this is an Objective-C pseudo-builtin and a definition is provided then
2899 // use that.
2900 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002901 if (IsArrow) {
2902 // Handle the following exceptional case PObj->isa.
2903 if (const ObjCObjectPointerType *OPT =
2904 BaseType->getAs<ObjCObjectPointerType>()) {
2905 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2906 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002907 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2908 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002909 }
2910 }
David Chisnall0f436562009-08-17 16:35:33 +00002911 // We have an 'id' type. Rather than fall through, we check if this
2912 // is a reference to 'isa'.
2913 if (BaseType != Context.ObjCIdRedefinitionType) {
2914 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002915 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002916 }
David Chisnall0f436562009-08-17 16:35:33 +00002917 }
John McCall129e2df2009-11-30 22:42:35 +00002918
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002919 // If this is an Objective-C pseudo-builtin and a definition is provided then
2920 // use that.
2921 if (Context.isObjCSelType(BaseType)) {
2922 // We have an 'SEL' type. Rather than fall through, we check if this
2923 // is a reference to 'sel_id'.
2924 if (BaseType != Context.ObjCSelRedefinitionType) {
2925 BaseType = Context.ObjCSelRedefinitionType;
2926 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2927 }
2928 }
John McCall129e2df2009-11-30 22:42:35 +00002929
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002930 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002931
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002932 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002933 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002934 // Also must look for a getter name which uses property syntax.
2935 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2936 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2937 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2938 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2939 ObjCMethodDecl *Getter;
2940 // FIXME: need to also look locally in the implementation.
2941 if ((Getter = IFace->lookupClassMethod(Sel))) {
2942 // Check the use of this method.
2943 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2944 return ExprError();
2945 }
2946 // If we found a getter then this may be a valid dot-reference, we
2947 // will look for the matching setter, in case it is needed.
2948 Selector SetterSel =
2949 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2950 PP.getSelectorTable(), Member);
2951 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2952 if (!Setter) {
2953 // If this reference is in an @implementation, also check for 'private'
2954 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002955 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002956 }
2957 // Look through local category implementations associated with the class.
2958 if (!Setter)
2959 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002960
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002961 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2962 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002963
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002964 if (Getter || Setter) {
2965 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002966
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002967 if (Getter)
2968 PType = Getter->getResultType();
2969 else
2970 // Get the expression type from Setter's incoming parameter.
2971 PType = (*(Setter->param_end() -1))->getType();
2972 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002973 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002974 PType,
2975 Setter, MemberLoc, BaseExpr));
2976 }
2977 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2978 << MemberName << BaseType);
2979 }
2980 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002981
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002982 if (BaseType->isObjCClassType() &&
2983 BaseType != Context.ObjCClassRedefinitionType) {
2984 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002985 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002986 }
Mike Stump1eb44332009-09-09 15:08:12 +00002987
John McCall129e2df2009-11-30 22:42:35 +00002988 if (IsArrow) {
2989 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002990 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002991 else if (BaseType->isObjCObjectPointerType())
2992 ;
John McCall812c1542009-12-07 22:46:59 +00002993 else if (BaseType->isRecordType()) {
2994 // Recover from arrow accesses to records, e.g.:
2995 // struct MyRecord foo;
2996 // foo->bar
2997 // This is actually well-formed in C++ if MyRecord has an
2998 // overloaded operator->, but that should have been dealt with
2999 // by now.
3000 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3001 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003002 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003003 IsArrow = false;
3004 } else {
John McCall129e2df2009-11-30 22:42:35 +00003005 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3006 << BaseType << BaseExpr->getSourceRange();
3007 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003008 }
John McCall812c1542009-12-07 22:46:59 +00003009 } else {
3010 // Recover from dot accesses to pointers, e.g.:
3011 // type *foo;
3012 // foo.bar
3013 // This is actually well-formed in two cases:
3014 // - 'type' is an Objective C type
3015 // - 'bar' is a pseudo-destructor name which happens to refer to
3016 // the appropriate pointer type
3017 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3018 const PointerType *PT = BaseType->getAs<PointerType>();
3019 if (PT && PT->getPointeeType()->isRecordType()) {
3020 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3021 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003022 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003023 BaseType = PT->getPointeeType();
3024 IsArrow = true;
3025 }
3026 }
John McCall129e2df2009-11-30 22:42:35 +00003027 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003028
John McCall129e2df2009-11-30 22:42:35 +00003029 // Handle field access to simple records. This also handles access
3030 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00003031 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003032 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3033 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003034 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003035 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003036 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003037
Chris Lattnera38e6b12008-07-21 04:59:05 +00003038 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3039 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003040 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3041 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00003042 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003043 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00003044 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00003045 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003046 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3047
Steve Naroffc70e8d92009-07-16 00:25:06 +00003048 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
3049 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003050 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003052 if (!IV) {
3053 // Attempt to correct for typos in ivar names.
3054 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3055 LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003056 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003057 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003058 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003059 diag::err_typecheck_member_reference_ivar_suggest)
3060 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregor849b2432010-03-31 17:46:05 +00003061 << FixItHint::CreateReplacement(R.getNameLoc(),
3062 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003063 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003064 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003065 }
3066 }
3067
Steve Naroffc70e8d92009-07-16 00:25:06 +00003068 if (IV) {
3069 // If the decl being referenced had an error, return an error for this
3070 // sub-expr without emitting another error, in order to avoid cascading
3071 // error cases.
3072 if (IV->isInvalidDecl())
3073 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003074
Steve Naroffc70e8d92009-07-16 00:25:06 +00003075 // Check whether we can reference this field.
3076 if (DiagnoseUseOfDecl(IV, MemberLoc))
3077 return ExprError();
3078 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3079 IV->getAccessControl() != ObjCIvarDecl::Package) {
3080 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3081 if (ObjCMethodDecl *MD = getCurMethodDecl())
3082 ClassOfMethodDecl = MD->getClassInterface();
3083 else if (ObjCImpDecl && getCurFunctionDecl()) {
3084 // Case of a c-function declared inside an objc implementation.
3085 // FIXME: For a c-style function nested inside an objc implementation
3086 // class, there is no implementation context available, so we pass
3087 // down the context as argument to this routine. Ideally, this context
3088 // need be passed down in the AST node and somehow calculated from the
3089 // AST for a function decl.
3090 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00003091 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00003092 dyn_cast<ObjCImplementationDecl>(ImplDecl))
3093 ClassOfMethodDecl = IMPD->getClassInterface();
3094 else if (ObjCCategoryImplDecl* CatImplClass =
3095 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3096 ClassOfMethodDecl = CatImplClass->getClassInterface();
3097 }
Mike Stump1eb44332009-09-09 15:08:12 +00003098
3099 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3100 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003101 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003102 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003103 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003104 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3105 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003106 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003107 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003108 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003109
3110 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3111 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003112 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003113 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003114 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003115 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003116 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003117 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003118 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003119 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003120 if (!IsArrow && (BaseType->isObjCIdType() ||
3121 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003122 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003123 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Steve Naroff14108da2009-07-10 23:34:53 +00003125 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003126 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003127 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3128 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3129 // Check the use of this declaration
3130 if (DiagnoseUseOfDecl(PD, MemberLoc))
3131 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Steve Naroff14108da2009-07-10 23:34:53 +00003133 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3134 MemberLoc, BaseExpr));
3135 }
3136 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3137 // Check the use of this method.
3138 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3139 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Douglas Gregor04badcf2010-04-21 00:45:42 +00003141 return Owned(ObjCMessageExpr::Create(Context,
3142 OMD->getResultType().getNonReferenceType(),
3143 OpLoc, BaseExpr, Sel,
3144 OMD, NULL, 0, MemberLoc));
Steve Naroff14108da2009-07-10 23:34:53 +00003145 }
3146 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003147
Steve Naroff14108da2009-07-10 23:34:53 +00003148 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003149 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003150 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00003151
Chris Lattnera38e6b12008-07-21 04:59:05 +00003152 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3153 // pointer to a (potentially qualified) interface type.
Chris Lattner7f816522010-04-11 07:45:24 +00003154 if (!IsArrow)
3155 if (const ObjCObjectPointerType *OPT =
3156 BaseType->getAsObjCInterfacePointerType())
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00003157 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Steve Narofff242b1b2009-07-24 17:54:45 +00003159 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003160 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003161 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003162 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003163 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003164 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003165
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003166 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003167 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003168 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003169 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3170 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003171 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003172 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003173 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003174 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003175
Douglas Gregor214f31a2009-03-27 06:00:30 +00003176 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3177 << BaseType << BaseExpr->getSourceRange();
3178
Douglas Gregor214f31a2009-03-27 06:00:30 +00003179 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003180}
3181
John McCall129e2df2009-11-30 22:42:35 +00003182/// The main callback when the parser finds something like
3183/// expression . [nested-name-specifier] identifier
3184/// expression -> [nested-name-specifier] identifier
3185/// where 'identifier' encompasses a fairly broad spectrum of
3186/// possibilities, including destructor and operator references.
3187///
3188/// \param OpKind either tok::arrow or tok::period
3189/// \param HasTrailingLParen whether the next token is '(', which
3190/// is used to diagnose mis-uses of special members that can
3191/// only be called
3192/// \param ObjCImpDecl the current ObjC @implementation decl;
3193/// this is an ugly hack around the fact that ObjC @implementations
3194/// aren't properly put in the context chain
3195Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3196 SourceLocation OpLoc,
3197 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003198 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003199 UnqualifiedId &Id,
3200 DeclPtrTy ObjCImpDecl,
3201 bool HasTrailingLParen) {
3202 if (SS.isSet() && SS.isInvalid())
3203 return ExprError();
3204
3205 TemplateArgumentListInfo TemplateArgsBuffer;
3206
3207 // Decompose the name into its component parts.
3208 DeclarationName Name;
3209 SourceLocation NameLoc;
3210 const TemplateArgumentListInfo *TemplateArgs;
3211 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3212 Name, NameLoc, TemplateArgs);
3213
3214 bool IsArrow = (OpKind == tok::arrow);
3215
3216 NamedDecl *FirstQualifierInScope
3217 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3218 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3219
3220 // This is a postfix expression, so get rid of ParenListExprs.
3221 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3222
3223 Expr *Base = BaseArg.takeAs<Expr>();
3224 OwningExprResult Result(*this);
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003225 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3226 isDependentScopeSpecifier(SS)) {
John McCallaa81e162009-12-01 22:10:20 +00003227 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003228 IsArrow, OpLoc,
3229 SS, FirstQualifierInScope,
3230 Name, NameLoc,
3231 TemplateArgs);
3232 } else {
3233 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3234 if (TemplateArgs) {
3235 // Re-use the lookup done for the template name.
3236 DecomposeTemplateName(R, Id);
3237 } else {
3238 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00003239 SS, ObjCImpDecl);
John McCall129e2df2009-11-30 22:42:35 +00003240
3241 if (Result.isInvalid()) {
3242 Owned(Base);
3243 return ExprError();
3244 }
3245
3246 if (Result.get()) {
3247 // The only way a reference to a destructor can be used is to
3248 // immediately call it, which falls into this case. If the
3249 // next token is not a '(', produce a diagnostic and build the
3250 // call now.
3251 if (!HasTrailingLParen &&
3252 Id.getKind() == UnqualifiedId::IK_DestructorName)
Douglas Gregor77549082010-02-24 21:29:12 +00003253 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall129e2df2009-11-30 22:42:35 +00003254
3255 return move(Result);
3256 }
3257 }
3258
John McCallaa81e162009-12-01 22:10:20 +00003259 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003260 OpLoc, IsArrow, SS, FirstQualifierInScope,
3261 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003262 }
3263
3264 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003265}
3266
Anders Carlsson56c5e332009-08-25 03:49:14 +00003267Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3268 FunctionDecl *FD,
3269 ParmVarDecl *Param) {
3270 if (Param->hasUnparsedDefaultArg()) {
3271 Diag (CallLoc,
3272 diag::err_use_of_default_argument_to_function_declared_later) <<
3273 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003274 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003275 diag::note_default_argument_declared_here);
3276 } else {
3277 if (Param->hasUninstantiatedDefaultArg()) {
3278 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3279
3280 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003281 MultiLevelTemplateArgumentList ArgList
3282 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003283
Mike Stump1eb44332009-09-09 15:08:12 +00003284 InstantiatingTemplate Inst(*this, CallLoc, Param,
3285 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003286 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003287
John McCallce3ff2b2009-08-25 22:02:44 +00003288 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003289 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003290 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Douglas Gregor65222e82009-12-23 18:19:08 +00003292 // Check the expression as an initializer for the parameter.
3293 InitializedEntity Entity
3294 = InitializedEntity::InitializeParameter(Param);
3295 InitializationKind Kind
3296 = InitializationKind::CreateCopy(Param->getLocation(),
3297 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3298 Expr *ResultE = Result.takeAs<Expr>();
3299
3300 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003301 Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor65222e82009-12-23 18:19:08 +00003302 MultiExprArg(*this, (void**)&ResultE, 1));
3303 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003304 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003305
Douglas Gregor65222e82009-12-23 18:19:08 +00003306 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003307 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003308 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003309 }
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Anders Carlsson56c5e332009-08-25 03:49:14 +00003311 // If the default expression creates temporaries, we need to
3312 // push them to the current stack of expression temporaries so they'll
3313 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003314 // FIXME: We should really be rebuilding the default argument with new
3315 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003316 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3317 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003318 }
3319
3320 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003321 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003322}
3323
Douglas Gregor88a35142008-12-22 05:46:06 +00003324/// ConvertArgumentsForCall - Converts the arguments specified in
3325/// Args/NumArgs to the parameter types of the function FDecl with
3326/// function prototype Proto. Call is the call expression itself, and
3327/// Fn is the function expression. For a C++ member function, this
3328/// routine does not attempt to convert the object argument. Returns
3329/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003330bool
3331Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003332 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003333 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003334 Expr **Args, unsigned NumArgs,
3335 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003336 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003337 // assignment, to the types of the corresponding parameter, ...
3338 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003339 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003340
Douglas Gregor88a35142008-12-22 05:46:06 +00003341 // If too few arguments are available (and we don't have default
3342 // arguments for the remaining parameters), don't make the call.
3343 if (NumArgs < NumArgsInProto) {
3344 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3345 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00003346 << Fn->getType()->isBlockPointerType()
3347 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003348 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003349 }
3350
3351 // If too many are passed and not variadic, error on the extras and drop
3352 // them.
3353 if (NumArgs > NumArgsInProto) {
3354 if (!Proto->isVariadic()) {
3355 Diag(Args[NumArgsInProto]->getLocStart(),
3356 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00003357 << Fn->getType()->isBlockPointerType()
3358 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003359 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3360 Args[NumArgs-1]->getLocEnd());
3361 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003362 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003363 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003364 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003365 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003366 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003367 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003368 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3369 if (Fn->getType()->isBlockPointerType())
3370 CallType = VariadicBlock; // Block
3371 else if (isa<MemberExpr>(Fn))
3372 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003373 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003374 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003375 if (Invalid)
3376 return true;
3377 unsigned TotalNumArgs = AllArgs.size();
3378 for (unsigned i = 0; i < TotalNumArgs; ++i)
3379 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003380
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003381 return false;
3382}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003383
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003384bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3385 FunctionDecl *FDecl,
3386 const FunctionProtoType *Proto,
3387 unsigned FirstProtoArg,
3388 Expr **Args, unsigned NumArgs,
3389 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003390 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003391 unsigned NumArgsInProto = Proto->getNumArgs();
3392 unsigned NumArgsToCheck = NumArgs;
3393 bool Invalid = false;
3394 if (NumArgs != NumArgsInProto)
3395 // Use default arguments for missing arguments
3396 NumArgsToCheck = NumArgsInProto;
3397 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003398 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003399 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003400 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003401
Douglas Gregor88a35142008-12-22 05:46:06 +00003402 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003403 if (ArgIx < NumArgs) {
3404 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003405
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003406 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3407 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003408 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003409 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003410 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003411
Douglas Gregora188ff22009-12-22 16:09:06 +00003412 // Pass the argument
3413 ParmVarDecl *Param = 0;
3414 if (FDecl && i < FDecl->getNumParams())
3415 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003416
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003417
Douglas Gregora188ff22009-12-22 16:09:06 +00003418 InitializedEntity Entity =
3419 Param? InitializedEntity::InitializeParameter(Param)
3420 : InitializedEntity::InitializeParameter(ProtoArgType);
3421 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3422 SourceLocation(),
3423 Owned(Arg));
3424 if (ArgE.isInvalid())
3425 return true;
3426
3427 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003428 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003429 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003430
Mike Stump1eb44332009-09-09 15:08:12 +00003431 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003432 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003433 if (ArgExpr.isInvalid())
3434 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003435
Anders Carlsson56c5e332009-08-25 03:49:14 +00003436 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003437 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003438 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003439 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003440
Douglas Gregor88a35142008-12-22 05:46:06 +00003441 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003442 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003443 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003444 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003445 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003446 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003447 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003448 }
3449 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003450 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003451}
3452
Steve Narofff69936d2007-09-16 03:34:24 +00003453/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003454/// This provides the location of the left/right parens and a list of comma
3455/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003456Action::OwningExprResult
3457Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3458 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003459 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003460 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003461
3462 // Since this might be a postfix expression, get rid of ParenListExprs.
3463 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003465 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003466 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003467 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Douglas Gregor88a35142008-12-22 05:46:06 +00003469 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003470 // If this is a pseudo-destructor expression, build the call immediately.
3471 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3472 if (NumArgs > 0) {
3473 // Pseudo-destructor calls should not have any arguments.
3474 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003475 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003476 SourceRange(Args[0]->getLocStart(),
3477 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Douglas Gregora71d8192009-09-04 17:36:40 +00003479 for (unsigned I = 0; I != NumArgs; ++I)
3480 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003481
Douglas Gregora71d8192009-09-04 17:36:40 +00003482 NumArgs = 0;
3483 }
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Douglas Gregora71d8192009-09-04 17:36:40 +00003485 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3486 RParenLoc));
3487 }
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregor17330012009-02-04 15:01:18 +00003489 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003490 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003491 // FIXME: Will need to cache the results of name lookup (including ADL) in
3492 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003493 bool Dependent = false;
3494 if (Fn->isTypeDependent())
3495 Dependent = true;
3496 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3497 Dependent = true;
3498
3499 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003500 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003501 Context.DependentTy, RParenLoc));
3502
3503 // Determine whether this is a call to an object (C++ [over.call.object]).
3504 if (Fn->getType()->isRecordType())
3505 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3506 CommaLocs, RParenLoc));
3507
John McCall129e2df2009-11-30 22:42:35 +00003508 Expr *NakedFn = Fn->IgnoreParens();
3509
3510 // Determine whether this is a call to an unresolved member function.
3511 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3512 // If lookup was unresolved but not dependent (i.e. didn't find
3513 // an unresolved using declaration), it has to be an overloaded
3514 // function set, which means it must contain either multiple
3515 // declarations (all methods or method templates) or a single
3516 // method template.
3517 assert((MemE->getNumDecls() > 1) ||
3518 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003519 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003520
John McCallaa81e162009-12-01 22:10:20 +00003521 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3522 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003523 }
3524
Douglas Gregorfa047642009-02-04 00:32:51 +00003525 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003526 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003527 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003528 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003529 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3530 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003531 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003532
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003533 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003535 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3536 BO->getOpcode() == BinaryOperator::PtrMemI) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003537 if (const FunctionProtoType *FPT =
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003538 dyn_cast<FunctionProtoType>(BO->getType())) {
3539 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003540
3541 ExprOwningPtr<CXXMemberCallExpr>
3542 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003543 NumArgs, ResultTy,
3544 RParenLoc));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003545
3546 if (CheckCallReturnType(FPT->getResultType(),
3547 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003548 TheCall.get(), 0))
3549 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003550
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003551 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003552 RParenLoc))
3553 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003554
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003555 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3556 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003557 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003558 diag::err_typecheck_call_not_function)
3559 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003560 }
3561 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003562 }
3563
Douglas Gregorfa047642009-02-04 00:32:51 +00003564 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003565 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003566 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003567
Eli Friedmanefa42f72009-12-26 03:35:45 +00003568 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003569 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3570 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00003571 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00003572 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003573 }
Chris Lattner04421082008-04-08 04:40:51 +00003574
John McCall3b4294e2009-12-16 12:17:52 +00003575 NamedDecl *NDecl = 0;
3576 if (isa<DeclRefExpr>(NakedFn))
3577 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3578
John McCallaa81e162009-12-01 22:10:20 +00003579 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3580}
3581
John McCall3b4294e2009-12-16 12:17:52 +00003582/// BuildResolvedCallExpr - Build a call to a resolved expression,
3583/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003584/// unary-convert to an expression of function-pointer or
3585/// block-pointer type.
3586///
3587/// \param NDecl the declaration being called, if available
3588Sema::OwningExprResult
3589Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3590 SourceLocation LParenLoc,
3591 Expr **Args, unsigned NumArgs,
3592 SourceLocation RParenLoc) {
3593 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3594
Chris Lattner04421082008-04-08 04:40:51 +00003595 // Promote the function operand.
3596 UsualUnaryConversions(Fn);
3597
Chris Lattner925e60d2007-12-28 05:29:59 +00003598 // Make the call expr early, before semantic checks. This guarantees cleanup
3599 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003600 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3601 Args, NumArgs,
3602 Context.BoolTy,
3603 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003604
Steve Naroffdd972f22008-09-05 22:11:13 +00003605 const FunctionType *FuncT;
3606 if (!Fn->getType()->isBlockPointerType()) {
3607 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3608 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003609 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003610 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003611 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3612 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003613 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003614 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003615 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003616 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003617 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003618 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003619 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3620 << Fn->getType() << Fn->getSourceRange());
3621
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003622 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003623 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003624 Fn->getSourceRange().getBegin(), TheCall.get(),
3625 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003626 return ExprError();
3627
Chris Lattner925e60d2007-12-28 05:29:59 +00003628 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003629 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003630
Douglas Gregor72564e72009-02-26 23:50:07 +00003631 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003632 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003633 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003634 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003635 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003636 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003637
Douglas Gregor74734d52009-04-02 15:37:10 +00003638 if (FDecl) {
3639 // Check if we have too few/too many template arguments, based
3640 // on our knowledge of the function definition.
3641 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003642 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003643 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003644 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003645 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3646 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3647 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3648 }
3649 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003650 }
3651
Steve Naroffb291ab62007-08-28 23:30:39 +00003652 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003653 for (unsigned i = 0; i != NumArgs; i++) {
3654 Expr *Arg = Args[i];
3655 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003656 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3657 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003658 PDiag(diag::err_call_incomplete_argument)
3659 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003660 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003661 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003662 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003663 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003664
Douglas Gregor88a35142008-12-22 05:46:06 +00003665 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3666 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003667 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3668 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003669
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003670 // Check for sentinels
3671 if (NDecl)
3672 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Chris Lattner59907c42007-08-10 20:18:51 +00003674 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003675 if (FDecl) {
3676 if (CheckFunctionCall(FDecl, TheCall.get()))
3677 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003679 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003680 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3681 } else if (NDecl) {
3682 if (CheckBlockCall(NDecl, TheCall.get()))
3683 return ExprError();
3684 }
Chris Lattner59907c42007-08-10 20:18:51 +00003685
Anders Carlssonec74c592009-08-16 03:06:32 +00003686 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003687}
3688
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003689Action::OwningExprResult
3690Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3691 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003692 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003693 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003694 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003695
3696 TypeSourceInfo *TInfo;
3697 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3698 if (!TInfo)
3699 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3700
3701 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3702}
3703
3704Action::OwningExprResult
3705Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3706 SourceLocation RParenLoc, ExprArg InitExpr) {
3707 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003708 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003709
Eli Friedman6223c222008-05-20 05:22:08 +00003710 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003711 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003712 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3713 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003714 } else if (!literalType->isDependentType() &&
3715 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003716 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003717 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003718 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003719 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003720
Douglas Gregor99a2e602009-12-16 01:38:02 +00003721 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003722 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003723 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003724 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003725 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003726 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3727 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3728 MultiExprArg(*this, (void**)&literalExpr, 1),
3729 &literalType);
3730 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003731 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003732 InitExpr.release();
3733 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003734
Chris Lattner371f2582008-12-04 23:50:19 +00003735 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003736 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003737 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003738 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003739 }
Eli Friedman08544622009-12-22 02:35:53 +00003740
3741 Result.release();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003742
John McCall1d7d8d62010-01-19 22:33:45 +00003743 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003744 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003745}
3746
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003747Action::OwningExprResult
3748Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003749 SourceLocation RBraceLoc) {
3750 unsigned NumInit = initlist.size();
3751 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003752
Steve Naroff08d92e42007-09-15 18:49:24 +00003753 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003754 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003755
Ted Kremenek709210f2010-04-13 23:39:13 +00003756 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3757 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003758 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003759 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003760}
3761
Anders Carlsson82debc72009-10-18 18:12:03 +00003762static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3763 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003764 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003765 return CastExpr::CK_NoOp;
3766
3767 if (SrcTy->hasPointerRepresentation()) {
3768 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003769 return DestTy->isObjCObjectPointerType() ?
3770 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003771 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003772 if (DestTy->isIntegerType())
3773 return CastExpr::CK_PointerToIntegral;
3774 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003775
Anders Carlsson82debc72009-10-18 18:12:03 +00003776 if (SrcTy->isIntegerType()) {
3777 if (DestTy->isIntegerType())
3778 return CastExpr::CK_IntegralCast;
3779 if (DestTy->hasPointerRepresentation())
3780 return CastExpr::CK_IntegralToPointer;
3781 if (DestTy->isRealFloatingType())
3782 return CastExpr::CK_IntegralToFloating;
3783 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003784
Anders Carlsson82debc72009-10-18 18:12:03 +00003785 if (SrcTy->isRealFloatingType()) {
3786 if (DestTy->isRealFloatingType())
3787 return CastExpr::CK_FloatingCast;
3788 if (DestTy->isIntegerType())
3789 return CastExpr::CK_FloatingToIntegral;
3790 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003791
Anders Carlsson82debc72009-10-18 18:12:03 +00003792 // FIXME: Assert here.
3793 // assert(false && "Unhandled cast combination!");
3794 return CastExpr::CK_Unknown;
3795}
3796
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003797/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003798bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003799 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003800 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003801 if (getLangOptions().CPlusPlus)
Douglas Gregord6e44a32010-04-16 22:09:46 +00003802 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003803
Douglas Gregora873dfc2010-02-03 00:27:59 +00003804 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003805
3806 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3807 // type needs to be scalar.
3808 if (castType->isVoidType()) {
3809 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003810 Kind = CastExpr::CK_ToVoid;
3811 return false;
3812 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003813
Anders Carlssonebeaf202009-10-16 02:35:04 +00003814 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003815 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003816 (castType->isStructureType() || castType->isUnionType())) {
3817 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003818 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003819 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3820 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003821 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003822 return false;
3823 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003824
Anders Carlssonc3516322009-10-16 02:48:28 +00003825 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003826 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003827 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003828 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003829 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003830 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003831 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003832 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003833 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3834 << castExpr->getSourceRange();
3835 break;
3836 }
3837 }
3838 if (Field == FieldEnd)
3839 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3840 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003841 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003842 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003843 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003844
Anders Carlssonc3516322009-10-16 02:48:28 +00003845 // Reject any other conversions to non-scalar types.
3846 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3847 << castType << castExpr->getSourceRange();
3848 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003849
3850 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003851 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003852 return Diag(castExpr->getLocStart(),
3853 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003854 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003855 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003856
3857 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003858 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003859
Anders Carlssonc3516322009-10-16 02:48:28 +00003860 if (castType->isVectorType())
3861 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3862 if (castExpr->getType()->isVectorType())
3863 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3864
Anders Carlsson16a89042009-10-16 05:23:41 +00003865 if (isa<ObjCSelectorExpr>(castExpr))
3866 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003867
Anders Carlssonc3516322009-10-16 02:48:28 +00003868 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003869 QualType castExprType = castExpr->getType();
3870 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3871 return Diag(castExpr->getLocStart(),
3872 diag::err_cast_pointer_from_non_pointer_int)
3873 << castExprType << castExpr->getSourceRange();
3874 } else if (!castExpr->getType()->isArithmeticType()) {
3875 if (!castType->isIntegralType() && castType->isArithmeticType())
3876 return Diag(castExpr->getLocStart(),
3877 diag::err_cast_pointer_to_non_pointer_int)
3878 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003879 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003880
3881 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003882 return false;
3883}
3884
Anders Carlssonc3516322009-10-16 02:48:28 +00003885bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3886 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003887 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003888
Anders Carlssona64db8f2007-11-27 05:51:55 +00003889 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003890 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003891 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003892 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003893 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003894 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003895 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003896 } else
3897 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003898 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003899 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003900
Anders Carlssonc3516322009-10-16 02:48:28 +00003901 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003902 return false;
3903}
3904
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003905bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00003906 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003907 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003908
Anders Carlsson16a89042009-10-16 05:23:41 +00003909 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003910
Nate Begeman9b10da62009-06-27 22:05:55 +00003911 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3912 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003913 if (SrcTy->isVectorType()) {
3914 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3915 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3916 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003917 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003918 return false;
3919 }
3920
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003921 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003922 // conversion will take place first from scalar to elt type, and then
3923 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003924 if (SrcTy->isPointerType())
3925 return Diag(R.getBegin(),
3926 diag::err_invalid_conversion_between_vector_and_scalar)
3927 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003928
3929 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3930 ImpCastExprToType(CastExpr, DestElemTy,
3931 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003932
Anders Carlsson16a89042009-10-16 05:23:41 +00003933 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003934 return false;
3935}
3936
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003937Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003938Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003939 SourceLocation RParenLoc, ExprArg Op) {
3940 assert((Ty != 0) && (Op.get() != 0) &&
3941 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003942
John McCall9d125032010-01-15 18:39:57 +00003943 TypeSourceInfo *castTInfo;
3944 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3945 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00003946 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Nate Begeman2ef13e52009-08-10 23:49:36 +00003948 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00003949 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003950 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00003951 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3952 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00003953
3954 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3955}
3956
3957Action::OwningExprResult
3958Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3959 SourceLocation RParenLoc, ExprArg Op) {
3960 Expr *castExpr = static_cast<Expr*>(Op.get());
3961
John McCallb042fdf2010-01-15 18:56:44 +00003962 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3963 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Douglas Gregord6e44a32010-04-16 22:09:46 +00003964 Kind))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003965 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003966
Douglas Gregord6e44a32010-04-16 22:09:46 +00003967 Op.release();
John McCallb042fdf2010-01-15 18:56:44 +00003968 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3969 Kind, castExpr, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003970 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003971}
3972
Nate Begeman2ef13e52009-08-10 23:49:36 +00003973/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3974/// of comma binary operators.
3975Action::OwningExprResult
3976Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3977 Expr *expr = EA.takeAs<Expr>();
3978 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3979 if (!E)
3980 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Nate Begeman2ef13e52009-08-10 23:49:36 +00003982 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Nate Begeman2ef13e52009-08-10 23:49:36 +00003984 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3985 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3986 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Nate Begeman2ef13e52009-08-10 23:49:36 +00003988 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3989}
3990
3991Action::OwningExprResult
3992Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3993 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00003994 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003995 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00003996 QualType Ty = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003997
3998 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003999 // then handle it as such.
4000 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4001 if (PE->getNumExprs() == 0) {
4002 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4003 return ExprError();
4004 }
4005
4006 llvm::SmallVector<Expr *, 8> initExprs;
4007 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4008 initExprs.push_back(PE->getExpr(i));
4009
4010 // FIXME: This means that pretty-printing the final AST will produce curly
4011 // braces instead of the original commas.
4012 Op.release();
Ted Kremenek709210f2010-04-13 23:39:13 +00004013 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4014 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004015 initExprs.size(), RParenLoc);
4016 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004017 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004018 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004019 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004020 // sequence of BinOp comma operators.
4021 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004022 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004023 }
4024}
4025
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004026Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004027 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004028 MultiExprArg Val,
4029 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004030 unsigned nexprs = Val.size();
4031 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004032 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4033 Expr *expr;
4034 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4035 expr = new (Context) ParenExpr(L, R, exprs[0]);
4036 else
4037 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004038 return Owned(expr);
4039}
4040
Sebastian Redl28507842009-02-26 14:39:58 +00004041/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4042/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004043/// C99 6.5.15
4044QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4045 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004046 // C++ is sufficiently different to merit its own checker.
4047 if (getLangOptions().CPlusPlus)
4048 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4049
John McCalld1b47bf2010-03-11 19:43:18 +00004050 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00004051
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004052 UsualUnaryConversions(Cond);
4053 UsualUnaryConversions(LHS);
4054 UsualUnaryConversions(RHS);
4055 QualType CondTy = Cond->getType();
4056 QualType LHSTy = LHS->getType();
4057 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004058
Reid Spencer5f016e22007-07-11 17:01:13 +00004059 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004060 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4061 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4062 << CondTy;
4063 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004064 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004065
Chris Lattner70d67a92008-01-06 22:42:25 +00004066 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004067 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4068 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004069
Chris Lattner70d67a92008-01-06 22:42:25 +00004070 // If both operands have arithmetic type, do the usual arithmetic conversions
4071 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004072 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4073 UsualArithmeticConversions(LHS, RHS);
4074 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004075 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004076
Chris Lattner70d67a92008-01-06 22:42:25 +00004077 // If both operands are the same structure or union type, the result is that
4078 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004079 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4080 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004081 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004082 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004083 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004084 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004085 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004086 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004087
Chris Lattner70d67a92008-01-06 22:42:25 +00004088 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004089 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004090 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4091 if (!LHSTy->isVoidType())
4092 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4093 << RHS->getSourceRange();
4094 if (!RHSTy->isVoidType())
4095 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4096 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004097 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4098 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004099 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004100 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004101 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4102 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004103 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004104 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004105 // promote the null to a pointer.
4106 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004107 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004108 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004109 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004110 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004111 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004112 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004113 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004114
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004115 // All objective-c pointer type analysis is done here.
4116 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4117 QuestionLoc);
4118 if (!compositeType.isNull())
4119 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004120
4121
Steve Naroff7154a772009-07-01 14:36:47 +00004122 // Handle block pointer types.
4123 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4124 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4125 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4126 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004127 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4128 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004129 return destType;
4130 }
4131 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004132 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004133 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004134 }
Steve Naroff7154a772009-07-01 14:36:47 +00004135 // We have 2 block pointer types.
4136 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4137 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004138 return LHSTy;
4139 }
Steve Naroff7154a772009-07-01 14:36:47 +00004140 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004141 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4142 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004143
Steve Naroff7154a772009-07-01 14:36:47 +00004144 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4145 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004146 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004147 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004148 // In this situation, we assume void* type. No especially good
4149 // reason, but this is what gcc does, and we do have to pick
4150 // to get a consistent AST.
4151 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004152 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4153 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004154 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004155 }
Steve Naroff7154a772009-07-01 14:36:47 +00004156 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004157 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4158 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004159 return LHSTy;
4160 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004161
Steve Naroff7154a772009-07-01 14:36:47 +00004162 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4163 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4164 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004165 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4166 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004167
4168 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4169 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4170 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004171 QualType destPointee
4172 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004173 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004174 // Add qualifiers if necessary.
4175 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4176 // Promote to void*.
4177 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004178 return destType;
4179 }
4180 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004181 QualType destPointee
4182 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004183 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004184 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004185 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004186 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004187 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004188 return destType;
4189 }
4190
4191 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4192 // Two identical pointer types are always compatible.
4193 return LHSTy;
4194 }
4195 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4196 rhptee.getUnqualifiedType())) {
4197 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4198 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4199 // In this situation, we assume void* type. No especially good
4200 // reason, but this is what gcc does, and we do have to pick
4201 // to get a consistent AST.
4202 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004203 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4204 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004205 return incompatTy;
4206 }
4207 // The pointer types are compatible.
4208 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4209 // differently qualified versions of compatible types, the result type is
4210 // a pointer to an appropriately qualified version of the *composite*
4211 // type.
4212 // FIXME: Need to calculate the composite type.
4213 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004214 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4215 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004216 return LHSTy;
4217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Steve Naroff7154a772009-07-01 14:36:47 +00004219 // GCC compatibility: soften pointer/integer mismatch.
4220 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4221 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4222 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004223 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004224 return RHSTy;
4225 }
4226 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4227 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4228 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004229 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004230 return LHSTy;
4231 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004232
Chris Lattner70d67a92008-01-06 22:42:25 +00004233 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004234 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4235 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004236 return QualType();
4237}
4238
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004239/// FindCompositeObjCPointerType - Helper method to find composite type of
4240/// two objective-c pointer types of the two input expressions.
4241QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4242 SourceLocation QuestionLoc) {
4243 QualType LHSTy = LHS->getType();
4244 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004245
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004246 // Handle things like Class and struct objc_class*. Here we case the result
4247 // to the pseudo-builtin, because that will be implicitly cast back to the
4248 // redefinition type if an attempt is made to access its fields.
4249 if (LHSTy->isObjCClassType() &&
4250 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4251 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4252 return LHSTy;
4253 }
4254 if (RHSTy->isObjCClassType() &&
4255 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4256 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4257 return RHSTy;
4258 }
4259 // And the same for struct objc_object* / id
4260 if (LHSTy->isObjCIdType() &&
4261 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4262 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4263 return LHSTy;
4264 }
4265 if (RHSTy->isObjCIdType() &&
4266 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4267 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4268 return RHSTy;
4269 }
4270 // And the same for struct objc_selector* / SEL
4271 if (Context.isObjCSelType(LHSTy) &&
4272 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4273 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4274 return LHSTy;
4275 }
4276 if (Context.isObjCSelType(RHSTy) &&
4277 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4278 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4279 return RHSTy;
4280 }
4281 // Check constraints for Objective-C object pointers types.
4282 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004283
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004284 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4285 // Two identical object pointer types are always compatible.
4286 return LHSTy;
4287 }
4288 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4289 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4290 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004291
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004292 // If both operands are interfaces and either operand can be
4293 // assigned to the other, use that type as the composite
4294 // type. This allows
4295 // xxx ? (A*) a : (B*) b
4296 // where B is a subclass of A.
4297 //
4298 // Additionally, as for assignment, if either type is 'id'
4299 // allow silent coercion. Finally, if the types are
4300 // incompatible then make sure to use 'id' as the composite
4301 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004302
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004303 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4304 // It could return the composite type.
4305 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4306 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4307 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4308 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4309 } else if ((LHSTy->isObjCQualifiedIdType() ||
4310 RHSTy->isObjCQualifiedIdType()) &&
4311 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4312 // Need to handle "id<xx>" explicitly.
4313 // GCC allows qualified id and any Objective-C type to devolve to
4314 // id. Currently localizing to here until clear this should be
4315 // part of ObjCQualifiedIdTypesAreCompatible.
4316 compositeType = Context.getObjCIdType();
4317 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4318 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004319 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004320 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4321 ;
4322 else {
4323 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4324 << LHSTy << RHSTy
4325 << LHS->getSourceRange() << RHS->getSourceRange();
4326 QualType incompatTy = Context.getObjCIdType();
4327 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4328 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4329 return incompatTy;
4330 }
4331 // The object pointer types are compatible.
4332 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4333 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4334 return compositeType;
4335 }
4336 // Check Objective-C object pointer types and 'void *'
4337 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4338 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4339 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4340 QualType destPointee
4341 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4342 QualType destType = Context.getPointerType(destPointee);
4343 // Add qualifiers if necessary.
4344 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4345 // Promote to void*.
4346 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4347 return destType;
4348 }
4349 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4350 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4351 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4352 QualType destPointee
4353 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4354 QualType destType = Context.getPointerType(destPointee);
4355 // Add qualifiers if necessary.
4356 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4357 // Promote to void*.
4358 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4359 return destType;
4360 }
4361 return QualType();
4362}
4363
Steve Narofff69936d2007-09-16 03:34:24 +00004364/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004365/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004366Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4367 SourceLocation ColonLoc,
4368 ExprArg Cond, ExprArg LHS,
4369 ExprArg RHS) {
4370 Expr *CondExpr = (Expr *) Cond.get();
4371 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004372
4373 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4374 // was the condition.
4375 bool isLHSNull = LHSExpr == 0;
4376 if (isLHSNull)
4377 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004378
4379 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004380 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004381 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004382 return ExprError();
4383
4384 Cond.release();
4385 LHS.release();
4386 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004387 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004388 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004389 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004390}
4391
Reid Spencer5f016e22007-07-11 17:01:13 +00004392// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004393// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004394// routine is it effectively iqnores the qualifiers on the top level pointee.
4395// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4396// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004397Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004398Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4399 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004400
David Chisnall0f436562009-08-17 16:35:33 +00004401 if ((lhsType->isObjCClassType() &&
4402 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4403 (rhsType->isObjCClassType() &&
4404 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4405 return Compatible;
4406 }
4407
Reid Spencer5f016e22007-07-11 17:01:13 +00004408 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004409 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4410 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004411
Reid Spencer5f016e22007-07-11 17:01:13 +00004412 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004413 lhptee = Context.getCanonicalType(lhptee);
4414 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004415
Chris Lattner5cf216b2008-01-04 18:04:52 +00004416 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004417
4418 // C99 6.5.16.1p1: This following citation is common to constraints
4419 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4420 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004421 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004422 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004423 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004424
Mike Stumpeed9cac2009-02-19 03:04:26 +00004425 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4426 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004427 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004428 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004429 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004430 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004431
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004432 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004433 assert(rhptee->isFunctionType());
4434 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004435 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004437 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004438 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004439 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004440
4441 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004442 assert(lhptee->isFunctionType());
4443 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004445 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004446 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004447 lhptee = lhptee.getUnqualifiedType();
4448 rhptee = rhptee.getUnqualifiedType();
4449 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4450 // Check if the pointee types are compatible ignoring the sign.
4451 // We explicitly check for char so that we catch "char" vs
4452 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004453 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004454 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004455 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004456 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004457
Chris Lattner6a2b9262009-10-17 20:33:28 +00004458 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004459 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004460 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004461 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004462
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004463 if (lhptee == rhptee) {
4464 // Types are compatible ignoring the sign. Qualifier incompatibility
4465 // takes priority over sign incompatibility because the sign
4466 // warning can be disabled.
4467 if (ConvTy != Compatible)
4468 return ConvTy;
4469 return IncompatiblePointerSign;
4470 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004471
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004472 // If we are a multi-level pointer, it's possible that our issue is simply
4473 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4474 // the eventual target type is the same and the pointers have the same
4475 // level of indirection, this must be the issue.
4476 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4477 do {
4478 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4479 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004480
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004481 lhptee = Context.getCanonicalType(lhptee);
4482 rhptee = Context.getCanonicalType(rhptee);
4483 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004484
Douglas Gregora4923eb2009-11-16 21:35:15 +00004485 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004486 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004487 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004488
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004489 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004490 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004491 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004492 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004493}
4494
Steve Naroff1c7d0672008-09-04 15:10:53 +00004495/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4496/// block pointer types are compatible or whether a block and normal pointer
4497/// are compatible. It is more restrict than comparing two function pointer
4498// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004499Sema::AssignConvertType
4500Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004501 QualType rhsType) {
4502 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004503
Steve Naroff1c7d0672008-09-04 15:10:53 +00004504 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004505 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4506 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004507
Steve Naroff1c7d0672008-09-04 15:10:53 +00004508 // make sure we operate on the canonical type
4509 lhptee = Context.getCanonicalType(lhptee);
4510 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004511
Steve Naroff1c7d0672008-09-04 15:10:53 +00004512 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004513
Steve Naroff1c7d0672008-09-04 15:10:53 +00004514 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004515 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004516 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004517
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004518 if (!getLangOptions().CPlusPlus) {
4519 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4520 return IncompatibleBlockPointer;
4521 }
4522 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004523 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004524 return ConvTy;
4525}
4526
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004527/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4528/// for assignment compatibility.
4529Sema::AssignConvertType
4530Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004531 if (lhsType->isObjCBuiltinType()) {
4532 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004533 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4534 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004535 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004536 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004537 }
4538 if (rhsType->isObjCBuiltinType()) {
4539 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004540 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4541 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004542 return IncompatiblePointer;
4543 return Compatible;
4544 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004545 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004546 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004547 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004548 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4549 // make sure we operate on the canonical type
4550 lhptee = Context.getCanonicalType(lhptee);
4551 rhptee = Context.getCanonicalType(rhptee);
4552 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4553 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004554
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004555 if (Context.typesAreCompatible(lhsType, rhsType))
4556 return Compatible;
4557 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4558 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004559 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004560}
4561
Mike Stumpeed9cac2009-02-19 03:04:26 +00004562/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4563/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004564/// pointers. Here are some objectionable examples that GCC considers warnings:
4565///
4566/// int a, *pint;
4567/// short *pshort;
4568/// struct foo *pfoo;
4569///
4570/// pint = pshort; // warning: assignment from incompatible pointer type
4571/// a = pint; // warning: assignment makes integer from pointer without a cast
4572/// pint = a; // warning: assignment makes pointer from integer without a cast
4573/// pint = pfoo; // warning: assignment from incompatible pointer type
4574///
4575/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004576/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004577///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004578Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004579Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004580 // Get canonical types. We're not formatting these types, just comparing
4581 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004582 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4583 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004584
4585 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004586 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004587
David Chisnall0f436562009-08-17 16:35:33 +00004588 if ((lhsType->isObjCClassType() &&
4589 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4590 (rhsType->isObjCClassType() &&
4591 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4592 return Compatible;
4593 }
4594
Douglas Gregor9d293df2008-10-28 00:22:11 +00004595 // If the left-hand side is a reference type, then we are in a
4596 // (rare!) case where we've allowed the use of references in C,
4597 // e.g., as a parameter type in a built-in function. In this case,
4598 // just make sure that the type referenced is compatible with the
4599 // right-hand side type. The caller is responsible for adjusting
4600 // lhsType so that the resulting expression does not have reference
4601 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004602 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004603 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004604 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004605 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004606 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004607 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4608 // to the same ExtVector type.
4609 if (lhsType->isExtVectorType()) {
4610 if (rhsType->isExtVectorType())
4611 return lhsType == rhsType ? Compatible : Incompatible;
4612 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4613 return Compatible;
4614 }
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Nate Begemanbe2341d2008-07-14 18:02:46 +00004616 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004617 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004618 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004619 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004620 if (getLangOptions().LaxVectorConversions &&
4621 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004622 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004623 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004624 }
4625 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004626 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004627
Chris Lattnere8b3e962008-01-04 23:32:24 +00004628 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004629 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004630
Chris Lattner78eca282008-04-07 06:49:41 +00004631 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004632 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004633 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004634
Chris Lattner78eca282008-04-07 06:49:41 +00004635 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004636 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004638 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004639 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004640 if (lhsType->isVoidPointerType()) // an exception to the rule.
4641 return Compatible;
4642 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004643 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004644 if (rhsType->getAs<BlockPointerType>()) {
4645 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004646 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004647
4648 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004649 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004650 return Compatible;
4651 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004652 return Incompatible;
4653 }
4654
4655 if (isa<BlockPointerType>(lhsType)) {
4656 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004657 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004658
Steve Naroffb4406862008-09-29 18:10:17 +00004659 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004660 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004661 return Compatible;
4662
Steve Naroff1c7d0672008-09-04 15:10:53 +00004663 if (rhsType->isBlockPointerType())
4664 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004665
Ted Kremenek6217b802009-07-29 21:53:49 +00004666 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004667 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004668 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004669 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004670 return Incompatible;
4671 }
4672
Steve Naroff14108da2009-07-10 23:34:53 +00004673 if (isa<ObjCObjectPointerType>(lhsType)) {
4674 if (rhsType->isIntegerType())
4675 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004677 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004678 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004679 if (rhsType->isVoidPointerType()) // an exception to the rule.
4680 return Compatible;
4681 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004682 }
4683 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004684 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004685 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004686 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004687 if (RHSPT->getPointeeType()->isVoidType())
4688 return Compatible;
4689 }
4690 // Treat block pointers as objects.
4691 if (rhsType->isBlockPointerType())
4692 return Compatible;
4693 return Incompatible;
4694 }
Chris Lattner78eca282008-04-07 06:49:41 +00004695 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004696 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004697 if (lhsType == Context.BoolTy)
4698 return Compatible;
4699
4700 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004701 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004702
Mike Stumpeed9cac2009-02-19 03:04:26 +00004703 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004704 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004705
4706 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004707 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004708 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004709 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004710 }
Steve Naroff14108da2009-07-10 23:34:53 +00004711 if (isa<ObjCObjectPointerType>(rhsType)) {
4712 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4713 if (lhsType == Context.BoolTy)
4714 return Compatible;
4715
4716 if (lhsType->isIntegerType())
4717 return PointerToInt;
4718
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004719 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004720 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004721 if (lhsType->isVoidPointerType()) // an exception to the rule.
4722 return Compatible;
4723 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004724 }
4725 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004726 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004727 return Compatible;
4728 return Incompatible;
4729 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004730
Chris Lattnerfc144e22008-01-04 23:18:45 +00004731 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004732 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004733 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004734 }
4735 return Incompatible;
4736}
4737
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004738/// \brief Constructs a transparent union from an expression that is
4739/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004740static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004741 QualType UnionType, FieldDecl *Field) {
4742 // Build an initializer list that designates the appropriate member
4743 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00004744 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00004745 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004746 SourceLocation());
4747 Initializer->setType(UnionType);
4748 Initializer->setInitializedFieldInUnion(Field);
4749
4750 // Build a compound literal constructing a value of the transparent
4751 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004752 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004753 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004754 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004755}
4756
4757Sema::AssignConvertType
4758Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4759 QualType FromType = rExpr->getType();
4760
Mike Stump1eb44332009-09-09 15:08:12 +00004761 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004762 // transparent_union GCC extension.
4763 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004764 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004765 return Incompatible;
4766
4767 // The field to initialize within the transparent union.
4768 RecordDecl *UD = UT->getDecl();
4769 FieldDecl *InitField = 0;
4770 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004771 for (RecordDecl::field_iterator it = UD->field_begin(),
4772 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004773 it != itend; ++it) {
4774 if (it->getType()->isPointerType()) {
4775 // If the transparent union contains a pointer type, we allow:
4776 // 1) void pointer
4777 // 2) null pointer constant
4778 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004779 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004780 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004781 InitField = *it;
4782 break;
4783 }
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004785 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004786 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004787 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004788 InitField = *it;
4789 break;
4790 }
4791 }
4792
4793 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4794 == Compatible) {
4795 InitField = *it;
4796 break;
4797 }
4798 }
4799
4800 if (!InitField)
4801 return Incompatible;
4802
4803 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4804 return Compatible;
4805}
4806
Chris Lattner5cf216b2008-01-04 18:04:52 +00004807Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004808Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004809 if (getLangOptions().CPlusPlus) {
4810 if (!lhsType->isRecordType()) {
4811 // C++ 5.17p3: If the left operand is not of class type, the
4812 // expression is implicitly converted (C++ 4) to the
4813 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004814 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004815 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004816 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004817 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004818 }
4819
4820 // FIXME: Currently, we fall through and treat C++ classes like C
4821 // structures.
4822 }
4823
Steve Naroff529a4ad2007-11-27 17:58:44 +00004824 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4825 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004826 if ((lhsType->isPointerType() ||
4827 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004828 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004829 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004830 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004831 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004832 return Compatible;
4833 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004834
Chris Lattner943140e2007-10-16 02:55:40 +00004835 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004836 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004837 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004838 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004839 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004840 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004841 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004842 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004843
Chris Lattner5cf216b2008-01-04 18:04:52 +00004844 Sema::AssignConvertType result =
4845 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004846
Steve Narofff1120de2007-08-24 22:33:52 +00004847 // C99 6.5.16.1p2: The value of the right operand is converted to the
4848 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004849 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4850 // so that we can use references in built-in functions even in C.
4851 // The getNonReferenceType() call makes sure that the resulting expression
4852 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004853 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004854 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4855 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004856 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004857}
4858
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004859QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004860 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004861 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004862 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004863 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004864}
4865
Chris Lattner7ef655a2010-01-12 21:23:57 +00004866QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004867 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004868 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004869 QualType lhsType =
4870 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4871 QualType rhsType =
4872 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004873
Nate Begemanbe2341d2008-07-14 18:02:46 +00004874 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004875 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004876 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004877
Nate Begemanbe2341d2008-07-14 18:02:46 +00004878 // Handle the case of a vector & extvector type of the same size and element
4879 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004880 if (getLangOptions().LaxVectorConversions) {
4881 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004882 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4883 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004884 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004885 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004886 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004887 }
4888 }
4889 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004890
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004891 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4892 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4893 bool swapped = false;
4894 if (rhsType->isExtVectorType()) {
4895 swapped = true;
4896 std::swap(rex, lex);
4897 std::swap(rhsType, lhsType);
4898 }
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Nate Begemandde25982009-06-28 19:12:57 +00004900 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004901 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004902 QualType EltTy = LV->getElementType();
4903 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4904 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004905 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004906 if (swapped) std::swap(rex, lex);
4907 return lhsType;
4908 }
4909 }
4910 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4911 rhsType->isRealFloatingType()) {
4912 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004913 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004914 if (swapped) std::swap(rex, lex);
4915 return lhsType;
4916 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004917 }
4918 }
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Nate Begemandde25982009-06-28 19:12:57 +00004920 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004921 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004922 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004923 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004924 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004925}
4926
Chris Lattner7ef655a2010-01-12 21:23:57 +00004927QualType Sema::CheckMultiplyDivideOperands(
4928 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004929 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004930 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004931
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004932 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004933
Chris Lattner7ef655a2010-01-12 21:23:57 +00004934 if (!lex->getType()->isArithmeticType() ||
4935 !rex->getType()->isArithmeticType())
4936 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004937
Chris Lattner7ef655a2010-01-12 21:23:57 +00004938 // Check for division by zero.
4939 if (isDiv &&
4940 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004941 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00004942 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004943
Chris Lattner7ef655a2010-01-12 21:23:57 +00004944 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004945}
4946
Chris Lattner7ef655a2010-01-12 21:23:57 +00004947QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004948 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004949 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4950 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4951 return CheckVectorOperands(Loc, lex, rex);
4952 return InvalidOperands(Loc, lex, rex);
4953 }
Steve Naroff90045e82007-07-13 23:32:42 +00004954
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004955 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004956
Chris Lattner7ef655a2010-01-12 21:23:57 +00004957 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4958 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004959
Chris Lattner7ef655a2010-01-12 21:23:57 +00004960 // Check for remainder by zero.
4961 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004962 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4963 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004964
Chris Lattner7ef655a2010-01-12 21:23:57 +00004965 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004966}
4967
Chris Lattner7ef655a2010-01-12 21:23:57 +00004968QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004969 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004970 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4971 QualType compType = CheckVectorOperands(Loc, lex, rex);
4972 if (CompLHSTy) *CompLHSTy = compType;
4973 return compType;
4974 }
Steve Naroff49b45262007-07-13 16:58:59 +00004975
Eli Friedmanab3a8522009-03-28 01:22:36 +00004976 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004977
Reid Spencer5f016e22007-07-11 17:01:13 +00004978 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004979 if (lex->getType()->isArithmeticType() &&
4980 rex->getType()->isArithmeticType()) {
4981 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004982 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004983 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004984
Eli Friedmand72d16e2008-05-18 18:08:51 +00004985 // Put any potential pointer into PExp
4986 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004987 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004988 std::swap(PExp, IExp);
4989
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004990 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004991
Eli Friedmand72d16e2008-05-18 18:08:51 +00004992 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004993 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Chris Lattnerb5f15622009-04-24 23:50:08 +00004995 // Check for arithmetic on pointers to incomplete types.
4996 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004997 if (getLangOptions().CPlusPlus) {
4998 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004999 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005000 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005001 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005002
5003 // GNU extension: arithmetic on pointer to void
5004 Diag(Loc, diag::ext_gnu_void_ptr)
5005 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005006 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005007 if (getLangOptions().CPlusPlus) {
5008 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5009 << lex->getType() << lex->getSourceRange();
5010 return QualType();
5011 }
5012
5013 // GNU extension: arithmetic on pointer to function
5014 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5015 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005016 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005017 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005018 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005019 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005020 PExp->getType()->isObjCObjectPointerType()) &&
5021 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005022 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5023 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005024 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005025 return QualType();
5026 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005027 // Diagnose bad cases where we step over interface counts.
5028 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5029 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5030 << PointeeTy << PExp->getSourceRange();
5031 return QualType();
5032 }
Mike Stump1eb44332009-09-09 15:08:12 +00005033
Eli Friedmanab3a8522009-03-28 01:22:36 +00005034 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005035 QualType LHSTy = Context.isPromotableBitField(lex);
5036 if (LHSTy.isNull()) {
5037 LHSTy = lex->getType();
5038 if (LHSTy->isPromotableIntegerType())
5039 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005040 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005041 *CompLHSTy = LHSTy;
5042 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005043 return PExp->getType();
5044 }
5045 }
5046
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005047 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005048}
5049
Chris Lattnereca7be62008-04-07 05:30:13 +00005050// C99 6.5.6
5051QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005052 SourceLocation Loc, QualType* CompLHSTy) {
5053 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5054 QualType compType = CheckVectorOperands(Loc, lex, rex);
5055 if (CompLHSTy) *CompLHSTy = compType;
5056 return compType;
5057 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005058
Eli Friedmanab3a8522009-03-28 01:22:36 +00005059 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005060
Chris Lattner6e4ab612007-12-09 21:53:25 +00005061 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005062
Chris Lattner6e4ab612007-12-09 21:53:25 +00005063 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005064 if (lex->getType()->isArithmeticType()
5065 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005066 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005067 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005068 }
Mike Stump1eb44332009-09-09 15:08:12 +00005069
Chris Lattner6e4ab612007-12-09 21:53:25 +00005070 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005071 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005072 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005073
Douglas Gregore7450f52009-03-24 19:52:54 +00005074 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005075
Douglas Gregore7450f52009-03-24 19:52:54 +00005076 bool ComplainAboutVoid = false;
5077 Expr *ComplainAboutFunc = 0;
5078 if (lpointee->isVoidType()) {
5079 if (getLangOptions().CPlusPlus) {
5080 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5081 << lex->getSourceRange() << rex->getSourceRange();
5082 return QualType();
5083 }
5084
5085 // GNU C extension: arithmetic on pointer to void
5086 ComplainAboutVoid = true;
5087 } else if (lpointee->isFunctionType()) {
5088 if (getLangOptions().CPlusPlus) {
5089 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005090 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005091 return QualType();
5092 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005093
5094 // GNU C extension: arithmetic on pointer to function
5095 ComplainAboutFunc = lex;
5096 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005097 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005098 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005099 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005100 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005101 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005102
Chris Lattnerb5f15622009-04-24 23:50:08 +00005103 // Diagnose bad cases where we step over interface counts.
5104 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5105 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5106 << lpointee << lex->getSourceRange();
5107 return QualType();
5108 }
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Chris Lattner6e4ab612007-12-09 21:53:25 +00005110 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005111 if (rex->getType()->isIntegerType()) {
5112 if (ComplainAboutVoid)
5113 Diag(Loc, diag::ext_gnu_void_ptr)
5114 << lex->getSourceRange() << rex->getSourceRange();
5115 if (ComplainAboutFunc)
5116 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005117 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005118 << ComplainAboutFunc->getSourceRange();
5119
Eli Friedmanab3a8522009-03-28 01:22:36 +00005120 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005121 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005122 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005123
Chris Lattner6e4ab612007-12-09 21:53:25 +00005124 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005125 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005126 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005127
Douglas Gregore7450f52009-03-24 19:52:54 +00005128 // RHS must be a completely-type object type.
5129 // Handle the GNU void* extension.
5130 if (rpointee->isVoidType()) {
5131 if (getLangOptions().CPlusPlus) {
5132 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5133 << lex->getSourceRange() << rex->getSourceRange();
5134 return QualType();
5135 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005136
Douglas Gregore7450f52009-03-24 19:52:54 +00005137 ComplainAboutVoid = true;
5138 } else if (rpointee->isFunctionType()) {
5139 if (getLangOptions().CPlusPlus) {
5140 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005141 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005142 return QualType();
5143 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005144
5145 // GNU extension: arithmetic on pointer to function
5146 if (!ComplainAboutFunc)
5147 ComplainAboutFunc = rex;
5148 } else if (!rpointee->isDependentType() &&
5149 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005150 PDiag(diag::err_typecheck_sub_ptr_object)
5151 << rex->getSourceRange()
5152 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005153 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005154
Eli Friedman88d936b2009-05-16 13:54:38 +00005155 if (getLangOptions().CPlusPlus) {
5156 // Pointee types must be the same: C++ [expr.add]
5157 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5158 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5159 << lex->getType() << rex->getType()
5160 << lex->getSourceRange() << rex->getSourceRange();
5161 return QualType();
5162 }
5163 } else {
5164 // Pointee types must be compatible C99 6.5.6p3
5165 if (!Context.typesAreCompatible(
5166 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5167 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5168 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5169 << lex->getType() << rex->getType()
5170 << lex->getSourceRange() << rex->getSourceRange();
5171 return QualType();
5172 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005173 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005174
Douglas Gregore7450f52009-03-24 19:52:54 +00005175 if (ComplainAboutVoid)
5176 Diag(Loc, diag::ext_gnu_void_ptr)
5177 << lex->getSourceRange() << rex->getSourceRange();
5178 if (ComplainAboutFunc)
5179 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005180 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005181 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005182
5183 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005184 return Context.getPointerDiffType();
5185 }
5186 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005187
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005188 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005189}
5190
Chris Lattnereca7be62008-04-07 05:30:13 +00005191// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005192QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005193 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005194 // C99 6.5.7p2: Each of the operands shall have integer type.
5195 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005196 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005197
Nate Begeman2207d792009-10-25 02:26:48 +00005198 // Vector shifts promote their scalar inputs to vector type.
5199 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5200 return CheckVectorOperands(Loc, lex, rex);
5201
Chris Lattnerca5eede2007-12-12 05:47:28 +00005202 // Shifts don't perform usual arithmetic conversions, they just do integer
5203 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005204 QualType LHSTy = Context.isPromotableBitField(lex);
5205 if (LHSTy.isNull()) {
5206 LHSTy = lex->getType();
5207 if (LHSTy->isPromotableIntegerType())
5208 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005209 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005210 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005211 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005212
Chris Lattnerca5eede2007-12-12 05:47:28 +00005213 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005214
Ryan Flynnd0439682009-08-07 16:20:20 +00005215 // Sanity-check shift operands
5216 llvm::APSInt Right;
5217 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005218 if (!rex->isValueDependent() &&
5219 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005220 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005221 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5222 else {
5223 llvm::APInt LeftBits(Right.getBitWidth(),
5224 Context.getTypeSize(lex->getType()));
5225 if (Right.uge(LeftBits))
5226 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5227 }
5228 }
5229
Chris Lattnerca5eede2007-12-12 05:47:28 +00005230 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005231 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005232}
5233
Douglas Gregor0c6db942009-05-04 06:07:12 +00005234// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005235QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005236 unsigned OpaqueOpc, bool isRelational) {
5237 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5238
Chris Lattner02dd4b12009-12-05 05:40:13 +00005239 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005240 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005241 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005242
John McCalld1b47bf2010-03-11 19:43:18 +00005243 CheckSignCompare(lex, rex, Loc, &Opc);
John McCall45aa4552009-11-05 00:40:04 +00005244
Chris Lattnera5937dd2007-08-26 01:18:55 +00005245 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005246 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5247 UsualArithmeticConversions(lex, rex);
5248 else {
5249 UsualUnaryConversions(lex);
5250 UsualUnaryConversions(rex);
5251 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005252 QualType lType = lex->getType();
5253 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005254
Mike Stumpaf199f32009-05-07 18:43:07 +00005255 if (!lType->isFloatingType()
5256 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005257 // For non-floating point types, check for self-comparisons of the form
5258 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5259 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005260 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005261 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005262 Expr *LHSStripped = lex->IgnoreParens();
5263 Expr *RHSStripped = rex->IgnoreParens();
5264 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5265 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005266 if (DRL->getDecl() == DRR->getDecl() &&
5267 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005268 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Chris Lattner55660a72009-03-08 19:39:53 +00005270 if (isa<CastExpr>(LHSStripped))
5271 LHSStripped = LHSStripped->IgnoreParenCasts();
5272 if (isa<CastExpr>(RHSStripped))
5273 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Chris Lattner55660a72009-03-08 19:39:53 +00005275 // Warn about comparisons against a string constant (unless the other
5276 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005277 Expr *literalString = 0;
5278 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005279 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005280 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005281 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005282 literalString = lex;
5283 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005284 } else if ((isa<StringLiteral>(RHSStripped) ||
5285 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005286 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005287 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005288 literalString = rex;
5289 literalStringStripped = RHSStripped;
5290 }
5291
5292 if (literalString) {
5293 std::string resultComparison;
5294 switch (Opc) {
5295 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5296 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5297 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5298 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5299 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5300 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5301 default: assert(false && "Invalid comparison operator");
5302 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005303
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005304 DiagRuntimeBehavior(Loc,
5305 PDiag(diag::warn_stringcompare)
5306 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00005307 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00005308 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005309 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005310
Douglas Gregor447b69e2008-11-19 03:25:36 +00005311 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005312 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005313
Chris Lattnera5937dd2007-08-26 01:18:55 +00005314 if (isRelational) {
5315 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005316 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005317 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005318 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005319 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005320 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005321
Chris Lattnera5937dd2007-08-26 01:18:55 +00005322 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005323 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005324 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005325
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005326 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005327 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005328 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005329 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005330
Chris Lattnera5937dd2007-08-26 01:18:55 +00005331 // All of the following pointer related warnings are GCC extensions, except
5332 // when handling null pointer constants. One day, we can consider making them
5333 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005334 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005335 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005336 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005337 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005338 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339
Douglas Gregor0c6db942009-05-04 06:07:12 +00005340 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005341 if (LCanPointeeTy == RCanPointeeTy)
5342 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005343 if (!isRelational &&
5344 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5345 // Valid unless comparison between non-null pointer and function pointer
5346 // This is a gcc extension compatibility comparison.
5347 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5348 && !LHSIsNull && !RHSIsNull) {
5349 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5350 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5351 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5352 return ResultTy;
5353 }
5354 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005355 // C++ [expr.rel]p2:
5356 // [...] Pointer conversions (4.10) and qualification
5357 // conversions (4.4) are performed on pointer operands (or on
5358 // a pointer operand and a null pointer constant) to bring
5359 // them to their composite pointer type. [...]
5360 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005361 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005362 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005363 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005364 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005365 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005366 if (T.isNull()) {
5367 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5368 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5369 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005370 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005371 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005372 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005373 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005374 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005375 }
5376
Eli Friedman73c39ab2009-10-20 08:27:19 +00005377 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5378 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005379 return ResultTy;
5380 }
Eli Friedman3075e762009-08-23 00:27:47 +00005381 // C99 6.5.9p2 and C99 6.5.8p2
5382 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5383 RCanPointeeTy.getUnqualifiedType())) {
5384 // Valid unless a relational comparison of function pointers
5385 if (isRelational && LCanPointeeTy->isFunctionType()) {
5386 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5387 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5388 }
5389 } else if (!isRelational &&
5390 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5391 // Valid unless comparison between non-null pointer and function pointer
5392 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5393 && !LHSIsNull && !RHSIsNull) {
5394 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5395 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5396 }
5397 } else {
5398 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005399 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005400 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005401 }
Eli Friedman3075e762009-08-23 00:27:47 +00005402 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005403 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005404 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005405 }
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005407 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005408 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005409 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005410 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005411 (lType->isPointerType() ||
5412 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005413 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005414 return ResultTy;
5415 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005416 if (LHSIsNull &&
5417 (rType->isPointerType() ||
5418 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005419 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005420 return ResultTy;
5421 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005422
5423 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005424 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005425 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5426 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005427 // In addition, pointers to members can be compared, or a pointer to
5428 // member and a null pointer constant. Pointer to member conversions
5429 // (4.11) and qualification conversions (4.4) are performed to bring
5430 // them to a common type. If one operand is a null pointer constant,
5431 // the common type is the type of the other operand. Otherwise, the
5432 // common type is a pointer to member type similar (4.4) to the type
5433 // of one of the operands, with a cv-qualification signature (4.4)
5434 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005435 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005436 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005437 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005438 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005439 if (T.isNull()) {
5440 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005441 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005442 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005443 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005444 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005445 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005446 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005447 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005448 }
Mike Stump1eb44332009-09-09 15:08:12 +00005449
Eli Friedman73c39ab2009-10-20 08:27:19 +00005450 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5451 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005452 return ResultTy;
5453 }
Mike Stump1eb44332009-09-09 15:08:12 +00005454
Douglas Gregor20b3e992009-08-24 17:42:35 +00005455 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005456 if (lType->isNullPtrType() && rType->isNullPtrType())
5457 return ResultTy;
5458 }
Mike Stump1eb44332009-09-09 15:08:12 +00005459
Steve Naroff1c7d0672008-09-04 15:10:53 +00005460 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005461 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005462 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5463 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005464
Steve Naroff1c7d0672008-09-04 15:10:53 +00005465 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005466 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005467 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005468 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005469 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005470 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005471 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005472 }
Steve Naroff59f53942008-09-28 01:11:11 +00005473 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005474 if (!isRelational
5475 && ((lType->isBlockPointerType() && rType->isPointerType())
5476 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005477 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005478 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005479 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005480 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005481 ->getPointeeType()->isVoidType())))
5482 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005484 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005485 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005486 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005487 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005488
Steve Naroff14108da2009-07-10 23:34:53 +00005489 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005490 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005491 const PointerType *LPT = lType->getAs<PointerType>();
5492 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005493 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005494 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005495 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005496 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005497
Steve Naroffa8069f12008-11-17 19:49:16 +00005498 if (!LPtrToVoid && !RPtrToVoid &&
5499 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005500 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005501 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005502 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005503 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005504 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005505 }
Steve Naroff14108da2009-07-10 23:34:53 +00005506 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005507 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005508 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5509 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005510 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005511 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005512 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005513 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005514 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005515 unsigned DiagID = 0;
5516 if (RHSIsNull) {
5517 if (isRelational)
5518 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5519 } else if (isRelational)
5520 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5521 else
5522 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005523
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005524 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005525 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005526 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005527 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005528 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005529 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005530 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005531 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005532 unsigned DiagID = 0;
5533 if (LHSIsNull) {
5534 if (isRelational)
5535 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5536 } else if (isRelational)
5537 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5538 else
5539 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005540
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005541 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005542 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005543 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005544 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005545 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005546 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005547 }
Steve Naroff39218df2008-09-04 16:56:14 +00005548 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005549 if (!isRelational && RHSIsNull
5550 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005551 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005552 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005553 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005554 if (!isRelational && LHSIsNull
5555 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005556 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005557 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005558 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005559 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005560}
5561
Nate Begemanbe2341d2008-07-14 18:02:46 +00005562/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005563/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005564/// like a scalar comparison, a vector comparison produces a vector of integer
5565/// types.
5566QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005567 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005568 bool isRelational) {
5569 // Check to make sure we're operating on vectors of the same type and width,
5570 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005571 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005572 if (vType.isNull())
5573 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005574
Nate Begemanbe2341d2008-07-14 18:02:46 +00005575 QualType lType = lex->getType();
5576 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005577
Nate Begemanbe2341d2008-07-14 18:02:46 +00005578 // For non-floating point types, check for self-comparisons of the form
5579 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5580 // often indicate logic errors in the program.
5581 if (!lType->isFloatingType()) {
5582 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5583 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5584 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005585 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005586 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005587
Nate Begemanbe2341d2008-07-14 18:02:46 +00005588 // Check for comparisons of floating point operands using != and ==.
5589 if (!isRelational && lType->isFloatingType()) {
5590 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005591 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005592 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005593
Nate Begemanbe2341d2008-07-14 18:02:46 +00005594 // Return the type for the comparison, which is the same as vector type for
5595 // integer vectors, or an integer type of identical size and number of
5596 // elements for floating point vectors.
5597 if (lType->isIntegerType())
5598 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005599
John McCall183700f2009-09-21 23:43:11 +00005600 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005601 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005602 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005603 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005604 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005605 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5606
Mike Stumpeed9cac2009-02-19 03:04:26 +00005607 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005608 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005609 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5610}
5611
Reid Spencer5f016e22007-07-11 17:01:13 +00005612inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005613 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005614 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005615 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005616
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005617 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005618
Steve Naroffa4332e22007-07-17 00:58:39 +00005619 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005620 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005621 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005622}
5623
5624inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005625 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005626 if (!Context.getLangOptions().CPlusPlus) {
5627 UsualUnaryConversions(lex);
5628 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005629
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005630 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5631 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005632
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005633 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005634 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005635
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005636 // C++ [expr.log.and]p1
5637 // C++ [expr.log.or]p1
5638 // The operands are both implicitly converted to type bool (clause 4).
5639 StandardConversionSequence LHS;
5640 if (!IsStandardConversion(lex, Context.BoolTy,
5641 /*InOverloadResolution=*/false, LHS))
5642 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005643
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005644 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005645 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005646 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005647
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005648 StandardConversionSequence RHS;
5649 if (!IsStandardConversion(rex, Context.BoolTy,
5650 /*InOverloadResolution=*/false, RHS))
5651 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005652
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005653 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005654 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005655 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005656
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005657 // C++ [expr.log.and]p2
5658 // C++ [expr.log.or]p2
5659 // The result is a bool.
5660 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005661}
5662
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005663/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5664/// is a read-only property; return true if so. A readonly property expression
5665/// depends on various declarations and thus must be treated specially.
5666///
Mike Stump1eb44332009-09-09 15:08:12 +00005667static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005668 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5669 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5670 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5671 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005672 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005673 BaseType->getAsObjCInterfacePointerType())
5674 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5675 if (S.isPropertyReadonly(PDecl, IFace))
5676 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005677 }
5678 }
5679 return false;
5680}
5681
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005682/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5683/// emit an error and return true. If so, return false.
5684static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005685 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005686 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005687 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005688 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5689 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005690 if (IsLV == Expr::MLV_Valid)
5691 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005692
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005693 unsigned Diag = 0;
5694 bool NeedType = false;
5695 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005696 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005697 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005698 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5699 NeedType = true;
5700 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005701 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005702 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5703 NeedType = true;
5704 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005705 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005706 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5707 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005708 case Expr::MLV_Valid:
5709 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005710 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005711 case Expr::MLV_MemberFunction:
5712 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005713 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5714 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005715 case Expr::MLV_IncompleteType:
5716 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005717 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005718 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005719 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005720 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005721 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5722 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005723 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005724 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5725 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005726 case Expr::MLV_ReadonlyProperty:
5727 Diag = diag::error_readonly_property_assignment;
5728 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005729 case Expr::MLV_NoSetterProperty:
5730 Diag = diag::error_nosetter_property_assignment;
5731 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005732 case Expr::MLV_SubObjCPropertySetting:
5733 Diag = diag::error_no_subobject_property_setting;
5734 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005735 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005736
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005737 SourceRange Assign;
5738 if (Loc != OrigLoc)
5739 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005740 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005741 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005742 else
Mike Stump1eb44332009-09-09 15:08:12 +00005743 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005744 return true;
5745}
5746
5747
5748
5749// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005750QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5751 SourceLocation Loc,
5752 QualType CompoundType) {
5753 // Verify that LHS is a modifiable lvalue, and emit error if not.
5754 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005755 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005756
5757 QualType LHSType = LHS->getType();
5758 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005759
Chris Lattner5cf216b2008-01-04 18:04:52 +00005760 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005761 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005762 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005763 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005764 // Special case of NSObject attributes on c-style pointer types.
5765 if (ConvTy == IncompatiblePointer &&
5766 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005767 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005768 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005769 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005770 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005771
Chris Lattner2c156472008-08-21 18:04:13 +00005772 // If the RHS is a unary plus or minus, check to see if they = and + are
5773 // right next to each other. If so, the user may have typo'd "x =+ 4"
5774 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005775 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005776 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5777 RHSCheck = ICE->getSubExpr();
5778 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5779 if ((UO->getOpcode() == UnaryOperator::Plus ||
5780 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005781 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005782 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005783 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5784 // And there is a space or other character before the subexpr of the
5785 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005786 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5787 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005788 Diag(Loc, diag::warn_not_compound_assign)
5789 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5790 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005791 }
Chris Lattner2c156472008-08-21 18:04:13 +00005792 }
5793 } else {
5794 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005795 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005796 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005797
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005798 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005799 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005800 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801
Reid Spencer5f016e22007-07-11 17:01:13 +00005802 // C99 6.5.16p3: The type of an assignment expression is the type of the
5803 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005804 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005805 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5806 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005807 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005808 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005809 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005810}
5811
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005812// C99 6.5.17
5813QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005814 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00005815 // C++ does not perform this conversion (C++ [expr.comma]p1).
5816 if (!getLangOptions().CPlusPlus)
5817 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005818
5819 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5820 // incomplete in C++).
5821
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005822 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005823}
5824
Steve Naroff49b45262007-07-13 16:58:59 +00005825/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5826/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005827QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5828 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005829 if (Op->isTypeDependent())
5830 return Context.DependentTy;
5831
Chris Lattner3528d352008-11-21 07:05:48 +00005832 QualType ResType = Op->getType();
5833 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005834
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005835 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5836 // Decrement of bool is not allowed.
5837 if (!isInc) {
5838 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5839 return QualType();
5840 }
5841 // Increment of bool sets it to true, but is deprecated.
5842 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5843 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005844 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005845 } else if (ResType->isAnyPointerType()) {
5846 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005847
Chris Lattner3528d352008-11-21 07:05:48 +00005848 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005849 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005850 if (getLangOptions().CPlusPlus) {
5851 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5852 << Op->getSourceRange();
5853 return QualType();
5854 }
5855
5856 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005857 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005858 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005859 if (getLangOptions().CPlusPlus) {
5860 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5861 << Op->getType() << Op->getSourceRange();
5862 return QualType();
5863 }
5864
5865 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005866 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005867 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005868 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005869 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005870 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005871 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005872 // Diagnose bad cases where we step over interface counts.
5873 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5874 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5875 << PointeeTy << Op->getSourceRange();
5876 return QualType();
5877 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005878 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005879 // C99 does not support ++/-- on complex types, we allow as an extension.
5880 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005881 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005882 } else {
5883 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005884 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005885 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005886 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005887 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005888 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005889 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005890 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005891 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005892}
5893
Anders Carlsson369dee42008-02-01 07:15:58 +00005894/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005895/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005896/// where the declaration is needed for type checking. We only need to
5897/// handle cases when the expression references a function designator
5898/// or is an lvalue. Here are some examples:
5899/// - &(x) => x
5900/// - &*****f => f for f a function designator.
5901/// - &s.xx => s
5902/// - &s.zz[1].yy -> s, if zz is an array
5903/// - *(x + 1) -> x, if x is an array
5904/// - &"123"[2] -> 0
5905/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005906static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005907 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005908 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005909 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005910 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005911 // If this is an arrow operator, the address is an offset from
5912 // the base's value, so the object the base refers to is
5913 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005914 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005915 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005916 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005917 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005918 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005919 // FIXME: This code shouldn't be necessary! We should catch the implicit
5920 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005921 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5922 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5923 if (ICE->getSubExpr()->getType()->isArrayType())
5924 return getPrimaryDecl(ICE->getSubExpr());
5925 }
5926 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005927 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005928 case Stmt::UnaryOperatorClass: {
5929 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005930
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005931 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005932 case UnaryOperator::Real:
5933 case UnaryOperator::Imag:
5934 case UnaryOperator::Extension:
5935 return getPrimaryDecl(UO->getSubExpr());
5936 default:
5937 return 0;
5938 }
5939 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005940 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005941 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005942 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005943 // If the result of an implicit cast is an l-value, we care about
5944 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005945 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005946 default:
5947 return 0;
5948 }
5949}
5950
5951/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005952/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005953/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005954/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005955/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005956/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005957/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005958QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005959 // Make sure to ignore parentheses in subsequent checks
5960 op = op->IgnoreParens();
5961
Douglas Gregor9103bb22008-12-17 22:52:20 +00005962 if (op->isTypeDependent())
5963 return Context.DependentTy;
5964
Steve Naroff08f19672008-01-13 17:10:08 +00005965 if (getLangOptions().C99) {
5966 // Implement C99-only parts of addressof rules.
5967 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5968 if (uOp->getOpcode() == UnaryOperator::Deref)
5969 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5970 // (assuming the deref expression is valid).
5971 return uOp->getSubExpr()->getType();
5972 }
5973 // Technically, there should be a check for array subscript
5974 // expressions here, but the result of one is always an lvalue anyway.
5975 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005976 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005977 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005978
Sebastian Redle27d87f2010-01-11 15:56:56 +00005979 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5980 if (lval == Expr::LV_MemberFunction && ME &&
5981 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5982 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5983 // &f where f is a member of the current object, or &o.f, or &p->f
5984 // All these are not allowed, and we need to catch them before the dcl
5985 // branch of the if, below.
5986 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5987 << dcl;
5988 // FIXME: Improve this diagnostic and provide a fixit.
5989
5990 // Now recover by acting as if the function had been accessed qualified.
5991 return Context.getMemberPointerType(op->getType(),
5992 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5993 .getTypePtr());
Douglas Gregore873fb72010-02-16 21:39:57 +00005994 } else if (lval == Expr::LV_ClassTemporary) {
5995 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
5996 : diag::ext_typecheck_addrof_class_temporary)
5997 << op->getType() << op->getSourceRange();
5998 if (isSFINAEContext())
5999 return QualType();
Sebastian Redle27d87f2010-01-11 15:56:56 +00006000 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006001 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006002 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006003 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006004 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006005 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6006 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006007 return QualType();
6008 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006009 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006010 // The operand cannot be a bit-field
6011 Diag(OpLoc, diag::err_typecheck_address_of)
6012 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006013 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006014 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006015 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006016 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006017 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006018 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006019 } else if (isa<ObjCPropertyRefExpr>(op)) {
6020 // cannot take address of a property expression.
6021 Diag(OpLoc, diag::err_typecheck_address_of)
6022 << "property expression" << op->getSourceRange();
6023 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006024 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6025 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006026 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6027 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00006028 } else if (isa<UnresolvedLookupExpr>(op)) {
6029 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006030 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006031 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006032 // with the register storage-class specifier.
6033 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6034 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006035 Diag(OpLoc, diag::err_typecheck_address_of)
6036 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006037 return QualType();
6038 }
John McCallba135432009-11-21 08:51:07 +00006039 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006040 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006041 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006042 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006043 // Could be a pointer to member, though, if there is an explicit
6044 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006045 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006046 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006047 if (Ctx && Ctx->isRecord()) {
6048 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006049 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006050 diag::err_cannot_form_pointer_to_member_of_reference_type)
6051 << FD->getDeclName() << FD->getType();
6052 return QualType();
6053 }
Mike Stump1eb44332009-09-09 15:08:12 +00006054
Sebastian Redlebc07d52009-02-03 20:19:35 +00006055 return Context.getMemberPointerType(op->getType(),
6056 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006057 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006058 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006059 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006060 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006061 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006062 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6063 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006064 return Context.getMemberPointerType(op->getType(),
6065 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6066 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006067 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006068 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006069
Eli Friedman441cf102009-05-16 23:27:50 +00006070 if (lval == Expr::LV_IncompleteVoidType) {
6071 // Taking the address of a void variable is technically illegal, but we
6072 // allow it in cases which are otherwise valid.
6073 // Example: "extern void x; void* y = &x;".
6074 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6075 }
6076
Reid Spencer5f016e22007-07-11 17:01:13 +00006077 // If the operand has type "type", the result has type "pointer to type".
6078 return Context.getPointerType(op->getType());
6079}
6080
Chris Lattner22caddc2008-11-23 09:13:29 +00006081QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006082 if (Op->isTypeDependent())
6083 return Context.DependentTy;
6084
Chris Lattner22caddc2008-11-23 09:13:29 +00006085 UsualUnaryConversions(Op);
6086 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006087
Chris Lattner22caddc2008-11-23 09:13:29 +00006088 // Note that per both C89 and C99, this is always legal, even if ptype is an
6089 // incomplete type or void. It would be possible to warn about dereferencing
6090 // a void pointer, but it's completely well-defined, and such a warning is
6091 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006092 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006093 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006094
John McCall183700f2009-09-21 23:43:11 +00006095 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006096 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006097
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006098 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006099 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006100 return QualType();
6101}
6102
6103static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6104 tok::TokenKind Kind) {
6105 BinaryOperator::Opcode Opc;
6106 switch (Kind) {
6107 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006108 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6109 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006110 case tok::star: Opc = BinaryOperator::Mul; break;
6111 case tok::slash: Opc = BinaryOperator::Div; break;
6112 case tok::percent: Opc = BinaryOperator::Rem; break;
6113 case tok::plus: Opc = BinaryOperator::Add; break;
6114 case tok::minus: Opc = BinaryOperator::Sub; break;
6115 case tok::lessless: Opc = BinaryOperator::Shl; break;
6116 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6117 case tok::lessequal: Opc = BinaryOperator::LE; break;
6118 case tok::less: Opc = BinaryOperator::LT; break;
6119 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6120 case tok::greater: Opc = BinaryOperator::GT; break;
6121 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6122 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6123 case tok::amp: Opc = BinaryOperator::And; break;
6124 case tok::caret: Opc = BinaryOperator::Xor; break;
6125 case tok::pipe: Opc = BinaryOperator::Or; break;
6126 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6127 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6128 case tok::equal: Opc = BinaryOperator::Assign; break;
6129 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6130 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6131 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6132 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6133 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6134 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6135 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6136 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6137 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6138 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6139 case tok::comma: Opc = BinaryOperator::Comma; break;
6140 }
6141 return Opc;
6142}
6143
6144static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6145 tok::TokenKind Kind) {
6146 UnaryOperator::Opcode Opc;
6147 switch (Kind) {
6148 default: assert(0 && "Unknown unary op!");
6149 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6150 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6151 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6152 case tok::star: Opc = UnaryOperator::Deref; break;
6153 case tok::plus: Opc = UnaryOperator::Plus; break;
6154 case tok::minus: Opc = UnaryOperator::Minus; break;
6155 case tok::tilde: Opc = UnaryOperator::Not; break;
6156 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006157 case tok::kw___real: Opc = UnaryOperator::Real; break;
6158 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6159 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6160 }
6161 return Opc;
6162}
6163
Douglas Gregoreaebc752008-11-06 23:29:22 +00006164/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6165/// operator @p Opc at location @c TokLoc. This routine only supports
6166/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006167Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6168 unsigned Op,
6169 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006170 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006171 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006172 // The following two variables are used for compound assignment operators
6173 QualType CompLHSTy; // Type of LHS after promotions for computation
6174 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006175
6176 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006177 case BinaryOperator::Assign:
6178 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6179 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006180 case BinaryOperator::PtrMemD:
6181 case BinaryOperator::PtrMemI:
6182 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6183 Opc == BinaryOperator::PtrMemI);
6184 break;
6185 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006186 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006187 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6188 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006189 break;
6190 case BinaryOperator::Rem:
6191 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6192 break;
6193 case BinaryOperator::Add:
6194 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6195 break;
6196 case BinaryOperator::Sub:
6197 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6198 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006199 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006200 case BinaryOperator::Shr:
6201 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6202 break;
6203 case BinaryOperator::LE:
6204 case BinaryOperator::LT:
6205 case BinaryOperator::GE:
6206 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006207 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006208 break;
6209 case BinaryOperator::EQ:
6210 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006211 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006212 break;
6213 case BinaryOperator::And:
6214 case BinaryOperator::Xor:
6215 case BinaryOperator::Or:
6216 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6217 break;
6218 case BinaryOperator::LAnd:
6219 case BinaryOperator::LOr:
6220 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6221 break;
6222 case BinaryOperator::MulAssign:
6223 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006224 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6225 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006226 CompLHSTy = CompResultTy;
6227 if (!CompResultTy.isNull())
6228 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006229 break;
6230 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006231 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6232 CompLHSTy = CompResultTy;
6233 if (!CompResultTy.isNull())
6234 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006235 break;
6236 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006237 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6238 if (!CompResultTy.isNull())
6239 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006240 break;
6241 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006242 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6243 if (!CompResultTy.isNull())
6244 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006245 break;
6246 case BinaryOperator::ShlAssign:
6247 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006248 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6249 CompLHSTy = CompResultTy;
6250 if (!CompResultTy.isNull())
6251 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006252 break;
6253 case BinaryOperator::AndAssign:
6254 case BinaryOperator::XorAssign:
6255 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006256 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6257 CompLHSTy = CompResultTy;
6258 if (!CompResultTy.isNull())
6259 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006260 break;
6261 case BinaryOperator::Comma:
6262 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6263 break;
6264 }
6265 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006266 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006267 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006268 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6269 else
6270 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006271 CompLHSTy, CompResultTy,
6272 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006273}
6274
Sebastian Redlaee3c932009-10-27 12:10:02 +00006275/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6276/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006277static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6278 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00006279 const PartialDiagnostic &FirstNote,
6280 SourceRange FirstParenRange,
6281 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006282 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00006283 Self.Diag(Loc, PD);
6284
6285 if (!FirstNote.getDiagID())
6286 return;
6287
6288 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6289 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6290 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006291 return;
6292 }
6293
Douglas Gregor55b38842010-04-14 16:09:52 +00006294 Self.Diag(Loc, FirstNote)
6295 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00006296 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006297
Douglas Gregor55b38842010-04-14 16:09:52 +00006298 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00006299 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006300
Douglas Gregor827feec2010-01-08 00:20:23 +00006301 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6302 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6303 // We can't display the parentheses, so just dig the
6304 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00006305 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00006306 return;
6307 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006308
Douglas Gregor55b38842010-04-14 16:09:52 +00006309 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00006310 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6311 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006312}
6313
Sebastian Redlaee3c932009-10-27 12:10:02 +00006314/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6315/// operators are mixed in a way that suggests that the programmer forgot that
6316/// comparison operators have higher precedence. The most typical example of
6317/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006318static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6319 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006320 typedef BinaryOperator BinOp;
6321 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6322 rhsopc = static_cast<BinOp::Opcode>(-1);
6323 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006324 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006325 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006326 rhsopc = BO->getOpcode();
6327
6328 // Subs are not binary operators.
6329 if (lhsopc == -1 && rhsopc == -1)
6330 return;
6331
6332 // Bitwise operations are sometimes used as eager logical ops.
6333 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006334 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6335 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006336 return;
6337
Sebastian Redlaee3c932009-10-27 12:10:02 +00006338 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006339 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006340 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006341 << SourceRange(lhs->getLocStart(), OpLoc)
6342 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006343 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006344 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006345 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6346 Self.PDiag(diag::note_precedence_bitwise_silence)
6347 << BinOp::getOpcodeStr(lhsopc),
6348 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00006349 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006350 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006351 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006352 << SourceRange(OpLoc, rhs->getLocEnd())
6353 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006354 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006355 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006356 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6357 Self.PDiag(diag::note_precedence_bitwise_silence)
6358 << BinOp::getOpcodeStr(rhsopc),
6359 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006360}
6361
6362/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6363/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6364/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6365static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6366 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006367 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006368 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6369}
6370
Reid Spencer5f016e22007-07-11 17:01:13 +00006371// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006372Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6373 tok::TokenKind Kind,
6374 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006375 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006376 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006377
Steve Narofff69936d2007-09-16 03:34:24 +00006378 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6379 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006380
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006381 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6382 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6383
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006384 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6385}
6386
6387Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6388 BinaryOperator::Opcode Opc,
6389 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006390 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006391 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006392 rhs->getType()->isOverloadableType())) {
6393 // Find all of the overloaded operators visible from this
6394 // point. We perform both an operator-name lookup from the local
6395 // scope and an argument-dependent lookup based on the types of
6396 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006397 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006398 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006399 if (S && OverOp != OO_None)
6400 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6401 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006402
Douglas Gregor063daf62009-03-13 18:40:31 +00006403 // Build the (potentially-overloaded, potentially-dependent)
6404 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006405 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006406 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006407
Douglas Gregoreaebc752008-11-06 23:29:22 +00006408 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006409 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006410}
6411
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006412Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006413 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006414 ExprArg InputArg) {
6415 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006416
Mike Stump390b4cc2009-05-16 07:39:55 +00006417 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006418 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006419 QualType resultType;
6420 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006421 case UnaryOperator::OffsetOf:
6422 assert(false && "Invalid unary operator");
6423 break;
6424
Reid Spencer5f016e22007-07-11 17:01:13 +00006425 case UnaryOperator::PreInc:
6426 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006427 case UnaryOperator::PostInc:
6428 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006429 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006430 Opc == UnaryOperator::PreInc ||
6431 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006432 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006433 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006434 resultType = CheckAddressOfOperand(Input, OpLoc);
6435 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006436 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006437 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006438 resultType = CheckIndirectionOperand(Input, OpLoc);
6439 break;
6440 case UnaryOperator::Plus:
6441 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006442 UsualUnaryConversions(Input);
6443 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006444 if (resultType->isDependentType())
6445 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006446 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6447 break;
6448 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6449 resultType->isEnumeralType())
6450 break;
6451 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6452 Opc == UnaryOperator::Plus &&
6453 resultType->isPointerType())
6454 break;
6455
Sebastian Redl0eb23302009-01-19 00:08:26 +00006456 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6457 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006458 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006459 UsualUnaryConversions(Input);
6460 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006461 if (resultType->isDependentType())
6462 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006463 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6464 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6465 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006466 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006467 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006468 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006469 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6470 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006471 break;
6472 case UnaryOperator::LNot: // logical negation
6473 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006474 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006475 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006476 if (resultType->isDependentType())
6477 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006478 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006479 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6480 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006481 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006482 // In C++, it's bool. C++ 5.3.1p8
6483 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006484 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006485 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006486 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006487 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006488 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006489 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006490 resultType = Input->getType();
6491 break;
6492 }
6493 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006494 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006495
6496 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006497 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006498}
6499
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006500Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6501 UnaryOperator::Opcode Opc,
6502 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006503 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006504 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6505 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006506 // Find all of the overloaded operators visible from this
6507 // point. We perform both an operator-name lookup from the local
6508 // scope and an argument-dependent lookup based on the types of
6509 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006510 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006511 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006512 if (S && OverOp != OO_None)
6513 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6514 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006515
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006516 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6517 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006518
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006519 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6520}
6521
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006522// Unary Operators. 'Tok' is the token for the operator.
6523Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6524 tok::TokenKind Op, ExprArg input) {
6525 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6526}
6527
Steve Naroff1b273c42007-09-16 14:56:35 +00006528/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006529Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6530 SourceLocation LabLoc,
6531 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006532 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006533 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006534
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006535 // If we haven't seen this label yet, create a forward reference. It
6536 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006537 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006538 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006539
Reid Spencer5f016e22007-07-11 17:01:13 +00006540 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006541 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6542 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006543}
6544
Sebastian Redlf53597f2009-03-15 17:47:39 +00006545Sema::OwningExprResult
6546Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6547 SourceLocation RPLoc) { // "({..})"
6548 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006549 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6550 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6551
Douglas Gregordd8f5692010-03-10 04:54:39 +00006552 bool isFileScope
6553 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006554 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006555 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006556
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006557 // FIXME: there are a variety of strange constraints to enforce here, for
6558 // example, it is not possible to goto into a stmt expression apparently.
6559 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006561 // If there are sub stmts in the compound stmt, take the type of the last one
6562 // as the type of the stmtexpr.
6563 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006564
Chris Lattner611b2ec2008-07-26 19:51:01 +00006565 if (!Compound->body_empty()) {
6566 Stmt *LastStmt = Compound->body_back();
6567 // If LastStmt is a label, skip down through into the body.
6568 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6569 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006570
Chris Lattner611b2ec2008-07-26 19:51:01 +00006571 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006572 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006573 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006574
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006575 // FIXME: Check that expression type is complete/non-abstract; statement
6576 // expressions are not lvalues.
6577
Sebastian Redlf53597f2009-03-15 17:47:39 +00006578 substmt.release();
6579 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006580}
Steve Naroffd34e9152007-08-01 22:05:33 +00006581
Sebastian Redlf53597f2009-03-15 17:47:39 +00006582Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6583 SourceLocation BuiltinLoc,
6584 SourceLocation TypeLoc,
6585 TypeTy *argty,
6586 OffsetOfComponent *CompPtr,
6587 unsigned NumComponents,
6588 SourceLocation RPLoc) {
6589 // FIXME: This function leaks all expressions in the offset components on
6590 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006591 // FIXME: Preserve type source info.
6592 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006593 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006594
Sebastian Redl28507842009-02-26 14:39:58 +00006595 bool Dependent = ArgTy->isDependentType();
6596
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006597 // We must have at least one component that refers to the type, and the first
6598 // one is known to be a field designator. Verify that the ArgTy represents
6599 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006600 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006601 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006603 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6604 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006605
Eli Friedman35183ac2009-02-27 06:44:11 +00006606 // Otherwise, create a null pointer as the base, and iteratively process
6607 // the offsetof designators.
6608 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6609 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006610 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006611 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006612
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006613 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6614 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006615 // FIXME: This diagnostic isn't actually visible because the location is in
6616 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006617 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006618 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6619 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006620
Sebastian Redl28507842009-02-26 14:39:58 +00006621 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006622 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006623
John McCalld00f2002009-11-04 03:03:43 +00006624 if (RequireCompleteType(TypeLoc, Res->getType(),
6625 diag::err_offsetof_incomplete_type))
6626 return ExprError();
6627
Sebastian Redl28507842009-02-26 14:39:58 +00006628 // FIXME: Dependent case loses a lot of information here. And probably
6629 // leaks like a sieve.
6630 for (unsigned i = 0; i != NumComponents; ++i) {
6631 const OffsetOfComponent &OC = CompPtr[i];
6632 if (OC.isBrackets) {
6633 // Offset of an array sub-field. TODO: Should we allow vector elements?
6634 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6635 if (!AT) {
6636 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006637 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6638 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006639 }
6640
6641 // FIXME: C++: Verify that operator[] isn't overloaded.
6642
Eli Friedman35183ac2009-02-27 06:44:11 +00006643 // Promote the array so it looks more like a normal array subscript
6644 // expression.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006645 DefaultFunctionArrayLvalueConversion(Res);
Eli Friedman35183ac2009-02-27 06:44:11 +00006646
Sebastian Redl28507842009-02-26 14:39:58 +00006647 // C99 6.5.2.1p1
6648 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006649 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006650 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006651 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006652 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006653 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006654
6655 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6656 OC.LocEnd);
6657 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006658 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006659
Ted Kremenek6217b802009-07-29 21:53:49 +00006660 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006661 if (!RC) {
6662 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006663 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6664 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006665 }
Chris Lattner704fe352007-08-30 17:59:59 +00006666
Sebastian Redl28507842009-02-26 14:39:58 +00006667 // Get the decl corresponding to this.
6668 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006669 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006670 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6671 DiagRuntimeBehavior(BuiltinLoc,
6672 PDiag(diag::warn_offsetof_non_pod_type)
6673 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6674 << Res->getType()))
6675 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006676 }
Mike Stump1eb44332009-09-09 15:08:12 +00006677
John McCalla24dc2e2009-11-17 02:14:36 +00006678 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6679 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006680
John McCall1bcee0a2009-12-02 08:25:40 +00006681 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006682 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006683 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006684 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6685 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686
Sebastian Redl28507842009-02-26 14:39:58 +00006687 // FIXME: C++: Verify that MemberDecl isn't a static field.
6688 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006689 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006690 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006691 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006692 } else {
John McCall6bb80172010-03-30 21:47:33 +00006693 PerformObjectMemberConversion(Res, /*Qualifier=*/0,
6694 *R.begin(), MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006695 // MemberDecl->getType() doesn't get the right qualifiers, but it
6696 // doesn't matter here.
6697 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6698 MemberDecl->getType().getNonReferenceType());
6699 }
Sebastian Redl28507842009-02-26 14:39:58 +00006700 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006701 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006702
Sebastian Redlf53597f2009-03-15 17:47:39 +00006703 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6704 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006705}
6706
6707
Sebastian Redlf53597f2009-03-15 17:47:39 +00006708Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6709 TypeTy *arg1,TypeTy *arg2,
6710 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006711 // FIXME: Preserve type source info.
6712 QualType argT1 = GetTypeFromParser(arg1);
6713 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006714
Steve Naroffd34e9152007-08-01 22:05:33 +00006715 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006716
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006717 if (getLangOptions().CPlusPlus) {
6718 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6719 << SourceRange(BuiltinLoc, RPLoc);
6720 return ExprError();
6721 }
6722
Sebastian Redlf53597f2009-03-15 17:47:39 +00006723 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6724 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006725}
6726
Sebastian Redlf53597f2009-03-15 17:47:39 +00006727Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6728 ExprArg cond,
6729 ExprArg expr1, ExprArg expr2,
6730 SourceLocation RPLoc) {
6731 Expr *CondExpr = static_cast<Expr*>(cond.get());
6732 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6733 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006734
Steve Naroffd04fdd52007-08-03 21:21:27 +00006735 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6736
Sebastian Redl28507842009-02-26 14:39:58 +00006737 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006738 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006739 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006740 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006741 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006742 } else {
6743 // The conditional expression is required to be a constant expression.
6744 llvm::APSInt condEval(32);
6745 SourceLocation ExpLoc;
6746 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006747 return ExprError(Diag(ExpLoc,
6748 diag::err_typecheck_choose_expr_requires_constant)
6749 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006750
Sebastian Redl28507842009-02-26 14:39:58 +00006751 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6752 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006753 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6754 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006755 }
6756
Sebastian Redlf53597f2009-03-15 17:47:39 +00006757 cond.release(); expr1.release(); expr2.release();
6758 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006759 resType, RPLoc,
6760 resType->isDependentType(),
6761 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006762}
6763
Steve Naroff4eb206b2008-09-03 18:15:37 +00006764//===----------------------------------------------------------------------===//
6765// Clang Extensions.
6766//===----------------------------------------------------------------------===//
6767
6768/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006769void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006770 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
6771 PushBlockScope(BlockScope, Block);
6772 CurContext->addDecl(Block);
6773 PushDeclContext(BlockScope, Block);
Steve Naroff090276f2008-10-10 01:28:17 +00006774}
6775
Mike Stump98eb8a72009-02-04 22:31:32 +00006776void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006777 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006778 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006779
Mike Stump98eb8a72009-02-04 22:31:32 +00006780 if (ParamInfo.getNumTypeObjects() == 0
6781 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006782 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006783 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6784
Mike Stump4eeab842009-04-28 01:10:27 +00006785 if (T->isArrayType()) {
6786 Diag(ParamInfo.getSourceRange().getBegin(),
6787 diag::err_block_returns_array);
6788 return;
6789 }
6790
Mike Stump98eb8a72009-02-04 22:31:32 +00006791 // The parameter list is optional, if there was none, assume ().
6792 if (!T->isFunctionType())
Rafael Espindola264ba482010-03-30 20:24:48 +00006793 T = Context.getFunctionType(T, 0, 0, false, 0, false, false, 0, 0,
6794 FunctionType::ExtInfo());
Mike Stump98eb8a72009-02-04 22:31:32 +00006795
6796 CurBlock->hasPrototype = true;
6797 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006798 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006799 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006800 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006801 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006802 // FIXME: remove the attribute.
6803 }
John McCall183700f2009-09-21 23:43:11 +00006804 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006805
Chris Lattner9097af12009-04-11 19:27:54 +00006806 // Do not allow returning a objc interface by-value.
6807 if (RetTy->isObjCInterfaceType()) {
6808 Diag(ParamInfo.getSourceRange().getBegin(),
6809 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6810 return;
6811 }
Douglas Gregora873dfc2010-02-03 00:27:59 +00006812
6813 CurBlock->ReturnType = RetTy;
Mike Stump98eb8a72009-02-04 22:31:32 +00006814 return;
6815 }
6816
Steve Naroff4eb206b2008-09-03 18:15:37 +00006817 // Analyze arguments to block.
6818 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6819 "Not a function declarator!");
6820 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006821
Steve Naroff090276f2008-10-10 01:28:17 +00006822 CurBlock->hasPrototype = FTI.hasPrototype;
6823 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006824
Steve Naroff4eb206b2008-09-03 18:15:37 +00006825 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6826 // no arguments, not a function that takes a single void argument.
6827 if (FTI.hasPrototype &&
6828 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006829 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6830 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006831 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006832 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006833 } else if (FTI.hasPrototype) {
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00006834 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6835 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
6836 if (Param->getIdentifier() == 0 &&
6837 !Param->isImplicit() &&
6838 !Param->isInvalidDecl() &&
6839 !getLangOptions().CPlusPlus)
6840 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6841 CurBlock->Params.push_back(Param);
6842 }
Steve Naroff090276f2008-10-10 01:28:17 +00006843 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006844 }
Douglas Gregor838db382010-02-11 01:19:42 +00006845 CurBlock->TheDecl->setParams(CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006846 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006847 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006848 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00006849
6850 bool ShouldCheckShadow =
6851 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
6852
Steve Naroff090276f2008-10-10 01:28:17 +00006853 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00006854 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6855 (*AI)->setOwningFunction(CurBlock->TheDecl);
6856
Steve Naroff090276f2008-10-10 01:28:17 +00006857 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00006858 if ((*AI)->getIdentifier()) {
6859 if (ShouldCheckShadow)
6860 CheckShadow(CurBlock->TheScope, *AI);
6861
Steve Naroff090276f2008-10-10 01:28:17 +00006862 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00006863 }
John McCall7a9813c2010-01-22 00:28:27 +00006864 }
Chris Lattner9097af12009-04-11 19:27:54 +00006865
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006866 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006867 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006868 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006869 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006870 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006871 // FIXME: remove the attribute.
6872 }
Mike Stump1eb44332009-09-09 15:08:12 +00006873
Chris Lattner9097af12009-04-11 19:27:54 +00006874 // Analyze the return type.
6875 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006876 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006877
Chris Lattner9097af12009-04-11 19:27:54 +00006878 // Do not allow returning a objc interface by-value.
6879 if (RetTy->isObjCInterfaceType()) {
6880 Diag(ParamInfo.getSourceRange().getBegin(),
6881 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6882 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006883 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006884}
6885
6886/// ActOnBlockError - If there is an error parsing a block, this callback
6887/// is invoked to pop the information about the block from the action impl.
6888void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006889 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006890 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006891 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006892 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006893}
6894
6895/// ActOnBlockStmtExpr - This is called when the body of a block statement
6896/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006897Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6898 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006899 // If blocks are disabled, emit an error.
6900 if (!LangOpts.Blocks)
6901 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006902
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006903 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006904
Steve Naroff090276f2008-10-10 01:28:17 +00006905 PopDeclContext();
6906
Steve Naroff4eb206b2008-09-03 18:15:37 +00006907 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006908 if (!BSI->ReturnType.isNull())
6909 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006910
Steve Naroff4eb206b2008-09-03 18:15:37 +00006911 llvm::SmallVector<QualType, 8> ArgTypes;
6912 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6913 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006914
Mike Stump56925862009-07-28 22:04:01 +00006915 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006916 QualType BlockTy;
6917 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006918 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00006919 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006920 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006921 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006922 BSI->isVariadic, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00006923 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006924
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006925 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006926 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006927 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006928
Chris Lattner17a78302009-04-19 05:28:12 +00006929 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006930 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner17a78302009-04-19 05:28:12 +00006931 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00006932
Anders Carlssone9146f22009-05-01 19:49:17 +00006933 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00006934
6935 bool Good = true;
6936 // Check goto/label use.
6937 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6938 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6939 LabelStmt *L = I->second;
6940
6941 // Verify that we have no forward references left. If so, there was a goto
6942 // or address of a label taken, but no definition of it.
6943 if (L->getSubStmt() != 0)
6944 continue;
6945
6946 // Emit error.
6947 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6948 Good = false;
6949 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006950 if (!Good) {
6951 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00006952 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006953 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006954
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00006955 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00006956 const sema::AnalysisBasedWarnings::Policy &WP =
6957 AnalysisWarnings.getDefaultPolicy();
6958 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00006959
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006960 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6961 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006962 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006963 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006964}
6965
Sebastian Redlf53597f2009-03-15 17:47:39 +00006966Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6967 ExprArg expr, TypeTy *type,
6968 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006969 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006970 Expr *E = static_cast<Expr*>(expr.get());
6971 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006972
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006973 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006974
6975 // Get the va_list type
6976 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006977 if (VaListType->isArrayType()) {
6978 // Deal with implicit array decay; for example, on x86-64,
6979 // va_list is an array, but it's supposed to decay to
6980 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006981 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006982 // Make sure the input expression also decays appropriately.
6983 UsualUnaryConversions(E);
6984 } else {
6985 // Otherwise, the va_list argument must be an l-value because
6986 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006987 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006988 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006989 return ExprError();
6990 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006991
Douglas Gregordd027302009-05-19 23:10:31 +00006992 if (!E->isTypeDependent() &&
6993 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006994 return ExprError(Diag(E->getLocStart(),
6995 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006996 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006997 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006998
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006999 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007000 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007001
Sebastian Redlf53597f2009-03-15 17:47:39 +00007002 expr.release();
7003 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
7004 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007005}
7006
Sebastian Redlf53597f2009-03-15 17:47:39 +00007007Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007008 // The type of __null will be int or long, depending on the size of
7009 // pointers on the target.
7010 QualType Ty;
7011 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7012 Ty = Context.IntTy;
7013 else
7014 Ty = Context.LongTy;
7015
Sebastian Redlf53597f2009-03-15 17:47:39 +00007016 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007017}
7018
Douglas Gregor849b2432010-03-31 17:46:05 +00007019static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
7020 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007021 if (!SemaRef.getLangOptions().ObjC1)
7022 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007023
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007024 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7025 if (!PT)
7026 return;
7027
7028 // Check if the destination is of type 'id'.
7029 if (!PT->isObjCIdType()) {
7030 // Check if the destination is the 'NSString' interface.
7031 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7032 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7033 return;
7034 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007035
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007036 // Strip off any parens and casts.
7037 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7038 if (!SL || SL->isWide())
7039 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007040
Douglas Gregor849b2432010-03-31 17:46:05 +00007041 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007042}
7043
Chris Lattner5cf216b2008-01-04 18:04:52 +00007044bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7045 SourceLocation Loc,
7046 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00007047 Expr *SrcExpr, AssignmentAction Action,
7048 bool *Complained) {
7049 if (Complained)
7050 *Complained = false;
7051
Chris Lattner5cf216b2008-01-04 18:04:52 +00007052 // Decode the result (notice that AST's are still created for extensions).
7053 bool isInvalid = false;
7054 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00007055 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007056
Chris Lattner5cf216b2008-01-04 18:04:52 +00007057 switch (ConvTy) {
7058 default: assert(0 && "Unknown conversion type");
7059 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007060 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007061 DiagKind = diag::ext_typecheck_convert_pointer_int;
7062 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007063 case IntToPointer:
7064 DiagKind = diag::ext_typecheck_convert_int_pointer;
7065 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007066 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00007067 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007068 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7069 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007070 case IncompatiblePointerSign:
7071 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7072 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007073 case FunctionVoidPointer:
7074 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7075 break;
7076 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007077 // If the qualifiers lost were because we were applying the
7078 // (deprecated) C++ conversion from a string literal to a char*
7079 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7080 // Ideally, this check would be performed in
7081 // CheckPointerTypesForAssignment. However, that would require a
7082 // bit of refactoring (so that the second argument is an
7083 // expression, rather than a type), which should be done as part
7084 // of a larger effort to fix CheckPointerTypesForAssignment for
7085 // C++ semantics.
7086 if (getLangOptions().CPlusPlus &&
7087 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7088 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007089 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7090 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007091 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007092 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007093 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007094 case IntToBlockPointer:
7095 DiagKind = diag::err_int_to_block_pointer;
7096 break;
7097 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007098 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007099 break;
Steve Naroff39579072008-10-14 22:18:38 +00007100 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007101 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007102 // it can give a more specific diagnostic.
7103 DiagKind = diag::warn_incompatible_qualified_id;
7104 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007105 case IncompatibleVectors:
7106 DiagKind = diag::warn_incompatible_vectors;
7107 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007108 case Incompatible:
7109 DiagKind = diag::err_typecheck_convert_incompatible;
7110 isInvalid = true;
7111 break;
7112 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007113
Douglas Gregord4eea832010-04-09 00:35:39 +00007114 QualType FirstType, SecondType;
7115 switch (Action) {
7116 case AA_Assigning:
7117 case AA_Initializing:
7118 // The destination type comes first.
7119 FirstType = DstType;
7120 SecondType = SrcType;
7121 break;
7122
7123 case AA_Returning:
7124 case AA_Passing:
7125 case AA_Converting:
7126 case AA_Sending:
7127 case AA_Casting:
7128 // The source type comes first.
7129 FirstType = SrcType;
7130 SecondType = DstType;
7131 break;
7132 }
7133
7134 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007135 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00007136 if (Complained)
7137 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007138 return isInvalid;
7139}
Anders Carlssone21555e2008-11-30 19:50:32 +00007140
Chris Lattner3bf68932009-04-25 21:59:05 +00007141bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007142 llvm::APSInt ICEResult;
7143 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7144 if (Result)
7145 *Result = ICEResult;
7146 return false;
7147 }
7148
Anders Carlssone21555e2008-11-30 19:50:32 +00007149 Expr::EvalResult EvalResult;
7150
Mike Stumpeed9cac2009-02-19 03:04:26 +00007151 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007152 EvalResult.HasSideEffects) {
7153 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7154
7155 if (EvalResult.Diag) {
7156 // We only show the note if it's not the usual "invalid subexpression"
7157 // or if it's actually in a subexpression.
7158 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7159 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7160 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7161 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007162
Anders Carlssone21555e2008-11-30 19:50:32 +00007163 return true;
7164 }
7165
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007166 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7167 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007168
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007169 if (EvalResult.Diag &&
7170 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7171 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007172
Anders Carlssone21555e2008-11-30 19:50:32 +00007173 if (Result)
7174 *Result = EvalResult.Val.getInt();
7175 return false;
7176}
Douglas Gregore0762c92009-06-19 23:52:42 +00007177
Douglas Gregor2afce722009-11-26 00:44:06 +00007178void
Mike Stump1eb44332009-09-09 15:08:12 +00007179Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007180 ExprEvalContexts.push_back(
7181 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007182}
7183
Mike Stump1eb44332009-09-09 15:08:12 +00007184void
Douglas Gregor2afce722009-11-26 00:44:06 +00007185Sema::PopExpressionEvaluationContext() {
7186 // Pop the current expression evaluation context off the stack.
7187 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7188 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007189
Douglas Gregor06d33692009-12-12 07:57:52 +00007190 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7191 if (Rec.PotentiallyReferenced) {
7192 // Mark any remaining declarations in the current position of the stack
7193 // as "referenced". If they were not meant to be referenced, semantic
7194 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007195 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007196 I = Rec.PotentiallyReferenced->begin(),
7197 IEnd = Rec.PotentiallyReferenced->end();
7198 I != IEnd; ++I)
7199 MarkDeclarationReferenced(I->first, I->second);
7200 }
7201
7202 if (Rec.PotentiallyDiagnosed) {
7203 // Emit any pending diagnostics.
7204 for (PotentiallyEmittedDiagnostics::iterator
7205 I = Rec.PotentiallyDiagnosed->begin(),
7206 IEnd = Rec.PotentiallyDiagnosed->end();
7207 I != IEnd; ++I)
7208 Diag(I->first, I->second);
7209 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007210 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007211
7212 // When are coming out of an unevaluated context, clear out any
7213 // temporaries that we may have created as part of the evaluation of
7214 // the expression in that context: they aren't relevant because they
7215 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007216 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007217 ExprTemporaries.size() > Rec.NumTemporaries)
7218 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7219 ExprTemporaries.end());
7220
7221 // Destroy the popped expression evaluation record.
7222 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007223}
Douglas Gregore0762c92009-06-19 23:52:42 +00007224
7225/// \brief Note that the given declaration was referenced in the source code.
7226///
7227/// This routine should be invoke whenever a given declaration is referenced
7228/// in the source code, and where that reference occurred. If this declaration
7229/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7230/// C99 6.9p3), then the declaration will be marked as used.
7231///
7232/// \param Loc the location where the declaration was referenced.
7233///
7234/// \param D the declaration that has been referenced by the source code.
7235void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7236 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007237
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007238 if (D->isUsed())
7239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007240
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007241 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7242 // template or not. The reason for this is that unevaluated expressions
7243 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7244 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007245 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007246 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007247 D->setUsed(true);
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007248 return;
7249 }
7250
7251 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7252 return;
7253
Douglas Gregore0762c92009-06-19 23:52:42 +00007254 // Do not mark anything as "used" within a dependent context; wait for
7255 // an instantiation.
7256 if (CurContext->isDependentContext())
7257 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007258
Douglas Gregor2afce722009-11-26 00:44:06 +00007259 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007260 case Unevaluated:
7261 // We are in an expression that is not potentially evaluated; do nothing.
7262 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007263
Douglas Gregorac7610d2009-06-22 20:57:11 +00007264 case PotentiallyEvaluated:
7265 // We are in a potentially-evaluated expression, so this declaration is
7266 // "used"; handle this below.
7267 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007268
Douglas Gregorac7610d2009-06-22 20:57:11 +00007269 case PotentiallyPotentiallyEvaluated:
7270 // We are in an expression that may be potentially evaluated; queue this
7271 // declaration reference until we know whether the expression is
7272 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007273 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007274 return;
7275 }
Mike Stump1eb44332009-09-09 15:08:12 +00007276
Douglas Gregore0762c92009-06-19 23:52:42 +00007277 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007278 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007279 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007280 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7281 if (!Constructor->isUsed())
7282 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007283 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007284 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007285 if (!Constructor->isUsed())
7286 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7287 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007288
Anders Carlssond6a637f2009-12-07 08:24:59 +00007289 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007290 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7291 if (Destructor->isImplicit() && !Destructor->isUsed())
7292 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007293
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007294 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7295 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7296 MethodDecl->getOverloadedOperator() == OO_Equal) {
7297 if (!MethodDecl->isUsed())
7298 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7299 }
7300 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007301 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007302 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007303 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007304 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007305 bool AlreadyInstantiated = false;
7306 if (FunctionTemplateSpecializationInfo *SpecInfo
7307 = Function->getTemplateSpecializationInfo()) {
7308 if (SpecInfo->getPointOfInstantiation().isInvalid())
7309 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007310 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007311 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007312 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007313 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007314 = Function->getMemberSpecializationInfo()) {
7315 if (MSInfo->getPointOfInstantiation().isInvalid())
7316 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007317 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007318 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007319 AlreadyInstantiated = true;
7320 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007321
Douglas Gregor60406be2010-01-16 22:29:39 +00007322 if (!AlreadyInstantiated) {
7323 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7324 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7325 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7326 Loc));
7327 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007328 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007329 Loc));
7330 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007331 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007332
Douglas Gregore0762c92009-06-19 23:52:42 +00007333 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007334 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007335
Douglas Gregore0762c92009-06-19 23:52:42 +00007336 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007337 }
Mike Stump1eb44332009-09-09 15:08:12 +00007338
Douglas Gregore0762c92009-06-19 23:52:42 +00007339 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007340 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007341 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007342 Var->getInstantiatedFromStaticDataMember()) {
7343 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7344 assert(MSInfo && "Missing member specialization information?");
7345 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7346 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7347 MSInfo->setPointOfInstantiation(Loc);
7348 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7349 }
7350 }
Mike Stump1eb44332009-09-09 15:08:12 +00007351
Douglas Gregore0762c92009-06-19 23:52:42 +00007352 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007353
Douglas Gregore0762c92009-06-19 23:52:42 +00007354 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007355 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007356 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007357}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007358
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007359/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7360/// of the program being compiled.
7361///
7362/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007363/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007364/// possibility that the code will actually be executable. Code in sizeof()
7365/// expressions, code used only during overload resolution, etc., are not
7366/// potentially evaluated. This routine will suppress such diagnostics or,
7367/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007368/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007369/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007370///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007371/// This routine should be used for all diagnostics that describe the run-time
7372/// behavior of a program, such as passing a non-POD value through an ellipsis.
7373/// Failure to do so will likely result in spurious diagnostics or failures
7374/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007375bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007376 const PartialDiagnostic &PD) {
7377 switch (ExprEvalContexts.back().Context ) {
7378 case Unevaluated:
7379 // The argument will never be evaluated, so don't complain.
7380 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007381
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007382 case PotentiallyEvaluated:
7383 Diag(Loc, PD);
7384 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007385
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007386 case PotentiallyPotentiallyEvaluated:
7387 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7388 break;
7389 }
7390
7391 return false;
7392}
7393
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007394bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7395 CallExpr *CE, FunctionDecl *FD) {
7396 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7397 return false;
7398
7399 PartialDiagnostic Note =
7400 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7401 << FD->getDeclName() : PDiag();
7402 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007403
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007404 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007405 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007406 PDiag(diag::err_call_function_incomplete_return)
7407 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007408 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007409 << CE->getSourceRange(),
7410 std::make_pair(NoteLoc, Note)))
7411 return true;
7412
7413 return false;
7414}
7415
John McCall5a881bb2009-10-12 21:59:07 +00007416// Diagnose the common s/=/==/ typo. Note that adding parentheses
7417// will prevent this condition from triggering, which is what we want.
7418void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7419 SourceLocation Loc;
7420
John McCalla52ef082009-11-11 02:41:58 +00007421 unsigned diagnostic = diag::warn_condition_is_assignment;
7422
John McCall5a881bb2009-10-12 21:59:07 +00007423 if (isa<BinaryOperator>(E)) {
7424 BinaryOperator *Op = cast<BinaryOperator>(E);
7425 if (Op->getOpcode() != BinaryOperator::Assign)
7426 return;
7427
John McCallc8d8ac52009-11-12 00:06:05 +00007428 // Greylist some idioms by putting them into a warning subcategory.
7429 if (ObjCMessageExpr *ME
7430 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7431 Selector Sel = ME->getSelector();
7432
John McCallc8d8ac52009-11-12 00:06:05 +00007433 // self = [<foo> init...]
7434 if (isSelfExpr(Op->getLHS())
7435 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7436 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7437
7438 // <foo> = [<bar> nextObject]
7439 else if (Sel.isUnarySelector() &&
7440 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7441 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7442 }
John McCalla52ef082009-11-11 02:41:58 +00007443
John McCall5a881bb2009-10-12 21:59:07 +00007444 Loc = Op->getOperatorLoc();
7445 } else if (isa<CXXOperatorCallExpr>(E)) {
7446 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7447 if (Op->getOperator() != OO_Equal)
7448 return;
7449
7450 Loc = Op->getOperatorLoc();
7451 } else {
7452 // Not an assignment.
7453 return;
7454 }
7455
John McCall5a881bb2009-10-12 21:59:07 +00007456 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007457 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007458
Douglas Gregor55b38842010-04-14 16:09:52 +00007459 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00007460 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00007461 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00007462 Diag(Loc, diag::note_condition_assign_silence)
7463 << FixItHint::CreateInsertion(Open, "(")
7464 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00007465}
7466
7467bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7468 DiagnoseAssignmentAsCondition(E);
7469
7470 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007471 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007472
7473 QualType T = E->getType();
7474
7475 if (getLangOptions().CPlusPlus) {
7476 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7477 return true;
7478 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7479 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7480 << T << E->getSourceRange();
7481 return true;
7482 }
7483 }
7484
7485 return false;
7486}