blob: 997b8f8dcb182902ab13541f2a5cb7bfc3609fb7 [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);
Douglas Gregorc96be1e2010-04-27 18:19:34 +00001066
1067 // Re-derive the naming class.
1068 if (SS.isSet()) {
1069 NestedNameSpecifier *Qualifier
1070 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1071 if (const Type *Ty = Qualifier->getAsType())
1072 if (CXXRecordDecl *NamingClass = Ty->getAsCXXRecordDecl())
1073 R.setNamingClass(NamingClass);
1074 }
John McCallf7a1a742009-11-24 19:00:30 +00001075 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001076 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1077 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John McCallf7a1a742009-11-24 19:00:30 +00001079 // If this reference is in an Objective-C method, then we need to do
1080 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001081 if (IvarLookupFollowUp) {
1082 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001083 if (E.isInvalid())
1084 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001085
John McCallf7a1a742009-11-24 19:00:30 +00001086 Expr *Ex = E.takeAs<Expr>();
1087 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001088 }
Chris Lattner8a934232008-03-31 00:36:02 +00001089 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001090
John McCallf7a1a742009-11-24 19:00:30 +00001091 if (R.isAmbiguous())
1092 return ExprError();
1093
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001094 // Determine whether this name might be a candidate for
1095 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001096 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001097
John McCallf7a1a742009-11-24 19:00:30 +00001098 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001100 // in C90, extension in C99, forbidden in C++).
1101 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1102 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1103 if (D) R.addDecl(D);
1104 }
1105
1106 // If this name wasn't predeclared and if this is not a function
1107 // call, diagnose the problem.
1108 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001109 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001110 return ExprError();
1111
1112 assert(!R.empty() &&
1113 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001114
1115 // If we found an Objective-C instance variable, let
1116 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001117 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001118 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1119 R.clear();
1120 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1121 assert(E.isInvalid() || E.get());
1122 return move(E);
1123 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 }
1125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
John McCallf7a1a742009-11-24 19:00:30 +00001127 // This is guaranteed from this point on.
1128 assert(!R.empty() || ADL);
1129
1130 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001131 // Warn about constructs like:
1132 // if (void *X = foo()) { ... } else { X }.
1133 // In the else block, the pointer is always false.
Douglas Gregor751f9a42009-06-30 15:47:41 +00001134 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1135 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001136 while (CheckS && CheckS->getControlParent()) {
Chris Lattner966c78b2010-04-12 06:12:50 +00001137 if ((CheckS->getFlags() & Scope::ElseScope) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001138 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001139 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001140 << Var->getDeclName()
Chris Lattner966c78b2010-04-12 06:12:50 +00001141 << (Var->getType()->isPointerType() ? 2 :
1142 Var->getType()->isBooleanType() ? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001143 break;
1144 }
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001146 // Move to the parent of this scope.
1147 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001148 }
1149 }
John McCallf7a1a742009-11-24 19:00:30 +00001150 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001151 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1152 // C99 DR 316 says that, if a function type comes from a
1153 // function definition (without a prototype), that type is only
1154 // used for checking compatibility. Therefore, when referencing
1155 // the function, we pretend that we don't have the full function
1156 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001157 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001158 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001159
Douglas Gregor751f9a42009-06-30 15:47:41 +00001160 QualType T = Func->getType();
1161 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001162 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001163 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001164 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001165 }
1166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCallaa81e162009-12-01 22:10:20 +00001168 // Check whether this might be a C++ implicit instance member access.
1169 // C++ [expr.prim.general]p6:
1170 // Within the definition of a non-static member function, an
1171 // identifier that names a non-static member is transformed to a
1172 // class member access expression.
1173 // But note that &SomeClass::foo is grammatically distinct, even
1174 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001175 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001176 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001177 if (!isAbstractMemberPointer)
1178 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001179 }
1180
John McCallf7a1a742009-11-24 19:00:30 +00001181 if (TemplateArgs)
1182 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001183
John McCallf7a1a742009-11-24 19:00:30 +00001184 return BuildDeclarationNameExpr(SS, R, ADL);
1185}
1186
John McCall3b4294e2009-12-16 12:17:52 +00001187/// Builds an expression which might be an implicit member expression.
1188Sema::OwningExprResult
1189Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1190 LookupResult &R,
1191 const TemplateArgumentListInfo *TemplateArgs) {
1192 switch (ClassifyImplicitMemberAccess(*this, R)) {
1193 case IMA_Instance:
1194 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1195
1196 case IMA_AnonymousMember:
1197 assert(R.isSingleResult());
1198 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1199 R.getAsSingle<FieldDecl>());
1200
1201 case IMA_Mixed:
1202 case IMA_Mixed_Unrelated:
1203 case IMA_Unresolved:
1204 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1205
1206 case IMA_Static:
1207 case IMA_Mixed_StaticContext:
1208 case IMA_Unresolved_StaticContext:
1209 if (TemplateArgs)
1210 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1211 return BuildDeclarationNameExpr(SS, R, false);
1212
1213 case IMA_Error_StaticContext:
1214 case IMA_Error_Unrelated:
1215 DiagnoseInstanceReference(*this, SS, R);
1216 return ExprError();
1217 }
1218
1219 llvm_unreachable("unexpected instance member access kind");
1220 return ExprError();
1221}
1222
John McCall129e2df2009-11-30 22:42:35 +00001223/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1224/// declaration name, generally during template instantiation.
1225/// There's a large number of things which don't need to be done along
1226/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001227Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001228Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001229 DeclarationName Name,
1230 SourceLocation NameLoc) {
1231 DeclContext *DC;
1232 if (!(DC = computeDeclContext(SS, false)) ||
1233 DC->isDependentContext() ||
1234 RequireCompleteDeclContext(SS))
1235 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1236
1237 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1238 LookupQualifiedName(R, DC);
1239
1240 if (R.isAmbiguous())
1241 return ExprError();
1242
1243 if (R.empty()) {
1244 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1245 return ExprError();
1246 }
1247
1248 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1249}
1250
1251/// LookupInObjCMethod - The parser has read a name in, and Sema has
1252/// detected that we're currently inside an ObjC method. Perform some
1253/// additional lookup.
1254///
1255/// Ideally, most of this would be done by lookup, but there's
1256/// actually quite a lot of extra work involved.
1257///
1258/// Returns a null sentinel to indicate trivial success.
1259Sema::OwningExprResult
1260Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001261 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001262 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001263 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Chris Lattnereb483eb2010-04-11 08:28:14 +00001264
John McCallf7a1a742009-11-24 19:00:30 +00001265 // There are two cases to handle here. 1) scoped lookup could have failed,
1266 // in which case we should look for an ivar. 2) scoped lookup could have
1267 // found a decl, but that decl is outside the current instance method (i.e.
1268 // a global variable). In these two cases, we do a lookup for an ivar with
1269 // this name, if the lookup sucedes, we replace it our current decl.
1270
1271 // If we're in a class method, we don't normally want to look for
1272 // ivars. But if we don't find anything else, and there's an
1273 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001274 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001275
1276 bool LookForIvars;
1277 if (Lookup.empty())
1278 LookForIvars = true;
1279 else if (IsClassMethod)
1280 LookForIvars = false;
1281 else
1282 LookForIvars = (Lookup.isSingleResult() &&
1283 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001284 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001285 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001286 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001287 ObjCInterfaceDecl *ClassDeclared;
1288 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1289 // Diagnose using an ivar in a class method.
1290 if (IsClassMethod)
1291 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1292 << IV->getDeclName());
1293
1294 // If we're referencing an invalid decl, just return this as a silent
1295 // error node. The error diagnostic was already emitted on the decl.
1296 if (IV->isInvalidDecl())
1297 return ExprError();
1298
1299 // Check if referencing a field with __attribute__((deprecated)).
1300 if (DiagnoseUseOfDecl(IV, Loc))
1301 return ExprError();
1302
1303 // Diagnose the use of an ivar outside of the declaring class.
1304 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1305 ClassDeclared != IFace)
1306 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1307
1308 // FIXME: This should use a new expr for a direct reference, don't
1309 // turn this into Self->ivar, just return a BareIVarExpr or something.
1310 IdentifierInfo &II = Context.Idents.get("self");
1311 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001312 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001313 CXXScopeSpec SelfScopeSpec;
1314 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1315 SelfName, false, false);
1316 MarkDeclarationReferenced(Loc, IV);
1317 return Owned(new (Context)
1318 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1319 SelfExpr.takeAs<Expr>(), true, true));
1320 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001321 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001322 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001323 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001324 ObjCInterfaceDecl *ClassDeclared;
1325 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1326 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1327 IFace == ClassDeclared)
1328 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1329 }
1330 }
1331
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001332 if (Lookup.empty() && II && AllowBuiltinCreation) {
1333 // FIXME. Consolidate this with similar code in LookupName.
1334 if (unsigned BuiltinID = II->getBuiltinID()) {
1335 if (!(getLangOptions().CPlusPlus &&
1336 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1337 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1338 S, Lookup.isForRedeclaration(),
1339 Lookup.getNameLoc());
1340 if (D) Lookup.addDecl(D);
1341 }
1342 }
1343 }
John McCallf7a1a742009-11-24 19:00:30 +00001344 // Sentinel value saying that we didn't do anything special.
1345 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001346}
John McCallba135432009-11-21 08:51:07 +00001347
John McCall6bb80172010-03-30 21:47:33 +00001348/// \brief Cast a base object to a member's actual type.
1349///
1350/// Logically this happens in three phases:
1351///
1352/// * First we cast from the base type to the naming class.
1353/// The naming class is the class into which we were looking
1354/// when we found the member; it's the qualifier type if a
1355/// qualifier was provided, and otherwise it's the base type.
1356///
1357/// * Next we cast from the naming class to the declaring class.
1358/// If the member we found was brought into a class's scope by
1359/// a using declaration, this is that class; otherwise it's
1360/// the class declaring the member.
1361///
1362/// * Finally we cast from the declaring class to the "true"
1363/// declaring class of the member. This conversion does not
1364/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001365bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001366Sema::PerformObjectMemberConversion(Expr *&From,
1367 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001368 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001369 NamedDecl *Member) {
1370 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1371 if (!RD)
1372 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001373
Douglas Gregor5fccd362010-03-03 23:55:11 +00001374 QualType DestRecordType;
1375 QualType DestType;
1376 QualType FromRecordType;
1377 QualType FromType = From->getType();
1378 bool PointerConversions = false;
1379 if (isa<FieldDecl>(Member)) {
1380 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001381
Douglas Gregor5fccd362010-03-03 23:55:11 +00001382 if (FromType->getAs<PointerType>()) {
1383 DestType = Context.getPointerType(DestRecordType);
1384 FromRecordType = FromType->getPointeeType();
1385 PointerConversions = true;
1386 } else {
1387 DestType = DestRecordType;
1388 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001389 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001390 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1391 if (Method->isStatic())
1392 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001393
Douglas Gregor5fccd362010-03-03 23:55:11 +00001394 DestType = Method->getThisType(Context);
1395 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001396
Douglas Gregor5fccd362010-03-03 23:55:11 +00001397 if (FromType->getAs<PointerType>()) {
1398 FromRecordType = FromType->getPointeeType();
1399 PointerConversions = true;
1400 } else {
1401 FromRecordType = FromType;
1402 DestType = DestRecordType;
1403 }
1404 } else {
1405 // No conversion necessary.
1406 return false;
1407 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001408
Douglas Gregor5fccd362010-03-03 23:55:11 +00001409 if (DestType->isDependentType() || FromType->isDependentType())
1410 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001411
Douglas Gregor5fccd362010-03-03 23:55:11 +00001412 // If the unqualified types are the same, no conversion is necessary.
1413 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1414 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001415
John McCall6bb80172010-03-30 21:47:33 +00001416 SourceRange FromRange = From->getSourceRange();
1417 SourceLocation FromLoc = FromRange.getBegin();
1418
Douglas Gregor5fccd362010-03-03 23:55:11 +00001419 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001420 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001421 // class name.
1422 //
1423 // If the member was a qualified name and the qualified referred to a
1424 // specific base subobject type, we'll cast to that intermediate type
1425 // first and then to the object in which the member is declared. That allows
1426 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1427 //
1428 // class Base { public: int x; };
1429 // class Derived1 : public Base { };
1430 // class Derived2 : public Base { };
1431 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1432 //
1433 // void VeryDerived::f() {
1434 // x = 17; // error: ambiguous base subobjects
1435 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1436 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001437 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001438 QualType QType = QualType(Qualifier->getAsType(), 0);
1439 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1440 assert(QType->isRecordType() && "lookup done with non-record type");
1441
1442 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1443
1444 // In C++98, the qualifier type doesn't actually have to be a base
1445 // type of the object type, in which case we just ignore it.
1446 // Otherwise build the appropriate casts.
1447 if (IsDerivedFrom(FromRecordType, QRecordType)) {
Anders Carlssoncee22422010-04-24 19:22:20 +00001448 CXXBaseSpecifierArray BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001449 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001450 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001451 return true;
1452
Douglas Gregor5fccd362010-03-03 23:55:11 +00001453 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001454 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001455 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlssoncee22422010-04-24 19:22:20 +00001456 /*isLvalue=*/!PointerConversions, BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001457
1458 FromType = QType;
1459 FromRecordType = QRecordType;
1460
1461 // If the qualifier type was the same as the destination type,
1462 // we're done.
1463 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1464 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001465 }
1466 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001467
John McCall6bb80172010-03-30 21:47:33 +00001468 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001469
John McCall6bb80172010-03-30 21:47:33 +00001470 // If we actually found the member through a using declaration, cast
1471 // down to the using declaration's type.
1472 //
1473 // Pointer equality is fine here because only one declaration of a
1474 // class ever has member declarations.
1475 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1476 assert(isa<UsingShadowDecl>(FoundDecl));
1477 QualType URecordType = Context.getTypeDeclType(
1478 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1479
1480 // We only need to do this if the naming-class to declaring-class
1481 // conversion is non-trivial.
1482 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1483 assert(IsDerivedFrom(FromRecordType, URecordType));
Anders Carlssoncee22422010-04-24 19:22:20 +00001484 CXXBaseSpecifierArray BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001485 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001486 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001487 return true;
1488
1489 QualType UType = URecordType;
1490 if (PointerConversions)
1491 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001492 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlssoncee22422010-04-24 19:22:20 +00001493 /*isLvalue=*/!PointerConversions, BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001494 FromType = UType;
1495 FromRecordType = URecordType;
1496 }
1497
1498 // We don't do access control for the conversion from the
1499 // declaring class to the true declaring class.
1500 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001501 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001502
Anders Carlssoncee22422010-04-24 19:22:20 +00001503 CXXBaseSpecifierArray BasePath;
1504 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1505 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00001506 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001507 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001508
John McCall23cba802010-03-30 23:58:03 +00001509 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
Anders Carlssoncee22422010-04-24 19:22:20 +00001510 /*isLvalue=*/!PointerConversions, BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001511 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001512}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001513
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001514/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001515static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001516 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001517 DeclAccessPair FoundDecl,
1518 SourceLocation Loc, QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001519 const TemplateArgumentListInfo *TemplateArgs = 0) {
1520 NestedNameSpecifier *Qualifier = 0;
1521 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001522 if (SS.isSet()) {
1523 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1524 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
John McCallf7a1a742009-11-24 19:00:30 +00001527 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
John McCall6bb80172010-03-30 21:47:33 +00001528 Member, FoundDecl, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001529}
1530
John McCallaa81e162009-12-01 22:10:20 +00001531/// Builds an implicit member access expression. The current context
1532/// is known to be an instance method, and the given unqualified lookup
1533/// set is known to contain only instance members, at least one of which
1534/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001535Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001536Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1537 LookupResult &R,
1538 const TemplateArgumentListInfo *TemplateArgs,
1539 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001540 assert(!R.empty() && !R.isAmbiguous());
1541
John McCallba135432009-11-21 08:51:07 +00001542 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001543
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001544 // We may have found a field within an anonymous union or struct
1545 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001546 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001547 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001548 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001549 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001550 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001551
John McCallaa81e162009-12-01 22:10:20 +00001552 // If this is known to be an instance access, go ahead and build a
1553 // 'this' expression now.
1554 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1555 Expr *This = 0; // null signifies implicit access
1556 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001557 SourceLocation Loc = R.getNameLoc();
1558 if (SS.getRange().isValid())
1559 Loc = SS.getRange().getBegin();
1560 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001561 }
1562
John McCallaa81e162009-12-01 22:10:20 +00001563 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1564 /*OpLoc*/ SourceLocation(),
1565 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001566 SS,
1567 /*FirstQualifierInScope*/ 0,
1568 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001569}
1570
John McCallf7a1a742009-11-24 19:00:30 +00001571bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001572 const LookupResult &R,
1573 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001574 // Only when used directly as the postfix-expression of a call.
1575 if (!HasTrailingLParen)
1576 return false;
1577
1578 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001579 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001580 return false;
1581
1582 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001583 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001584 return false;
1585
1586 // Turn off ADL when we find certain kinds of declarations during
1587 // normal lookup:
1588 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1589 NamedDecl *D = *I;
1590
1591 // C++0x [basic.lookup.argdep]p3:
1592 // -- a declaration of a class member
1593 // Since using decls preserve this property, we check this on the
1594 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001595 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001596 return false;
1597
1598 // C++0x [basic.lookup.argdep]p3:
1599 // -- a block-scope function declaration that is not a
1600 // using-declaration
1601 // NOTE: we also trigger this for function templates (in fact, we
1602 // don't check the decl type at all, since all other decl types
1603 // turn off ADL anyway).
1604 if (isa<UsingShadowDecl>(D))
1605 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1606 else if (D->getDeclContext()->isFunctionOrMethod())
1607 return false;
1608
1609 // C++0x [basic.lookup.argdep]p3:
1610 // -- a declaration that is neither a function or a function
1611 // template
1612 // And also for builtin functions.
1613 if (isa<FunctionDecl>(D)) {
1614 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1615
1616 // But also builtin functions.
1617 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1618 return false;
1619 } else if (!isa<FunctionTemplateDecl>(D))
1620 return false;
1621 }
1622
1623 return true;
1624}
1625
1626
John McCallba135432009-11-21 08:51:07 +00001627/// Diagnoses obvious problems with the use of the given declaration
1628/// as an expression. This is only actually called for lookups that
1629/// were not overloaded, and it doesn't promise that the declaration
1630/// will in fact be used.
1631static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1632 if (isa<TypedefDecl>(D)) {
1633 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1634 return true;
1635 }
1636
1637 if (isa<ObjCInterfaceDecl>(D)) {
1638 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1639 return true;
1640 }
1641
1642 if (isa<NamespaceDecl>(D)) {
1643 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1644 return true;
1645 }
1646
1647 return false;
1648}
1649
1650Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001651Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001652 LookupResult &R,
1653 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001654 // If this is a single, fully-resolved result and we don't need ADL,
1655 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001656 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCall5b3f9132009-11-22 01:44:31 +00001657 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001658
1659 // We only need to check the declaration if there's exactly one
1660 // result, because in the overloaded case the results can only be
1661 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001662 if (R.isSingleResult() &&
1663 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001664 return ExprError();
1665
John McCallc373d482010-01-27 01:50:18 +00001666 // Otherwise, just build an unresolved lookup expression. Suppress
1667 // any lookup-related diagnostics; we'll hash these out later, when
1668 // we've picked a target.
1669 R.suppressDiagnostics();
1670
John McCallf7a1a742009-11-24 19:00:30 +00001671 bool Dependent
1672 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001673 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001674 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001675 (NestedNameSpecifier*) SS.getScopeRep(),
1676 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001677 R.getLookupName(), R.getNameLoc(),
1678 NeedsADL, R.isOverloadedResult());
John McCallc373d482010-01-27 01:50:18 +00001679 ULE->addDecls(R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001680
1681 return Owned(ULE);
1682}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001683
John McCallba135432009-11-21 08:51:07 +00001684
1685/// \brief Complete semantic analysis for a reference to the given declaration.
1686Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001687Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001688 SourceLocation Loc, NamedDecl *D) {
1689 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001690 assert(!isa<FunctionTemplateDecl>(D) &&
1691 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001692
1693 if (CheckDeclInExpr(*this, Loc, D))
1694 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001695
Douglas Gregor9af2f522009-12-01 16:58:18 +00001696 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1697 // Specifically diagnose references to class templates that are missing
1698 // a template argument list.
1699 Diag(Loc, diag::err_template_decl_ref)
1700 << Template << SS.getRange();
1701 Diag(Template->getLocation(), diag::note_template_decl_here);
1702 return ExprError();
1703 }
1704
1705 // Make sure that we're referring to a value.
1706 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1707 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001708 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001709 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001710 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001711 return ExprError();
1712 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001713
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001714 // Check whether this declaration can be used. Note that we suppress
1715 // this check when we're going to perform argument-dependent lookup
1716 // on this function name, because this might not be the function
1717 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001718 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001719 return ExprError();
1720
Steve Naroffdd972f22008-09-05 22:11:13 +00001721 // Only create DeclRefExpr's for valid Decl's.
1722 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001723 return ExprError();
1724
Chris Lattner639e2d32008-10-20 05:16:36 +00001725 // If the identifier reference is inside a block, and it refers to a value
1726 // that is outside the block, create a BlockDeclRefExpr instead of a
1727 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1728 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001729 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001730 // We do not do this for things like enum constants, global variables, etc,
1731 // as they do not get snapshotted.
1732 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001733 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001734 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001735 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1736 Diag(Loc, diag::err_ref_vm_type);
1737 Diag(D->getLocation(), diag::note_declared_at);
1738 return ExprError();
1739 }
1740
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001741 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001742 Diag(Loc, diag::err_ref_array_type);
1743 Diag(D->getLocation(), diag::note_declared_at);
1744 return ExprError();
1745 }
1746
Douglas Gregore0762c92009-06-19 23:52:42 +00001747 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001748 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001749 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001750 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001751 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001752 // This is to record that a 'const' was actually synthesize and added.
1753 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001754 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Eli Friedman5fdeae12009-03-22 23:00:19 +00001756 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001757 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001758 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001759 }
1760 // If this reference is not in a block or if the referenced variable is
1761 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001762
John McCallf7a1a742009-11-24 19:00:30 +00001763 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001764}
1765
Sebastian Redlcd965b92009-01-18 18:53:16 +00001766Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1767 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001768 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001771 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001772 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1773 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1774 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001776
Chris Lattnerfa28b302008-01-12 08:14:25 +00001777 // Pre-defined identifiers are of type char[x], where x is the length of the
1778 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Anders Carlsson3a082d82009-09-08 18:24:21 +00001780 Decl *currentDecl = getCurFunctionOrMethodDecl();
1781 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001782 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001783 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001784 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001785
Anders Carlsson773f3972009-09-11 01:22:35 +00001786 QualType ResTy;
1787 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1788 ResTy = Context.DependentTy;
1789 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001790 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001791
Anders Carlsson773f3972009-09-11 01:22:35 +00001792 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001793 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001794 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1795 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001796 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001797}
1798
Sebastian Redlcd965b92009-01-18 18:53:16 +00001799Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001801 bool Invalid = false;
1802 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1803 if (Invalid)
1804 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001805
Benjamin Kramerddeea562010-02-27 13:44:12 +00001806 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1807 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001809 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001810
Chris Lattnere8337df2009-12-30 21:19:39 +00001811 QualType Ty;
1812 if (!getLangOptions().CPlusPlus)
1813 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1814 else if (Literal.isWide())
1815 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001816 else if (Literal.isMultiChar())
1817 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001818 else
1819 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001820
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001821 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1822 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001823 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001824}
1825
Sebastian Redlcd965b92009-01-18 18:53:16 +00001826Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1827 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1829 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001830 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001831 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001832 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001833 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 }
Ted Kremenek28396602009-01-13 23:19:12 +00001835
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001837 // Add padding so that NumericLiteralParser can overread by one character.
1838 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001842 bool Invalid = false;
1843 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1844 if (Invalid)
1845 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001846
Mike Stump1eb44332009-09-09 15:08:12 +00001847 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 Tok.getLocation(), PP);
1849 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001850 return ExprError();
1851
Chris Lattner5d661452007-08-26 03:42:43 +00001852 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001853
Chris Lattner5d661452007-08-26 03:42:43 +00001854 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001855 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001856 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001857 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001858 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001859 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001860 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001861 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001862
1863 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1864
John McCall94c939d2009-12-24 09:08:04 +00001865 using llvm::APFloat;
1866 APFloat Val(Format);
1867
1868 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001869
1870 // Overflow is always an error, but underflow is only an error if
1871 // we underflowed to zero (APFloat reports denormals as underflow).
1872 if ((result & APFloat::opOverflow) ||
1873 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001874 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001875 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001876 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001877 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001878 APFloat::getLargest(Format).toString(buffer);
1879 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001880 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001881 APFloat::getSmallest(Format).toString(buffer);
1882 }
1883
1884 Diag(Tok.getLocation(), diagnostic)
1885 << Ty
1886 << llvm::StringRef(buffer.data(), buffer.size());
1887 }
1888
1889 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001890 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001891
Chris Lattner5d661452007-08-26 03:42:43 +00001892 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001893 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001894 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001895 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001896
Neil Boothb9449512007-08-29 22:00:19 +00001897 // long long is a C99 feature.
1898 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001899 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001900 Diag(Tok.getLocation(), diag::ext_longlong);
1901
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001903 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001904
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 if (Literal.GetIntegerValue(ResultVal)) {
1906 // If this value didn't fit into uintmax_t, warn and force to ull.
1907 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001908 Ty = Context.UnsignedLongLongTy;
1909 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001910 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 } else {
1912 // If this value fits into a ULL, try to figure out what else it fits into
1913 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1916 // be an unsigned int.
1917 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1918
1919 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001920 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001921 if (!Literal.isLong && !Literal.isLongLong) {
1922 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001923 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // Does it fit in a unsigned int?
1926 if (ResultVal.isIntN(IntSize)) {
1927 // Does it fit in a signed int?
1928 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001929 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001931 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001932 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001937 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001938 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001939
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 // Does it fit in a unsigned long?
1941 if (ResultVal.isIntN(LongSize)) {
1942 // Does it fit in a signed long?
1943 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001944 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001946 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001947 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001949 }
1950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001952 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001953 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 // Does it fit in a unsigned long long?
1956 if (ResultVal.isIntN(LongLongSize)) {
1957 // Does it fit in a signed long long?
1958 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001959 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001961 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001962 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 }
1964 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001965
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 // If we still couldn't decide a type, we probably have something that
1967 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001968 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001970 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001971 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001973
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001974 if (ResultVal.getBitWidth() != Width)
1975 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001977 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001979
Chris Lattner5d661452007-08-26 03:42:43 +00001980 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1981 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001982 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001983 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001984
1985 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001986}
1987
Sebastian Redlcd965b92009-01-18 18:53:16 +00001988Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1989 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001990 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001991 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001992 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001993}
1994
1995/// The UsualUnaryConversions() function is *not* called by this routine.
1996/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001997bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001998 SourceLocation OpLoc,
1999 const SourceRange &ExprRange,
2000 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002001 if (exprType->isDependentType())
2002 return false;
2003
Sebastian Redl5d484e82009-11-23 17:18:46 +00002004 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2005 // the result is the size of the referenced type."
2006 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2007 // result shall be the alignment of the referenced type."
2008 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2009 exprType = Ref->getPointeeType();
2010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002012 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002013 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002014 if (isSizeof)
2015 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2016 return false;
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Chris Lattner1efaa952009-04-24 00:30:45 +00002019 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002020 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002021 Diag(OpLoc, diag::ext_sizeof_void_type)
2022 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002023 return false;
2024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Chris Lattner1efaa952009-04-24 00:30:45 +00002026 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002027 PDiag(diag::err_sizeof_alignof_incomplete_type)
2028 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002029 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Chris Lattner1efaa952009-04-24 00:30:45 +00002031 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00002032 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002033 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002034 << exprType << isSizeof << ExprRange;
2035 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002036 }
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Chris Lattner1efaa952009-04-24 00:30:45 +00002038 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002039}
2040
Chris Lattner31e21e02009-01-24 20:17:12 +00002041bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2042 const SourceRange &ExprRange) {
2043 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002044
Mike Stump1eb44332009-09-09 15:08:12 +00002045 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002046 if (isa<DeclRefExpr>(E))
2047 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002048
2049 // Cannot know anything else if the expression is dependent.
2050 if (E->isTypeDependent())
2051 return false;
2052
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002053 if (E->getBitField()) {
2054 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2055 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002056 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002057
2058 // Alignment of a field access is always okay, so long as it isn't a
2059 // bit-field.
2060 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002061 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002062 return false;
2063
Chris Lattner31e21e02009-01-24 20:17:12 +00002064 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2065}
2066
Douglas Gregorba498172009-03-13 21:01:28 +00002067/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002068Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002069Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002070 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002071 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002072 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002073 return ExprError();
2074
John McCalla93c9342009-12-07 02:54:59 +00002075 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002076
Douglas Gregorba498172009-03-13 21:01:28 +00002077 if (!T->isDependentType() &&
2078 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2079 return ExprError();
2080
2081 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002082 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002083 Context.getSizeType(), OpLoc,
2084 R.getEnd()));
2085}
2086
2087/// \brief Build a sizeof or alignof expression given an expression
2088/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002089Action::OwningExprResult
2090Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002091 bool isSizeOf, SourceRange R) {
2092 // Verify that the operand is valid.
2093 bool isInvalid = false;
2094 if (E->isTypeDependent()) {
2095 // Delay type-checking for type-dependent expressions.
2096 } else if (!isSizeOf) {
2097 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002098 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002099 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2100 isInvalid = true;
2101 } else {
2102 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2103 }
2104
2105 if (isInvalid)
2106 return ExprError();
2107
2108 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2109 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2110 Context.getSizeType(), OpLoc,
2111 R.getEnd()));
2112}
2113
Sebastian Redl05189992008-11-11 17:56:53 +00002114/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2115/// the same for @c alignof and @c __alignof
2116/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002117Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002118Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2119 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002121 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002122
Sebastian Redl05189992008-11-11 17:56:53 +00002123 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002124 TypeSourceInfo *TInfo;
2125 (void) GetTypeFromParser(TyOrEx, &TInfo);
2126 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002127 }
Sebastian Redl05189992008-11-11 17:56:53 +00002128
Douglas Gregorba498172009-03-13 21:01:28 +00002129 Expr *ArgEx = (Expr *)TyOrEx;
2130 Action::OwningExprResult Result
2131 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2132
2133 if (Result.isInvalid())
2134 DeleteExpr(ArgEx);
2135
2136 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002137}
2138
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002139QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002140 if (V->isTypeDependent())
2141 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Chris Lattnercc26ed72007-08-26 05:39:26 +00002143 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002144 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002145 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattnercc26ed72007-08-26 05:39:26 +00002147 // Otherwise they pass through real integer and floating point types here.
2148 if (V->getType()->isArithmeticType())
2149 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Chris Lattnercc26ed72007-08-26 05:39:26 +00002151 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002152 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2153 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002154 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002155}
2156
2157
Reid Spencer5f016e22007-07-11 17:01:13 +00002158
Sebastian Redl0eb23302009-01-19 00:08:26 +00002159Action::OwningExprResult
2160Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2161 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 UnaryOperator::Opcode Opc;
2163 switch (Kind) {
2164 default: assert(0 && "Unknown unary op!");
2165 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2166 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2167 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002168
Eli Friedmane4216e92009-11-18 03:38:04 +00002169 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00002170}
2171
Sebastian Redl0eb23302009-01-19 00:08:26 +00002172Action::OwningExprResult
2173Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2174 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002175 // Since this might be a postfix expression, get rid of ParenListExprs.
2176 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2177
Sebastian Redl0eb23302009-01-19 00:08:26 +00002178 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2179 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Douglas Gregor337c6b92008-11-19 17:17:41 +00002181 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002182 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2183 Base.release();
2184 Idx.release();
2185 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2186 Context.DependentTy, RLoc));
2187 }
2188
Mike Stump1eb44332009-09-09 15:08:12 +00002189 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002190 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002191 LHSExp->getType()->isEnumeralType() ||
2192 RHSExp->getType()->isRecordType() ||
2193 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002194 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002195 }
2196
Sebastian Redlf322ed62009-10-29 20:17:01 +00002197 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2198}
2199
2200
2201Action::OwningExprResult
2202Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2203 ExprArg Idx, SourceLocation RLoc) {
2204 Expr *LHSExp = static_cast<Expr*>(Base.get());
2205 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2206
Chris Lattner12d9ff62007-07-16 00:14:47 +00002207 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002208 if (!LHSExp->getType()->getAs<VectorType>())
2209 DefaultFunctionArrayLvalueConversion(LHSExp);
2210 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002211
Chris Lattner12d9ff62007-07-16 00:14:47 +00002212 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002213
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002215 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002216 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002218 Expr *BaseExpr, *IndexExpr;
2219 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002220 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2221 BaseExpr = LHSExp;
2222 IndexExpr = RHSExp;
2223 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002224 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002225 BaseExpr = LHSExp;
2226 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002227 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002228 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002229 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002230 BaseExpr = RHSExp;
2231 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002232 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002233 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002234 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002235 BaseExpr = LHSExp;
2236 IndexExpr = RHSExp;
2237 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002238 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002239 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002240 // Handle the uncommon case of "123[Ptr]".
2241 BaseExpr = RHSExp;
2242 IndexExpr = LHSExp;
2243 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002244 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002245 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002246 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002247
Chris Lattner12d9ff62007-07-16 00:14:47 +00002248 // FIXME: need to deal with const...
2249 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002250 } else if (LHSTy->isArrayType()) {
2251 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002252 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002253 // wasn't promoted because of the C90 rule that doesn't
2254 // allow promoting non-lvalue arrays. Warn, then
2255 // force the promotion here.
2256 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2257 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002258 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2259 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002260 LHSTy = LHSExp->getType();
2261
2262 BaseExpr = LHSExp;
2263 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002264 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002265 } else if (RHSTy->isArrayType()) {
2266 // Same as previous, except for 123[f().a] case
2267 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2268 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002269 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2270 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002271 RHSTy = RHSExp->getType();
2272
2273 BaseExpr = RHSExp;
2274 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002275 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002276 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002277 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2278 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002279 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002281 if (!(IndexExpr->getType()->isIntegerType() &&
2282 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002283 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2284 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002285
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002286 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002287 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2288 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002289 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2290
Douglas Gregore7450f52009-03-24 19:52:54 +00002291 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002292 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2293 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002294 // incomplete types are not object types.
2295 if (ResultType->isFunctionType()) {
2296 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2297 << ResultType << BaseExpr->getSourceRange();
2298 return ExprError();
2299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Douglas Gregore7450f52009-03-24 19:52:54 +00002301 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002302 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002303 PDiag(diag::err_subscript_incomplete_type)
2304 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002305 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Chris Lattner1efaa952009-04-24 00:30:45 +00002307 // Diagnose bad cases where we step over interface counts.
2308 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2309 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2310 << ResultType << BaseExpr->getSourceRange();
2311 return ExprError();
2312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Sebastian Redl0eb23302009-01-19 00:08:26 +00002314 Base.release();
2315 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002316 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002317 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002318}
2319
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002320QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002321CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002322 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002323 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002324 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2325 // see FIXME there.
2326 //
2327 // FIXME: This logic can be greatly simplified by splitting it along
2328 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002329 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002330
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002331 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002332 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002333
Mike Stumpeed9cac2009-02-19 03:04:26 +00002334 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002335 // special names that indicate a subset of exactly half the elements are
2336 // to be selected.
2337 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002338
Nate Begeman353417a2009-01-18 01:47:54 +00002339 // This flag determines whether or not CompName has an 's' char prefix,
2340 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002341 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002342
2343 // Check that we've found one of the special components, or that the component
2344 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002345 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002346 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2347 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002348 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002349 do
2350 compStr++;
2351 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002352 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002353 do
2354 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002355 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002356 }
Nate Begeman353417a2009-01-18 01:47:54 +00002357
Mike Stumpeed9cac2009-02-19 03:04:26 +00002358 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002359 // We didn't get to the end of the string. This means the component names
2360 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002361 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2362 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002363 return QualType();
2364 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002365
Nate Begeman353417a2009-01-18 01:47:54 +00002366 // Ensure no component accessor exceeds the width of the vector type it
2367 // operates on.
2368 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002369 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002370
2371 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002372 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002373
2374 while (*compStr) {
2375 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2376 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2377 << baseType << SourceRange(CompLoc);
2378 return QualType();
2379 }
2380 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002381 }
Nate Begeman8a997642008-05-09 06:41:27 +00002382
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002383 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002384 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002385 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002386 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002387 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002388 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002389 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002390 if (HexSwizzle)
2391 CompSize--;
2392
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002393 if (CompSize == 1)
2394 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002395
Nate Begeman213541a2008-04-18 23:10:10 +00002396 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002397 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002398 // diagostics look bad. We want extended vector types to appear built-in.
2399 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2400 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2401 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002402 }
2403 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002404}
2405
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002406static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002407 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002408 const Selector &Sel,
2409 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Anders Carlsson8f28f992009-08-26 18:25:21 +00002411 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002412 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002413 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002414 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002416 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2417 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002419 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002420 return D;
2421 }
2422 return 0;
2423}
2424
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002425static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002426 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002427 const Selector &Sel,
2428 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002429 // Check protocols on qualified interfaces.
2430 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002431 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002432 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002433 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002434 GDecl = PD;
2435 break;
2436 }
2437 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002438 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002439 GDecl = OMD;
2440 break;
2441 }
2442 }
2443 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002444 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002445 E = QIdTy->qual_end(); I != E; ++I) {
2446 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002447 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002448 if (GDecl)
2449 return GDecl;
2450 }
2451 }
2452 return GDecl;
2453}
Chris Lattner76a642f2009-02-15 22:43:40 +00002454
John McCall129e2df2009-11-30 22:42:35 +00002455Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002456Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2457 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002458 const CXXScopeSpec &SS,
2459 NamedDecl *FirstQualifierInScope,
2460 DeclarationName Name, SourceLocation NameLoc,
2461 const TemplateArgumentListInfo *TemplateArgs) {
2462 Expr *BaseExpr = Base.takeAs<Expr>();
2463
2464 // Even in dependent contexts, try to diagnose base expressions with
2465 // obviously wrong types, e.g.:
2466 //
2467 // T* t;
2468 // t.f;
2469 //
2470 // In Obj-C++, however, the above expression is valid, since it could be
2471 // accessing the 'f' property if T is an Obj-C interface. The extra check
2472 // allows this, while still reporting an error if T is a struct pointer.
2473 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002474 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002475 if (PT && (!getLangOptions().ObjC1 ||
2476 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002477 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002478 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002479 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002480 return ExprError();
2481 }
2482 }
2483
Douglas Gregor01e56ae2010-04-12 20:54:26 +00002484 assert(BaseType->isDependentType() || Name.isDependentName() ||
2485 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00002486
2487 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2488 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002489 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002490 IsArrow, OpLoc,
2491 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2492 SS.getRange(),
2493 FirstQualifierInScope,
2494 Name, NameLoc,
2495 TemplateArgs));
2496}
2497
2498/// We know that the given qualified member reference points only to
2499/// declarations which do not belong to the static type of the base
2500/// expression. Diagnose the problem.
2501static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2502 Expr *BaseExpr,
2503 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002504 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002505 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002506 // If this is an implicit member access, use a different set of
2507 // diagnostics.
2508 if (!BaseExpr)
2509 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002510
John McCall110acc12010-04-27 01:43:38 +00002511 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2512 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002513}
2514
2515// Check whether the declarations we found through a nested-name
2516// specifier in a member expression are actually members of the base
2517// type. The restriction here is:
2518//
2519// C++ [expr.ref]p2:
2520// ... In these cases, the id-expression shall name a
2521// member of the class or of one of its base classes.
2522//
2523// So it's perfectly legitimate for the nested-name specifier to name
2524// an unrelated class, and for us to find an overload set including
2525// decls from classes which are not superclasses, as long as the decl
2526// we actually pick through overload resolution is from a superclass.
2527bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2528 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002529 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002530 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002531 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2532 if (!BaseRT) {
2533 // We can't check this yet because the base type is still
2534 // dependent.
2535 assert(BaseType->isDependentType());
2536 return false;
2537 }
2538 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002539
2540 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002541 // If this is an implicit member reference and we find a
2542 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00002543 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002544 return false;
John McCall129e2df2009-11-30 22:42:35 +00002545
John McCallaa81e162009-12-01 22:10:20 +00002546 // Note that we use the DC of the decl, not the underlying decl.
2547 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2548 while (RecordD->isAnonymousStructOrUnion())
2549 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2550
2551 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2552 MemberRecord.insert(RecordD->getCanonicalDecl());
2553
2554 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2555 return false;
2556 }
2557
John McCall2f841ba2009-12-02 03:53:29 +00002558 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002559 return true;
2560}
2561
2562static bool
2563LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2564 SourceRange BaseRange, const RecordType *RTy,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002565 SourceLocation OpLoc, CXXScopeSpec &SS) {
John McCallaa81e162009-12-01 22:10:20 +00002566 RecordDecl *RDecl = RTy->getDecl();
2567 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002568 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002569 << BaseRange))
2570 return true;
2571
2572 DeclContext *DC = RDecl;
2573 if (SS.isSet()) {
2574 // If the member name was a qualified-id, look into the
2575 // nested-name-specifier.
2576 DC = SemaRef.computeDeclContext(SS, false);
2577
John McCall2f841ba2009-12-02 03:53:29 +00002578 if (SemaRef.RequireCompleteDeclContext(SS)) {
2579 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2580 << SS.getRange() << DC;
2581 return true;
2582 }
2583
John McCallaa81e162009-12-01 22:10:20 +00002584 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002585
John McCallaa81e162009-12-01 22:10:20 +00002586 if (!isa<TypeDecl>(DC)) {
2587 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2588 << DC << SS.getRange();
2589 return true;
John McCall129e2df2009-11-30 22:42:35 +00002590 }
2591 }
2592
John McCallaa81e162009-12-01 22:10:20 +00002593 // The record definition is complete, now look up the member.
2594 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002595
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002596 if (!R.empty())
2597 return false;
2598
2599 // We didn't find anything with the given name, so try to correct
2600 // for typos.
2601 DeclarationName Name = R.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +00002602 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
2603 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002604 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2605 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2606 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00002607 << FixItHint::CreateReplacement(R.getNameLoc(),
2608 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002609 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2610 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2611 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002612 return false;
2613 } else {
2614 R.clear();
2615 }
2616
John McCall129e2df2009-11-30 22:42:35 +00002617 return false;
2618}
2619
2620Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002621Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002622 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002623 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002624 NamedDecl *FirstQualifierInScope,
2625 DeclarationName Name, SourceLocation NameLoc,
2626 const TemplateArgumentListInfo *TemplateArgs) {
2627 Expr *Base = BaseArg.takeAs<Expr>();
2628
John McCall2f841ba2009-12-02 03:53:29 +00002629 if (BaseType->isDependentType() ||
2630 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002631 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002632 IsArrow, OpLoc,
2633 SS, FirstQualifierInScope,
2634 Name, NameLoc,
2635 TemplateArgs);
2636
2637 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002638
John McCallaa81e162009-12-01 22:10:20 +00002639 // Implicit member accesses.
2640 if (!Base) {
2641 QualType RecordTy = BaseType;
2642 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2643 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2644 RecordTy->getAs<RecordType>(),
2645 OpLoc, SS))
2646 return ExprError();
2647
2648 // Explicit member accesses.
2649 } else {
2650 OwningExprResult Result =
2651 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00002652 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCallaa81e162009-12-01 22:10:20 +00002653
2654 if (Result.isInvalid()) {
2655 Owned(Base);
2656 return ExprError();
2657 }
2658
2659 if (Result.get())
2660 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002661 }
2662
John McCallaa81e162009-12-01 22:10:20 +00002663 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002664 OpLoc, IsArrow, SS, FirstQualifierInScope,
2665 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002666}
2667
2668Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002669Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2670 SourceLocation OpLoc, bool IsArrow,
2671 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002672 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002673 LookupResult &R,
2674 const TemplateArgumentListInfo *TemplateArgs) {
2675 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002676 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002677 if (IsArrow) {
2678 assert(BaseType->isPointerType());
2679 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2680 }
John McCall161755a2010-04-06 21:38:20 +00002681 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00002682
2683 NestedNameSpecifier *Qualifier =
2684 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2685 DeclarationName MemberName = R.getLookupName();
2686 SourceLocation MemberLoc = R.getNameLoc();
2687
2688 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002689 return ExprError();
2690
John McCall129e2df2009-11-30 22:42:35 +00002691 if (R.empty()) {
2692 // Rederive where we looked up.
2693 DeclContext *DC = (SS.isSet()
2694 ? computeDeclContext(SS, false)
2695 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002696
John McCall129e2df2009-11-30 22:42:35 +00002697 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002698 << MemberName << DC
2699 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002700 return ExprError();
2701 }
2702
John McCallc2233c52010-01-15 08:34:02 +00002703 // Diagnose lookups that find only declarations from a non-base
2704 // type. This is possible for either qualified lookups (which may
2705 // have been qualified with an unrelated type) or implicit member
2706 // expressions (which were found with unqualified lookup and thus
2707 // may have come from an enclosing scope). Note that it's okay for
2708 // lookup to find declarations from a non-base type as long as those
2709 // aren't the ones picked by overload resolution.
2710 if ((SS.isSet() || !BaseExpr ||
2711 (isa<CXXThisExpr>(BaseExpr) &&
2712 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2713 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002714 return ExprError();
2715
2716 // Construct an unresolved result if we in fact got an unresolved
2717 // result.
2718 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002719 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002720 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002721 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002722 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002723
John McCallc373d482010-01-27 01:50:18 +00002724 // Suppress any lookup-related diagnostics; we'll do these when we
2725 // pick a member.
2726 R.suppressDiagnostics();
2727
John McCall129e2df2009-11-30 22:42:35 +00002728 UnresolvedMemberExpr *MemExpr
2729 = UnresolvedMemberExpr::Create(Context, Dependent,
2730 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002731 BaseExpr, BaseExprType,
2732 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002733 Qualifier, SS.getRange(),
2734 MemberName, MemberLoc,
2735 TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00002736 MemExpr->addDecls(R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002737
2738 return Owned(MemExpr);
2739 }
2740
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002741 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00002742 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00002743 NamedDecl *MemberDecl = R.getFoundDecl();
2744
2745 // FIXME: diagnose the presence of template arguments now.
2746
2747 // If the decl being referenced had an error, return an error for this
2748 // sub-expr without emitting another error, in order to avoid cascading
2749 // error cases.
2750 if (MemberDecl->isInvalidDecl())
2751 return ExprError();
2752
John McCallaa81e162009-12-01 22:10:20 +00002753 // Handle the implicit-member-access case.
2754 if (!BaseExpr) {
2755 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00002756 if (!MemberDecl->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002757 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2758
Douglas Gregor828a1972010-01-07 23:12:05 +00002759 SourceLocation Loc = R.getNameLoc();
2760 if (SS.getRange().isValid())
2761 Loc = SS.getRange().getBegin();
2762 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002763 }
2764
John McCall129e2df2009-11-30 22:42:35 +00002765 bool ShouldCheckUse = true;
2766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2767 // Don't diagnose the use of a virtual member function unless it's
2768 // explicitly qualified.
2769 if (MD->isVirtual() && !SS.isSet())
2770 ShouldCheckUse = false;
2771 }
2772
2773 // Check the use of this member.
2774 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2775 Owned(BaseExpr);
2776 return ExprError();
2777 }
2778
2779 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2780 // We may have found a field within an anonymous union or struct
2781 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002782 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2783 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002784 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2785 BaseExpr, OpLoc);
2786
2787 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2788 QualType MemberType = FD->getType();
2789 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2790 MemberType = Ref->getPointeeType();
2791 else {
2792 Qualifiers BaseQuals = BaseType.getQualifiers();
2793 BaseQuals.removeObjCGCAttr();
2794 if (FD->isMutable()) BaseQuals.removeConst();
2795
2796 Qualifiers MemberQuals
2797 = Context.getCanonicalType(MemberType).getQualifiers();
2798
2799 Qualifiers Combined = BaseQuals + MemberQuals;
2800 if (Combined != MemberQuals)
2801 MemberType = Context.getQualifiedType(MemberType, Combined);
2802 }
2803
2804 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002805 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002806 return ExprError();
2807 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002808 FD, FoundDecl, MemberLoc, MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002809 }
2810
2811 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2812 MarkDeclarationReferenced(MemberLoc, Var);
2813 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002814 Var, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002815 Var->getType().getNonReferenceType()));
2816 }
2817
2818 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2819 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2820 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002821 MemberFn, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002822 MemberFn->getType()));
2823 }
2824
2825 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2826 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2827 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002828 Enum, FoundDecl, MemberLoc, Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002829 }
2830
2831 Owned(BaseExpr);
2832
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002833 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00002834 if (isa<TypeDecl>(MemberDecl))
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002835 Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2836 << MemberName << BaseType << int(IsArrow);
2837 else
2838 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2839 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00002840
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002841 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2842 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00002843 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002844 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002845}
2846
2847/// Look up the given member of the given non-type-dependent
2848/// expression. This can return in one of two ways:
2849/// * If it returns a sentinel null-but-valid result, the caller will
2850/// assume that lookup was performed and the results written into
2851/// the provided structure. It will take over from there.
2852/// * Otherwise, the returned expression will be produced in place of
2853/// an ordinary member expression.
2854///
2855/// The ObjCImpDecl bit is a gross hack that will need to be properly
2856/// fixed for ObjC++.
2857Sema::OwningExprResult
2858Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002859 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002860 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002861 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002862 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Steve Naroff3cc4af82007-12-16 21:42:28 +00002864 // Perform default conversions.
2865 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002866
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002867 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002868 assert(!BaseType->isDependentType());
2869
2870 DeclarationName MemberName = R.getLookupName();
2871 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002872
2873 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002874 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002875 // function. Suggest the addition of those parentheses, build the
2876 // call, and continue on.
2877 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2878 if (const FunctionProtoType *Fun
2879 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2880 QualType ResultTy = Fun->getResultType();
2881 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002882 ((!IsArrow && ResultTy->isRecordType()) ||
2883 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002884 ResultTy->getAs<PointerType>()->getPointeeType()
2885 ->isRecordType()))) {
2886 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2887 Diag(Loc, diag::err_member_reference_needs_call)
2888 << QualType(Fun, 0)
Douglas Gregor849b2432010-03-31 17:46:05 +00002889 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002890
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002891 OwningExprResult NewBase
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002892 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002893 MultiExprArg(*this, 0, 0), 0, Loc);
2894 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002895 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002896
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002897 BaseExpr = NewBase.takeAs<Expr>();
2898 DefaultFunctionArrayConversion(BaseExpr);
2899 BaseType = BaseExpr->getType();
2900 }
2901 }
2902 }
2903
David Chisnall0f436562009-08-17 16:35:33 +00002904 // If this is an Objective-C pseudo-builtin and a definition is provided then
2905 // use that.
2906 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002907 if (IsArrow) {
2908 // Handle the following exceptional case PObj->isa.
2909 if (const ObjCObjectPointerType *OPT =
2910 BaseType->getAs<ObjCObjectPointerType>()) {
2911 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2912 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002913 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2914 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002915 }
2916 }
David Chisnall0f436562009-08-17 16:35:33 +00002917 // We have an 'id' type. Rather than fall through, we check if this
2918 // is a reference to 'isa'.
2919 if (BaseType != Context.ObjCIdRedefinitionType) {
2920 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002921 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002922 }
David Chisnall0f436562009-08-17 16:35:33 +00002923 }
John McCall129e2df2009-11-30 22:42:35 +00002924
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002925 // If this is an Objective-C pseudo-builtin and a definition is provided then
2926 // use that.
2927 if (Context.isObjCSelType(BaseType)) {
2928 // We have an 'SEL' type. Rather than fall through, we check if this
2929 // is a reference to 'sel_id'.
2930 if (BaseType != Context.ObjCSelRedefinitionType) {
2931 BaseType = Context.ObjCSelRedefinitionType;
2932 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2933 }
2934 }
John McCall129e2df2009-11-30 22:42:35 +00002935
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002936 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002937
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002938 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002939 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002940 // Also must look for a getter name which uses property syntax.
2941 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2942 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2943 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2944 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2945 ObjCMethodDecl *Getter;
2946 // FIXME: need to also look locally in the implementation.
2947 if ((Getter = IFace->lookupClassMethod(Sel))) {
2948 // Check the use of this method.
2949 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2950 return ExprError();
2951 }
2952 // If we found a getter then this may be a valid dot-reference, we
2953 // will look for the matching setter, in case it is needed.
2954 Selector SetterSel =
2955 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2956 PP.getSelectorTable(), Member);
2957 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2958 if (!Setter) {
2959 // If this reference is in an @implementation, also check for 'private'
2960 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002961 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002962 }
2963 // Look through local category implementations associated with the class.
2964 if (!Setter)
2965 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002966
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002967 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2968 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002969
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002970 if (Getter || Setter) {
2971 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002972
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002973 if (Getter)
2974 PType = Getter->getResultType();
2975 else
2976 // Get the expression type from Setter's incoming parameter.
2977 PType = (*(Setter->param_end() -1))->getType();
2978 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002979 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002980 PType,
2981 Setter, MemberLoc, BaseExpr));
2982 }
2983 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2984 << MemberName << BaseType);
2985 }
2986 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002987
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002988 if (BaseType->isObjCClassType() &&
2989 BaseType != Context.ObjCClassRedefinitionType) {
2990 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002991 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002992 }
Mike Stump1eb44332009-09-09 15:08:12 +00002993
John McCall129e2df2009-11-30 22:42:35 +00002994 if (IsArrow) {
2995 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002996 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002997 else if (BaseType->isObjCObjectPointerType())
2998 ;
John McCall812c1542009-12-07 22:46:59 +00002999 else if (BaseType->isRecordType()) {
3000 // Recover from arrow accesses to records, e.g.:
3001 // struct MyRecord foo;
3002 // foo->bar
3003 // This is actually well-formed in C++ if MyRecord has an
3004 // overloaded operator->, but that should have been dealt with
3005 // by now.
3006 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3007 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003008 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003009 IsArrow = false;
3010 } else {
John McCall129e2df2009-11-30 22:42:35 +00003011 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3012 << BaseType << BaseExpr->getSourceRange();
3013 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003014 }
John McCall812c1542009-12-07 22:46:59 +00003015 } else {
3016 // Recover from dot accesses to pointers, e.g.:
3017 // type *foo;
3018 // foo.bar
3019 // This is actually well-formed in two cases:
3020 // - 'type' is an Objective C type
3021 // - 'bar' is a pseudo-destructor name which happens to refer to
3022 // the appropriate pointer type
3023 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3024 const PointerType *PT = BaseType->getAs<PointerType>();
3025 if (PT && PT->getPointeeType()->isRecordType()) {
3026 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3027 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003028 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003029 BaseType = PT->getPointeeType();
3030 IsArrow = true;
3031 }
3032 }
John McCall129e2df2009-11-30 22:42:35 +00003033 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003034
John McCall129e2df2009-11-30 22:42:35 +00003035 // Handle field access to simple records. This also handles access
3036 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00003037 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003038 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3039 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003040 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003041 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003042 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003043
Chris Lattnera38e6b12008-07-21 04:59:05 +00003044 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3045 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003046 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3047 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00003048 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003049 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00003050 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00003051 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003052 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3053
Steve Naroffc70e8d92009-07-16 00:25:06 +00003054 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
3055 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003056 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003058 if (!IV) {
3059 // Attempt to correct for typos in ivar names.
3060 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3061 LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003062 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003063 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003064 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003065 diag::err_typecheck_member_reference_ivar_suggest)
3066 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregor849b2432010-03-31 17:46:05 +00003067 << FixItHint::CreateReplacement(R.getNameLoc(),
3068 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003069 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003070 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003071 }
3072 }
3073
Steve Naroffc70e8d92009-07-16 00:25:06 +00003074 if (IV) {
3075 // If the decl being referenced had an error, return an error for this
3076 // sub-expr without emitting another error, in order to avoid cascading
3077 // error cases.
3078 if (IV->isInvalidDecl())
3079 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003080
Steve Naroffc70e8d92009-07-16 00:25:06 +00003081 // Check whether we can reference this field.
3082 if (DiagnoseUseOfDecl(IV, MemberLoc))
3083 return ExprError();
3084 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3085 IV->getAccessControl() != ObjCIvarDecl::Package) {
3086 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3087 if (ObjCMethodDecl *MD = getCurMethodDecl())
3088 ClassOfMethodDecl = MD->getClassInterface();
3089 else if (ObjCImpDecl && getCurFunctionDecl()) {
3090 // Case of a c-function declared inside an objc implementation.
3091 // FIXME: For a c-style function nested inside an objc implementation
3092 // class, there is no implementation context available, so we pass
3093 // down the context as argument to this routine. Ideally, this context
3094 // need be passed down in the AST node and somehow calculated from the
3095 // AST for a function decl.
3096 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00003097 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00003098 dyn_cast<ObjCImplementationDecl>(ImplDecl))
3099 ClassOfMethodDecl = IMPD->getClassInterface();
3100 else if (ObjCCategoryImplDecl* CatImplClass =
3101 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3102 ClassOfMethodDecl = CatImplClass->getClassInterface();
3103 }
Mike Stump1eb44332009-09-09 15:08:12 +00003104
3105 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3106 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003107 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003108 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003109 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003110 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3111 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003112 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003113 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003114 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003115
3116 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3117 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003118 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003119 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003120 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003121 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003122 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003123 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003124 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003125 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003126 if (!IsArrow && (BaseType->isObjCIdType() ||
3127 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003128 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003129 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Steve Naroff14108da2009-07-10 23:34:53 +00003131 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003132 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003133 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3134 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3135 // Check the use of this declaration
3136 if (DiagnoseUseOfDecl(PD, MemberLoc))
3137 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Steve Naroff14108da2009-07-10 23:34:53 +00003139 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3140 MemberLoc, BaseExpr));
3141 }
3142 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3143 // Check the use of this method.
3144 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3145 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Douglas Gregor04badcf2010-04-21 00:45:42 +00003147 return Owned(ObjCMessageExpr::Create(Context,
3148 OMD->getResultType().getNonReferenceType(),
3149 OpLoc, BaseExpr, Sel,
3150 OMD, NULL, 0, MemberLoc));
Steve Naroff14108da2009-07-10 23:34:53 +00003151 }
3152 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003153
Steve Naroff14108da2009-07-10 23:34:53 +00003154 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003155 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003156 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00003157
Chris Lattnera38e6b12008-07-21 04:59:05 +00003158 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3159 // pointer to a (potentially qualified) interface type.
Chris Lattner7f816522010-04-11 07:45:24 +00003160 if (!IsArrow)
3161 if (const ObjCObjectPointerType *OPT =
3162 BaseType->getAsObjCInterfacePointerType())
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00003163 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Steve Narofff242b1b2009-07-24 17:54:45 +00003165 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003166 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003167 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003168 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003169 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003170 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003171
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003172 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003173 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003174 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003175 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3176 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003177 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003178 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003179 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003180 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003181
Douglas Gregor214f31a2009-03-27 06:00:30 +00003182 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3183 << BaseType << BaseExpr->getSourceRange();
3184
Douglas Gregor214f31a2009-03-27 06:00:30 +00003185 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003186}
3187
John McCall129e2df2009-11-30 22:42:35 +00003188/// The main callback when the parser finds something like
3189/// expression . [nested-name-specifier] identifier
3190/// expression -> [nested-name-specifier] identifier
3191/// where 'identifier' encompasses a fairly broad spectrum of
3192/// possibilities, including destructor and operator references.
3193///
3194/// \param OpKind either tok::arrow or tok::period
3195/// \param HasTrailingLParen whether the next token is '(', which
3196/// is used to diagnose mis-uses of special members that can
3197/// only be called
3198/// \param ObjCImpDecl the current ObjC @implementation decl;
3199/// this is an ugly hack around the fact that ObjC @implementations
3200/// aren't properly put in the context chain
3201Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3202 SourceLocation OpLoc,
3203 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003204 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003205 UnqualifiedId &Id,
3206 DeclPtrTy ObjCImpDecl,
3207 bool HasTrailingLParen) {
3208 if (SS.isSet() && SS.isInvalid())
3209 return ExprError();
3210
3211 TemplateArgumentListInfo TemplateArgsBuffer;
3212
3213 // Decompose the name into its component parts.
3214 DeclarationName Name;
3215 SourceLocation NameLoc;
3216 const TemplateArgumentListInfo *TemplateArgs;
3217 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3218 Name, NameLoc, TemplateArgs);
3219
3220 bool IsArrow = (OpKind == tok::arrow);
3221
3222 NamedDecl *FirstQualifierInScope
3223 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3224 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3225
3226 // This is a postfix expression, so get rid of ParenListExprs.
3227 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3228
3229 Expr *Base = BaseArg.takeAs<Expr>();
3230 OwningExprResult Result(*this);
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003231 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3232 isDependentScopeSpecifier(SS)) {
John McCallaa81e162009-12-01 22:10:20 +00003233 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003234 IsArrow, OpLoc,
3235 SS, FirstQualifierInScope,
3236 Name, NameLoc,
3237 TemplateArgs);
3238 } else {
3239 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3240 if (TemplateArgs) {
3241 // Re-use the lookup done for the template name.
3242 DecomposeTemplateName(R, Id);
Douglas Gregorc96be1e2010-04-27 18:19:34 +00003243
3244 // Re-derive the naming class.
3245 if (SS.isSet()) {
3246 NestedNameSpecifier *Qualifier
3247 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3248 if (const Type *Ty = Qualifier->getAsType())
3249 if (CXXRecordDecl *NamingClass = Ty->getAsCXXRecordDecl())
3250 R.setNamingClass(NamingClass);
3251 } else {
3252 QualType BaseType = Base->getType();
3253 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3254 BaseType = Ptr->getPointeeType();
3255 if (CXXRecordDecl *NamingClass = BaseType->getAsCXXRecordDecl())
3256 R.setNamingClass(NamingClass);
3257 }
John McCall129e2df2009-11-30 22:42:35 +00003258 } else {
3259 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00003260 SS, ObjCImpDecl);
John McCall129e2df2009-11-30 22:42:35 +00003261
3262 if (Result.isInvalid()) {
3263 Owned(Base);
3264 return ExprError();
3265 }
3266
3267 if (Result.get()) {
3268 // The only way a reference to a destructor can be used is to
3269 // immediately call it, which falls into this case. If the
3270 // next token is not a '(', produce a diagnostic and build the
3271 // call now.
3272 if (!HasTrailingLParen &&
3273 Id.getKind() == UnqualifiedId::IK_DestructorName)
Douglas Gregor77549082010-02-24 21:29:12 +00003274 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall129e2df2009-11-30 22:42:35 +00003275
3276 return move(Result);
3277 }
3278 }
3279
John McCallaa81e162009-12-01 22:10:20 +00003280 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003281 OpLoc, IsArrow, SS, FirstQualifierInScope,
3282 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003283 }
3284
3285 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003286}
3287
Anders Carlsson56c5e332009-08-25 03:49:14 +00003288Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3289 FunctionDecl *FD,
3290 ParmVarDecl *Param) {
3291 if (Param->hasUnparsedDefaultArg()) {
3292 Diag (CallLoc,
3293 diag::err_use_of_default_argument_to_function_declared_later) <<
3294 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003295 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003296 diag::note_default_argument_declared_here);
3297 } else {
3298 if (Param->hasUninstantiatedDefaultArg()) {
3299 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3300
3301 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003302 MultiLevelTemplateArgumentList ArgList
3303 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003304
Mike Stump1eb44332009-09-09 15:08:12 +00003305 InstantiatingTemplate Inst(*this, CallLoc, Param,
3306 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003307 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003308
John McCallce3ff2b2009-08-25 22:02:44 +00003309 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003310 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003311 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Douglas Gregor65222e82009-12-23 18:19:08 +00003313 // Check the expression as an initializer for the parameter.
3314 InitializedEntity Entity
3315 = InitializedEntity::InitializeParameter(Param);
3316 InitializationKind Kind
3317 = InitializationKind::CreateCopy(Param->getLocation(),
3318 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3319 Expr *ResultE = Result.takeAs<Expr>();
3320
3321 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003322 Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor65222e82009-12-23 18:19:08 +00003323 MultiExprArg(*this, (void**)&ResultE, 1));
3324 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003325 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003326
Douglas Gregor65222e82009-12-23 18:19:08 +00003327 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003328 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003329 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Anders Carlsson56c5e332009-08-25 03:49:14 +00003332 // If the default expression creates temporaries, we need to
3333 // push them to the current stack of expression temporaries so they'll
3334 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003335 // FIXME: We should really be rebuilding the default argument with new
3336 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003337 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3338 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003339 }
3340
3341 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003342 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003343}
3344
Douglas Gregor88a35142008-12-22 05:46:06 +00003345/// ConvertArgumentsForCall - Converts the arguments specified in
3346/// Args/NumArgs to the parameter types of the function FDecl with
3347/// function prototype Proto. Call is the call expression itself, and
3348/// Fn is the function expression. For a C++ member function, this
3349/// routine does not attempt to convert the object argument. Returns
3350/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003351bool
3352Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003353 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003354 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003355 Expr **Args, unsigned NumArgs,
3356 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003357 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003358 // assignment, to the types of the corresponding parameter, ...
3359 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003360 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003361
Douglas Gregor88a35142008-12-22 05:46:06 +00003362 // If too few arguments are available (and we don't have default
3363 // arguments for the remaining parameters), don't make the call.
3364 if (NumArgs < NumArgsInProto) {
3365 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3366 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00003367 << Fn->getType()->isBlockPointerType()
3368 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003369 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003370 }
3371
3372 // If too many are passed and not variadic, error on the extras and drop
3373 // them.
3374 if (NumArgs > NumArgsInProto) {
3375 if (!Proto->isVariadic()) {
3376 Diag(Args[NumArgsInProto]->getLocStart(),
3377 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00003378 << Fn->getType()->isBlockPointerType()
3379 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003380 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3381 Args[NumArgs-1]->getLocEnd());
3382 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003383 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003384 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003385 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003386 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003387 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003388 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003389 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3390 if (Fn->getType()->isBlockPointerType())
3391 CallType = VariadicBlock; // Block
3392 else if (isa<MemberExpr>(Fn))
3393 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003394 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003395 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003396 if (Invalid)
3397 return true;
3398 unsigned TotalNumArgs = AllArgs.size();
3399 for (unsigned i = 0; i < TotalNumArgs; ++i)
3400 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003401
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003402 return false;
3403}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003404
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003405bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3406 FunctionDecl *FDecl,
3407 const FunctionProtoType *Proto,
3408 unsigned FirstProtoArg,
3409 Expr **Args, unsigned NumArgs,
3410 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003411 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003412 unsigned NumArgsInProto = Proto->getNumArgs();
3413 unsigned NumArgsToCheck = NumArgs;
3414 bool Invalid = false;
3415 if (NumArgs != NumArgsInProto)
3416 // Use default arguments for missing arguments
3417 NumArgsToCheck = NumArgsInProto;
3418 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003420 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003421 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003422
Douglas Gregor88a35142008-12-22 05:46:06 +00003423 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003424 if (ArgIx < NumArgs) {
3425 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003426
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003427 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3428 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003429 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003430 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003431 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003432
Douglas Gregora188ff22009-12-22 16:09:06 +00003433 // Pass the argument
3434 ParmVarDecl *Param = 0;
3435 if (FDecl && i < FDecl->getNumParams())
3436 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003437
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003438
Douglas Gregora188ff22009-12-22 16:09:06 +00003439 InitializedEntity Entity =
3440 Param? InitializedEntity::InitializeParameter(Param)
3441 : InitializedEntity::InitializeParameter(ProtoArgType);
3442 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3443 SourceLocation(),
3444 Owned(Arg));
3445 if (ArgE.isInvalid())
3446 return true;
3447
3448 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003449 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003450 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003451
Mike Stump1eb44332009-09-09 15:08:12 +00003452 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003453 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003454 if (ArgExpr.isInvalid())
3455 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003456
Anders Carlsson56c5e332009-08-25 03:49:14 +00003457 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003458 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003459 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003460 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003461
Douglas Gregor88a35142008-12-22 05:46:06 +00003462 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003463 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003464 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003465 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003466 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003467 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003468 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003469 }
3470 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003471 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003472}
3473
Steve Narofff69936d2007-09-16 03:34:24 +00003474/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003475/// This provides the location of the left/right parens and a list of comma
3476/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003477Action::OwningExprResult
3478Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3479 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003480 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003481 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003482
3483 // Since this might be a postfix expression, get rid of ParenListExprs.
3484 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003486 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003487 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003488 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Douglas Gregor88a35142008-12-22 05:46:06 +00003490 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003491 // If this is a pseudo-destructor expression, build the call immediately.
3492 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3493 if (NumArgs > 0) {
3494 // Pseudo-destructor calls should not have any arguments.
3495 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003496 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003497 SourceRange(Args[0]->getLocStart(),
3498 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Douglas Gregora71d8192009-09-04 17:36:40 +00003500 for (unsigned I = 0; I != NumArgs; ++I)
3501 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Douglas Gregora71d8192009-09-04 17:36:40 +00003503 NumArgs = 0;
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Douglas Gregora71d8192009-09-04 17:36:40 +00003506 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3507 RParenLoc));
3508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor17330012009-02-04 15:01:18 +00003510 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003511 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003512 // FIXME: Will need to cache the results of name lookup (including ADL) in
3513 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003514 bool Dependent = false;
3515 if (Fn->isTypeDependent())
3516 Dependent = true;
3517 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3518 Dependent = true;
3519
3520 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003521 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003522 Context.DependentTy, RParenLoc));
3523
3524 // Determine whether this is a call to an object (C++ [over.call.object]).
3525 if (Fn->getType()->isRecordType())
3526 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3527 CommaLocs, RParenLoc));
3528
John McCall129e2df2009-11-30 22:42:35 +00003529 Expr *NakedFn = Fn->IgnoreParens();
3530
3531 // Determine whether this is a call to an unresolved member function.
3532 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3533 // If lookup was unresolved but not dependent (i.e. didn't find
3534 // an unresolved using declaration), it has to be an overloaded
3535 // function set, which means it must contain either multiple
3536 // declarations (all methods or method templates) or a single
3537 // method template.
3538 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00003539 isa<FunctionTemplateDecl>(
3540 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003541 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003542
John McCallaa81e162009-12-01 22:10:20 +00003543 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3544 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003545 }
3546
Douglas Gregorfa047642009-02-04 00:32:51 +00003547 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003548 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003549 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003550 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003551 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3552 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003553 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003554
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003555 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003556 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003557 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3558 BO->getOpcode() == BinaryOperator::PtrMemI) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003559 if (const FunctionProtoType *FPT =
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003560 dyn_cast<FunctionProtoType>(BO->getType())) {
3561 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003562
3563 ExprOwningPtr<CXXMemberCallExpr>
3564 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003565 NumArgs, ResultTy,
3566 RParenLoc));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003567
3568 if (CheckCallReturnType(FPT->getResultType(),
3569 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003570 TheCall.get(), 0))
3571 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003572
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003573 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003574 RParenLoc))
3575 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003576
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003577 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3578 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003579 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003580 diag::err_typecheck_call_not_function)
3581 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003582 }
3583 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003584 }
3585
Douglas Gregorfa047642009-02-04 00:32:51 +00003586 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003587 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003588 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003589
Eli Friedmanefa42f72009-12-26 03:35:45 +00003590 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003591 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3592 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00003593 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00003594 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003595 }
Chris Lattner04421082008-04-08 04:40:51 +00003596
John McCall3b4294e2009-12-16 12:17:52 +00003597 NamedDecl *NDecl = 0;
3598 if (isa<DeclRefExpr>(NakedFn))
3599 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3600
John McCallaa81e162009-12-01 22:10:20 +00003601 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3602}
3603
John McCall3b4294e2009-12-16 12:17:52 +00003604/// BuildResolvedCallExpr - Build a call to a resolved expression,
3605/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003606/// unary-convert to an expression of function-pointer or
3607/// block-pointer type.
3608///
3609/// \param NDecl the declaration being called, if available
3610Sema::OwningExprResult
3611Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3612 SourceLocation LParenLoc,
3613 Expr **Args, unsigned NumArgs,
3614 SourceLocation RParenLoc) {
3615 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3616
Chris Lattner04421082008-04-08 04:40:51 +00003617 // Promote the function operand.
3618 UsualUnaryConversions(Fn);
3619
Chris Lattner925e60d2007-12-28 05:29:59 +00003620 // Make the call expr early, before semantic checks. This guarantees cleanup
3621 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003622 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3623 Args, NumArgs,
3624 Context.BoolTy,
3625 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003626
Steve Naroffdd972f22008-09-05 22:11:13 +00003627 const FunctionType *FuncT;
3628 if (!Fn->getType()->isBlockPointerType()) {
3629 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3630 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003631 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003632 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003633 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3634 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003635 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003636 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003637 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003638 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003639 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003640 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003641 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3642 << Fn->getType() << Fn->getSourceRange());
3643
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003644 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003645 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003646 Fn->getSourceRange().getBegin(), TheCall.get(),
3647 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003648 return ExprError();
3649
Chris Lattner925e60d2007-12-28 05:29:59 +00003650 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003651 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003652
Douglas Gregor72564e72009-02-26 23:50:07 +00003653 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003654 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003655 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003656 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003657 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003658 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003659
Douglas Gregor74734d52009-04-02 15:37:10 +00003660 if (FDecl) {
3661 // Check if we have too few/too many template arguments, based
3662 // on our knowledge of the function definition.
3663 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003664 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003665 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003666 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003667 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3668 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3669 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3670 }
3671 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003672 }
3673
Steve Naroffb291ab62007-08-28 23:30:39 +00003674 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003675 for (unsigned i = 0; i != NumArgs; i++) {
3676 Expr *Arg = Args[i];
3677 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003678 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3679 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003680 PDiag(diag::err_call_incomplete_argument)
3681 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003682 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003683 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003685 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003686
Douglas Gregor88a35142008-12-22 05:46:06 +00003687 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3688 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003689 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3690 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003691
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003692 // Check for sentinels
3693 if (NDecl)
3694 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Chris Lattner59907c42007-08-10 20:18:51 +00003696 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003697 if (FDecl) {
3698 if (CheckFunctionCall(FDecl, TheCall.get()))
3699 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003701 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003702 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3703 } else if (NDecl) {
3704 if (CheckBlockCall(NDecl, TheCall.get()))
3705 return ExprError();
3706 }
Chris Lattner59907c42007-08-10 20:18:51 +00003707
Anders Carlssonec74c592009-08-16 03:06:32 +00003708 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003709}
3710
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003711Action::OwningExprResult
3712Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3713 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003714 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003715 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003716 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003717
3718 TypeSourceInfo *TInfo;
3719 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3720 if (!TInfo)
3721 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3722
3723 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3724}
3725
3726Action::OwningExprResult
3727Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3728 SourceLocation RParenLoc, ExprArg InitExpr) {
3729 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003730 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003731
Eli Friedman6223c222008-05-20 05:22:08 +00003732 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003733 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003734 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3735 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003736 } else if (!literalType->isDependentType() &&
3737 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003738 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003739 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003740 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003741 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003742
Douglas Gregor99a2e602009-12-16 01:38:02 +00003743 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003744 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003745 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003746 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003747 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003748 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3749 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3750 MultiExprArg(*this, (void**)&literalExpr, 1),
3751 &literalType);
3752 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003753 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003754 InitExpr.release();
3755 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003756
Chris Lattner371f2582008-12-04 23:50:19 +00003757 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003758 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003759 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003760 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003761 }
Eli Friedman08544622009-12-22 02:35:53 +00003762
3763 Result.release();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003764
John McCall1d7d8d62010-01-19 22:33:45 +00003765 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003766 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003767}
3768
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003769Action::OwningExprResult
3770Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003771 SourceLocation RBraceLoc) {
3772 unsigned NumInit = initlist.size();
3773 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003774
Steve Naroff08d92e42007-09-15 18:49:24 +00003775 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003776 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003777
Ted Kremenek709210f2010-04-13 23:39:13 +00003778 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3779 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003780 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003781 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003782}
3783
Anders Carlsson82debc72009-10-18 18:12:03 +00003784static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3785 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003786 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003787 return CastExpr::CK_NoOp;
3788
3789 if (SrcTy->hasPointerRepresentation()) {
3790 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003791 return DestTy->isObjCObjectPointerType() ?
3792 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003793 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003794 if (DestTy->isIntegerType())
3795 return CastExpr::CK_PointerToIntegral;
3796 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003797
Anders Carlsson82debc72009-10-18 18:12:03 +00003798 if (SrcTy->isIntegerType()) {
3799 if (DestTy->isIntegerType())
3800 return CastExpr::CK_IntegralCast;
3801 if (DestTy->hasPointerRepresentation())
3802 return CastExpr::CK_IntegralToPointer;
3803 if (DestTy->isRealFloatingType())
3804 return CastExpr::CK_IntegralToFloating;
3805 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003806
Anders Carlsson82debc72009-10-18 18:12:03 +00003807 if (SrcTy->isRealFloatingType()) {
3808 if (DestTy->isRealFloatingType())
3809 return CastExpr::CK_FloatingCast;
3810 if (DestTy->isIntegerType())
3811 return CastExpr::CK_FloatingToIntegral;
3812 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003813
Anders Carlsson82debc72009-10-18 18:12:03 +00003814 // FIXME: Assert here.
3815 // assert(false && "Unhandled cast combination!");
3816 return CastExpr::CK_Unknown;
3817}
3818
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003819/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003820bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003821 CastExpr::CastKind& Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003822 CXXBaseSpecifierArray &BasePath,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003823 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003824 if (getLangOptions().CPlusPlus)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003825 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3826 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003827
Douglas Gregora873dfc2010-02-03 00:27:59 +00003828 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003829
3830 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3831 // type needs to be scalar.
3832 if (castType->isVoidType()) {
3833 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003834 Kind = CastExpr::CK_ToVoid;
3835 return false;
3836 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003837
Anders Carlssonebeaf202009-10-16 02:35:04 +00003838 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003839 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003840 (castType->isStructureType() || castType->isUnionType())) {
3841 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003842 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003843 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3844 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003845 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003846 return false;
3847 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003848
Anders Carlssonc3516322009-10-16 02:48:28 +00003849 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003850 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003852 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003853 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003854 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003855 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003856 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003857 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3858 << castExpr->getSourceRange();
3859 break;
3860 }
3861 }
3862 if (Field == FieldEnd)
3863 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3864 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003865 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003866 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003867 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003868
Anders Carlssonc3516322009-10-16 02:48:28 +00003869 // Reject any other conversions to non-scalar types.
3870 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3871 << castType << castExpr->getSourceRange();
3872 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003873
3874 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003875 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003876 return Diag(castExpr->getLocStart(),
3877 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003878 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003879 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003880
3881 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003882 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003883
Anders Carlssonc3516322009-10-16 02:48:28 +00003884 if (castType->isVectorType())
3885 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3886 if (castExpr->getType()->isVectorType())
3887 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3888
Anders Carlsson16a89042009-10-16 05:23:41 +00003889 if (isa<ObjCSelectorExpr>(castExpr))
3890 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003891
Anders Carlssonc3516322009-10-16 02:48:28 +00003892 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003893 QualType castExprType = castExpr->getType();
3894 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3895 return Diag(castExpr->getLocStart(),
3896 diag::err_cast_pointer_from_non_pointer_int)
3897 << castExprType << castExpr->getSourceRange();
3898 } else if (!castExpr->getType()->isArithmeticType()) {
3899 if (!castType->isIntegralType() && castType->isArithmeticType())
3900 return Diag(castExpr->getLocStart(),
3901 diag::err_cast_pointer_to_non_pointer_int)
3902 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003903 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003904
3905 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003906 return false;
3907}
3908
Anders Carlssonc3516322009-10-16 02:48:28 +00003909bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3910 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003911 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003912
Anders Carlssona64db8f2007-11-27 05:51:55 +00003913 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003914 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003915 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003916 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003917 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003918 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003919 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003920 } else
3921 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003922 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003923 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003924
Anders Carlssonc3516322009-10-16 02:48:28 +00003925 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003926 return false;
3927}
3928
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003929bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00003930 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003931 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003932
Anders Carlsson16a89042009-10-16 05:23:41 +00003933 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003934
Nate Begeman9b10da62009-06-27 22:05:55 +00003935 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3936 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003937 if (SrcTy->isVectorType()) {
3938 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3939 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3940 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003941 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003942 return false;
3943 }
3944
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003945 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003946 // conversion will take place first from scalar to elt type, and then
3947 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003948 if (SrcTy->isPointerType())
3949 return Diag(R.getBegin(),
3950 diag::err_invalid_conversion_between_vector_and_scalar)
3951 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003952
3953 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3954 ImpCastExprToType(CastExpr, DestElemTy,
3955 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003956
Anders Carlsson16a89042009-10-16 05:23:41 +00003957 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003958 return false;
3959}
3960
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003961Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003962Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003963 SourceLocation RParenLoc, ExprArg Op) {
3964 assert((Ty != 0) && (Op.get() != 0) &&
3965 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003966
John McCall9d125032010-01-15 18:39:57 +00003967 TypeSourceInfo *castTInfo;
3968 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3969 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00003970 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Nate Begeman2ef13e52009-08-10 23:49:36 +00003972 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00003973 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003974 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00003975 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3976 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00003977
3978 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3979}
3980
3981Action::OwningExprResult
3982Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3983 SourceLocation RParenLoc, ExprArg Op) {
3984 Expr *castExpr = static_cast<Expr*>(Op.get());
3985
John McCallb042fdf2010-01-15 18:56:44 +00003986 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +00003987 CXXBaseSpecifierArray BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00003988 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003989 Kind, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003990 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003991
Douglas Gregord6e44a32010-04-16 22:09:46 +00003992 Op.release();
John McCallb042fdf2010-01-15 18:56:44 +00003993 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +00003994 Kind, castExpr, BasePath, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003995 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003996}
3997
Nate Begeman2ef13e52009-08-10 23:49:36 +00003998/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3999/// of comma binary operators.
4000Action::OwningExprResult
4001Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4002 Expr *expr = EA.takeAs<Expr>();
4003 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4004 if (!E)
4005 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Nate Begeman2ef13e52009-08-10 23:49:36 +00004007 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Nate Begeman2ef13e52009-08-10 23:49:36 +00004009 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4010 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4011 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Nate Begeman2ef13e52009-08-10 23:49:36 +00004013 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4014}
4015
4016Action::OwningExprResult
4017Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4018 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00004019 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004020 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00004021 QualType Ty = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004022
4023 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00004024 // then handle it as such.
4025 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4026 if (PE->getNumExprs() == 0) {
4027 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4028 return ExprError();
4029 }
4030
4031 llvm::SmallVector<Expr *, 8> initExprs;
4032 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4033 initExprs.push_back(PE->getExpr(i));
4034
4035 // FIXME: This means that pretty-printing the final AST will produce curly
4036 // braces instead of the original commas.
4037 Op.release();
Ted Kremenek709210f2010-04-13 23:39:13 +00004038 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4039 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004040 initExprs.size(), RParenLoc);
4041 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004042 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004043 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004044 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004045 // sequence of BinOp comma operators.
4046 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004047 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004048 }
4049}
4050
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004051Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004052 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004053 MultiExprArg Val,
4054 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004055 unsigned nexprs = Val.size();
4056 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004057 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4058 Expr *expr;
4059 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4060 expr = new (Context) ParenExpr(L, R, exprs[0]);
4061 else
4062 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004063 return Owned(expr);
4064}
4065
Sebastian Redl28507842009-02-26 14:39:58 +00004066/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4067/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004068/// C99 6.5.15
4069QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4070 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004071 // C++ is sufficiently different to merit its own checker.
4072 if (getLangOptions().CPlusPlus)
4073 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4074
John McCalld1b47bf2010-03-11 19:43:18 +00004075 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00004076
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004077 UsualUnaryConversions(Cond);
4078 UsualUnaryConversions(LHS);
4079 UsualUnaryConversions(RHS);
4080 QualType CondTy = Cond->getType();
4081 QualType LHSTy = LHS->getType();
4082 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004083
Reid Spencer5f016e22007-07-11 17:01:13 +00004084 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004085 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4086 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4087 << CondTy;
4088 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004089 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004090
Chris Lattner70d67a92008-01-06 22:42:25 +00004091 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004092 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4093 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004094
Chris Lattner70d67a92008-01-06 22:42:25 +00004095 // If both operands have arithmetic type, do the usual arithmetic conversions
4096 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004097 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4098 UsualArithmeticConversions(LHS, RHS);
4099 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004100 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004101
Chris Lattner70d67a92008-01-06 22:42:25 +00004102 // If both operands are the same structure or union type, the result is that
4103 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004104 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4105 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004106 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004107 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004108 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004109 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004110 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004111 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004112
Chris Lattner70d67a92008-01-06 22:42:25 +00004113 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004114 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004115 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4116 if (!LHSTy->isVoidType())
4117 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4118 << RHS->getSourceRange();
4119 if (!RHSTy->isVoidType())
4120 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4121 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004122 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4123 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004124 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004125 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004126 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4127 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004128 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004129 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004130 // promote the null to a pointer.
4131 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004132 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004133 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004134 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004135 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004136 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004137 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004138 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004139
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004140 // All objective-c pointer type analysis is done here.
4141 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4142 QuestionLoc);
4143 if (!compositeType.isNull())
4144 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004145
4146
Steve Naroff7154a772009-07-01 14:36:47 +00004147 // Handle block pointer types.
4148 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4149 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4150 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4151 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004152 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4153 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004154 return destType;
4155 }
4156 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004157 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004158 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004159 }
Steve Naroff7154a772009-07-01 14:36:47 +00004160 // We have 2 block pointer types.
4161 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4162 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004163 return LHSTy;
4164 }
Steve Naroff7154a772009-07-01 14:36:47 +00004165 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004166 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4167 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004168
Steve Naroff7154a772009-07-01 14:36:47 +00004169 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4170 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004171 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004172 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004173 // In this situation, we assume void* type. No especially good
4174 // reason, but this is what gcc does, and we do have to pick
4175 // to get a consistent AST.
4176 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004177 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4178 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004179 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004180 }
Steve Naroff7154a772009-07-01 14:36:47 +00004181 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004182 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4183 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004184 return LHSTy;
4185 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004186
Steve Naroff7154a772009-07-01 14:36:47 +00004187 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4188 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4189 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004190 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4191 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004192
4193 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4194 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4195 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004196 QualType destPointee
4197 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004198 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004199 // Add qualifiers if necessary.
4200 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4201 // Promote to void*.
4202 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004203 return destType;
4204 }
4205 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004206 QualType destPointee
4207 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004208 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004209 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004210 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004211 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004212 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004213 return destType;
4214 }
4215
4216 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4217 // Two identical pointer types are always compatible.
4218 return LHSTy;
4219 }
4220 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4221 rhptee.getUnqualifiedType())) {
4222 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4223 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4224 // In this situation, we assume void* type. No especially good
4225 // reason, but this is what gcc does, and we do have to pick
4226 // to get a consistent AST.
4227 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004228 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4229 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004230 return incompatTy;
4231 }
4232 // The pointer types are compatible.
4233 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4234 // differently qualified versions of compatible types, the result type is
4235 // a pointer to an appropriately qualified version of the *composite*
4236 // type.
4237 // FIXME: Need to calculate the composite type.
4238 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004239 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4240 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004241 return LHSTy;
4242 }
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Steve Naroff7154a772009-07-01 14:36:47 +00004244 // GCC compatibility: soften pointer/integer mismatch.
4245 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4246 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4247 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004248 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004249 return RHSTy;
4250 }
4251 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4252 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4253 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004254 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004255 return LHSTy;
4256 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004257
Chris Lattner70d67a92008-01-06 22:42:25 +00004258 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004259 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4260 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004261 return QualType();
4262}
4263
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004264/// FindCompositeObjCPointerType - Helper method to find composite type of
4265/// two objective-c pointer types of the two input expressions.
4266QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4267 SourceLocation QuestionLoc) {
4268 QualType LHSTy = LHS->getType();
4269 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004270
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004271 // Handle things like Class and struct objc_class*. Here we case the result
4272 // to the pseudo-builtin, because that will be implicitly cast back to the
4273 // redefinition type if an attempt is made to access its fields.
4274 if (LHSTy->isObjCClassType() &&
4275 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4276 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4277 return LHSTy;
4278 }
4279 if (RHSTy->isObjCClassType() &&
4280 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4281 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4282 return RHSTy;
4283 }
4284 // And the same for struct objc_object* / id
4285 if (LHSTy->isObjCIdType() &&
4286 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4287 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4288 return LHSTy;
4289 }
4290 if (RHSTy->isObjCIdType() &&
4291 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4292 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4293 return RHSTy;
4294 }
4295 // And the same for struct objc_selector* / SEL
4296 if (Context.isObjCSelType(LHSTy) &&
4297 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4298 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4299 return LHSTy;
4300 }
4301 if (Context.isObjCSelType(RHSTy) &&
4302 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4303 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4304 return RHSTy;
4305 }
4306 // Check constraints for Objective-C object pointers types.
4307 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004308
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004309 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4310 // Two identical object pointer types are always compatible.
4311 return LHSTy;
4312 }
4313 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4314 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4315 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004316
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004317 // If both operands are interfaces and either operand can be
4318 // assigned to the other, use that type as the composite
4319 // type. This allows
4320 // xxx ? (A*) a : (B*) b
4321 // where B is a subclass of A.
4322 //
4323 // Additionally, as for assignment, if either type is 'id'
4324 // allow silent coercion. Finally, if the types are
4325 // incompatible then make sure to use 'id' as the composite
4326 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004327
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004328 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4329 // It could return the composite type.
4330 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4331 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4332 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4333 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4334 } else if ((LHSTy->isObjCQualifiedIdType() ||
4335 RHSTy->isObjCQualifiedIdType()) &&
4336 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4337 // Need to handle "id<xx>" explicitly.
4338 // GCC allows qualified id and any Objective-C type to devolve to
4339 // id. Currently localizing to here until clear this should be
4340 // part of ObjCQualifiedIdTypesAreCompatible.
4341 compositeType = Context.getObjCIdType();
4342 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4343 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004344 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004345 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4346 ;
4347 else {
4348 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4349 << LHSTy << RHSTy
4350 << LHS->getSourceRange() << RHS->getSourceRange();
4351 QualType incompatTy = Context.getObjCIdType();
4352 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4353 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4354 return incompatTy;
4355 }
4356 // The object pointer types are compatible.
4357 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4358 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4359 return compositeType;
4360 }
4361 // Check Objective-C object pointer types and 'void *'
4362 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4363 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4364 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4365 QualType destPointee
4366 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4367 QualType destType = Context.getPointerType(destPointee);
4368 // Add qualifiers if necessary.
4369 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4370 // Promote to void*.
4371 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4372 return destType;
4373 }
4374 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4375 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4376 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4377 QualType destPointee
4378 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4379 QualType destType = Context.getPointerType(destPointee);
4380 // Add qualifiers if necessary.
4381 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4382 // Promote to void*.
4383 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4384 return destType;
4385 }
4386 return QualType();
4387}
4388
Steve Narofff69936d2007-09-16 03:34:24 +00004389/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004390/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004391Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4392 SourceLocation ColonLoc,
4393 ExprArg Cond, ExprArg LHS,
4394 ExprArg RHS) {
4395 Expr *CondExpr = (Expr *) Cond.get();
4396 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004397
4398 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4399 // was the condition.
4400 bool isLHSNull = LHSExpr == 0;
4401 if (isLHSNull)
4402 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004403
4404 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004405 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004406 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004407 return ExprError();
4408
4409 Cond.release();
4410 LHS.release();
4411 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004412 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004413 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004414 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004415}
4416
Reid Spencer5f016e22007-07-11 17:01:13 +00004417// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004418// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004419// routine is it effectively iqnores the qualifiers on the top level pointee.
4420// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4421// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004422Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004423Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4424 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004425
David Chisnall0f436562009-08-17 16:35:33 +00004426 if ((lhsType->isObjCClassType() &&
4427 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4428 (rhsType->isObjCClassType() &&
4429 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4430 return Compatible;
4431 }
4432
Reid Spencer5f016e22007-07-11 17:01:13 +00004433 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004434 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4435 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436
Reid Spencer5f016e22007-07-11 17:01:13 +00004437 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004438 lhptee = Context.getCanonicalType(lhptee);
4439 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004440
Chris Lattner5cf216b2008-01-04 18:04:52 +00004441 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004442
4443 // C99 6.5.16.1p1: This following citation is common to constraints
4444 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4445 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004446 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004447 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004448 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004449
Mike Stumpeed9cac2009-02-19 03:04:26 +00004450 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4451 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004452 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004453 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004454 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004455 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004456
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004457 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004458 assert(rhptee->isFunctionType());
4459 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004460 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004461
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004462 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004463 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004464 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004465
4466 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004467 assert(lhptee->isFunctionType());
4468 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004469 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004470 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004471 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004472 lhptee = lhptee.getUnqualifiedType();
4473 rhptee = rhptee.getUnqualifiedType();
4474 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4475 // Check if the pointee types are compatible ignoring the sign.
4476 // We explicitly check for char so that we catch "char" vs
4477 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004478 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004479 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004480 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004481 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004482
Chris Lattner6a2b9262009-10-17 20:33:28 +00004483 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004484 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004485 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004486 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004487
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004488 if (lhptee == rhptee) {
4489 // Types are compatible ignoring the sign. Qualifier incompatibility
4490 // takes priority over sign incompatibility because the sign
4491 // warning can be disabled.
4492 if (ConvTy != Compatible)
4493 return ConvTy;
4494 return IncompatiblePointerSign;
4495 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004496
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004497 // If we are a multi-level pointer, it's possible that our issue is simply
4498 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4499 // the eventual target type is the same and the pointers have the same
4500 // level of indirection, this must be the issue.
4501 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4502 do {
4503 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4504 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004505
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004506 lhptee = Context.getCanonicalType(lhptee);
4507 rhptee = Context.getCanonicalType(rhptee);
4508 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004509
Douglas Gregora4923eb2009-11-16 21:35:15 +00004510 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004511 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004512 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004513
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004514 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004515 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004516 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004517 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004518}
4519
Steve Naroff1c7d0672008-09-04 15:10:53 +00004520/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4521/// block pointer types are compatible or whether a block and normal pointer
4522/// are compatible. It is more restrict than comparing two function pointer
4523// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004524Sema::AssignConvertType
4525Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004526 QualType rhsType) {
4527 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004528
Steve Naroff1c7d0672008-09-04 15:10:53 +00004529 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004530 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4531 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004532
Steve Naroff1c7d0672008-09-04 15:10:53 +00004533 // make sure we operate on the canonical type
4534 lhptee = Context.getCanonicalType(lhptee);
4535 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004536
Steve Naroff1c7d0672008-09-04 15:10:53 +00004537 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004538
Steve Naroff1c7d0672008-09-04 15:10:53 +00004539 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004540 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004541 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004542
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004543 if (!getLangOptions().CPlusPlus) {
4544 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4545 return IncompatibleBlockPointer;
4546 }
4547 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004548 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004549 return ConvTy;
4550}
4551
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004552/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4553/// for assignment compatibility.
4554Sema::AssignConvertType
4555Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004556 if (lhsType->isObjCBuiltinType()) {
4557 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004558 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4559 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004560 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004561 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004562 }
4563 if (rhsType->isObjCBuiltinType()) {
4564 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004565 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4566 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004567 return IncompatiblePointer;
4568 return Compatible;
4569 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004570 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004571 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004572 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004573 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4574 // make sure we operate on the canonical type
4575 lhptee = Context.getCanonicalType(lhptee);
4576 rhptee = Context.getCanonicalType(rhptee);
4577 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4578 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004579
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004580 if (Context.typesAreCompatible(lhsType, rhsType))
4581 return Compatible;
4582 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4583 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004584 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004585}
4586
Mike Stumpeed9cac2009-02-19 03:04:26 +00004587/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4588/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004589/// pointers. Here are some objectionable examples that GCC considers warnings:
4590///
4591/// int a, *pint;
4592/// short *pshort;
4593/// struct foo *pfoo;
4594///
4595/// pint = pshort; // warning: assignment from incompatible pointer type
4596/// a = pint; // warning: assignment makes integer from pointer without a cast
4597/// pint = a; // warning: assignment makes pointer from integer without a cast
4598/// pint = pfoo; // warning: assignment from incompatible pointer type
4599///
4600/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004601/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004602///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004603Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004604Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004605 // Get canonical types. We're not formatting these types, just comparing
4606 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004607 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4608 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004609
4610 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004611 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004612
David Chisnall0f436562009-08-17 16:35:33 +00004613 if ((lhsType->isObjCClassType() &&
4614 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4615 (rhsType->isObjCClassType() &&
4616 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4617 return Compatible;
4618 }
4619
Douglas Gregor9d293df2008-10-28 00:22:11 +00004620 // If the left-hand side is a reference type, then we are in a
4621 // (rare!) case where we've allowed the use of references in C,
4622 // e.g., as a parameter type in a built-in function. In this case,
4623 // just make sure that the type referenced is compatible with the
4624 // right-hand side type. The caller is responsible for adjusting
4625 // lhsType so that the resulting expression does not have reference
4626 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004627 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004628 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004629 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004630 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004631 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004632 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4633 // to the same ExtVector type.
4634 if (lhsType->isExtVectorType()) {
4635 if (rhsType->isExtVectorType())
4636 return lhsType == rhsType ? Compatible : Incompatible;
4637 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4638 return Compatible;
4639 }
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Nate Begemanbe2341d2008-07-14 18:02:46 +00004641 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004642 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004643 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004644 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004645 if (getLangOptions().LaxVectorConversions &&
4646 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004647 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004648 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004649 }
4650 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004651 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004652
Chris Lattnere8b3e962008-01-04 23:32:24 +00004653 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004654 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004655
Chris Lattner78eca282008-04-07 06:49:41 +00004656 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004657 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004658 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004659
Chris Lattner78eca282008-04-07 06:49:41 +00004660 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004661 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004662
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004663 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004664 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004665 if (lhsType->isVoidPointerType()) // an exception to the rule.
4666 return Compatible;
4667 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004668 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004669 if (rhsType->getAs<BlockPointerType>()) {
4670 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004671 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004672
4673 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004674 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004675 return Compatible;
4676 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004677 return Incompatible;
4678 }
4679
4680 if (isa<BlockPointerType>(lhsType)) {
4681 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004682 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004683
Steve Naroffb4406862008-09-29 18:10:17 +00004684 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004685 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004686 return Compatible;
4687
Steve Naroff1c7d0672008-09-04 15:10:53 +00004688 if (rhsType->isBlockPointerType())
4689 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004690
Ted Kremenek6217b802009-07-29 21:53:49 +00004691 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004692 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004693 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004694 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004695 return Incompatible;
4696 }
4697
Steve Naroff14108da2009-07-10 23:34:53 +00004698 if (isa<ObjCObjectPointerType>(lhsType)) {
4699 if (rhsType->isIntegerType())
4700 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004702 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004703 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004704 if (rhsType->isVoidPointerType()) // an exception to the rule.
4705 return Compatible;
4706 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004707 }
4708 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004709 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004710 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004711 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004712 if (RHSPT->getPointeeType()->isVoidType())
4713 return Compatible;
4714 }
4715 // Treat block pointers as objects.
4716 if (rhsType->isBlockPointerType())
4717 return Compatible;
4718 return Incompatible;
4719 }
Chris Lattner78eca282008-04-07 06:49:41 +00004720 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004721 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004722 if (lhsType == Context.BoolTy)
4723 return Compatible;
4724
4725 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004726 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004727
Mike Stumpeed9cac2009-02-19 03:04:26 +00004728 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004729 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004730
4731 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004732 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004733 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004734 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004735 }
Steve Naroff14108da2009-07-10 23:34:53 +00004736 if (isa<ObjCObjectPointerType>(rhsType)) {
4737 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4738 if (lhsType == Context.BoolTy)
4739 return Compatible;
4740
4741 if (lhsType->isIntegerType())
4742 return PointerToInt;
4743
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004744 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004745 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004746 if (lhsType->isVoidPointerType()) // an exception to the rule.
4747 return Compatible;
4748 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004749 }
4750 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004751 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004752 return Compatible;
4753 return Incompatible;
4754 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004755
Chris Lattnerfc144e22008-01-04 23:18:45 +00004756 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004757 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004758 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004759 }
4760 return Incompatible;
4761}
4762
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004763/// \brief Constructs a transparent union from an expression that is
4764/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004765static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004766 QualType UnionType, FieldDecl *Field) {
4767 // Build an initializer list that designates the appropriate member
4768 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00004769 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00004770 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004771 SourceLocation());
4772 Initializer->setType(UnionType);
4773 Initializer->setInitializedFieldInUnion(Field);
4774
4775 // Build a compound literal constructing a value of the transparent
4776 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004777 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004778 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004779 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004780}
4781
4782Sema::AssignConvertType
4783Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4784 QualType FromType = rExpr->getType();
4785
Mike Stump1eb44332009-09-09 15:08:12 +00004786 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004787 // transparent_union GCC extension.
4788 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004789 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004790 return Incompatible;
4791
4792 // The field to initialize within the transparent union.
4793 RecordDecl *UD = UT->getDecl();
4794 FieldDecl *InitField = 0;
4795 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004796 for (RecordDecl::field_iterator it = UD->field_begin(),
4797 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004798 it != itend; ++it) {
4799 if (it->getType()->isPointerType()) {
4800 // If the transparent union contains a pointer type, we allow:
4801 // 1) void pointer
4802 // 2) null pointer constant
4803 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004804 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004805 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004806 InitField = *it;
4807 break;
4808 }
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004810 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004811 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004812 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004813 InitField = *it;
4814 break;
4815 }
4816 }
4817
4818 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4819 == Compatible) {
4820 InitField = *it;
4821 break;
4822 }
4823 }
4824
4825 if (!InitField)
4826 return Incompatible;
4827
4828 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4829 return Compatible;
4830}
4831
Chris Lattner5cf216b2008-01-04 18:04:52 +00004832Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004833Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004834 if (getLangOptions().CPlusPlus) {
4835 if (!lhsType->isRecordType()) {
4836 // C++ 5.17p3: If the left operand is not of class type, the
4837 // expression is implicitly converted (C++ 4) to the
4838 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004839 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004840 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004841 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004842 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004843 }
4844
4845 // FIXME: Currently, we fall through and treat C++ classes like C
4846 // structures.
4847 }
4848
Steve Naroff529a4ad2007-11-27 17:58:44 +00004849 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4850 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004851 if ((lhsType->isPointerType() ||
4852 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004853 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004854 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004855 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004856 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004857 return Compatible;
4858 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004859
Chris Lattner943140e2007-10-16 02:55:40 +00004860 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004861 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004862 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004863 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004864 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004865 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004866 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004867 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004868
Chris Lattner5cf216b2008-01-04 18:04:52 +00004869 Sema::AssignConvertType result =
4870 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004871
Steve Narofff1120de2007-08-24 22:33:52 +00004872 // C99 6.5.16.1p2: The value of the right operand is converted to the
4873 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004874 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4875 // so that we can use references in built-in functions even in C.
4876 // The getNonReferenceType() call makes sure that the resulting expression
4877 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004878 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004879 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4880 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004881 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004882}
4883
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004884QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004885 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004886 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004887 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004888 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004889}
4890
Chris Lattner7ef655a2010-01-12 21:23:57 +00004891QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004892 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004893 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004894 QualType lhsType =
4895 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4896 QualType rhsType =
4897 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004898
Nate Begemanbe2341d2008-07-14 18:02:46 +00004899 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004900 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004901 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004902
Nate Begemanbe2341d2008-07-14 18:02:46 +00004903 // Handle the case of a vector & extvector type of the same size and element
4904 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004905 if (getLangOptions().LaxVectorConversions) {
4906 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004907 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4908 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004909 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004910 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004911 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004912 }
4913 }
4914 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004915
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004916 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4917 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4918 bool swapped = false;
4919 if (rhsType->isExtVectorType()) {
4920 swapped = true;
4921 std::swap(rex, lex);
4922 std::swap(rhsType, lhsType);
4923 }
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Nate Begemandde25982009-06-28 19:12:57 +00004925 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004926 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004927 QualType EltTy = LV->getElementType();
4928 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4929 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004930 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004931 if (swapped) std::swap(rex, lex);
4932 return lhsType;
4933 }
4934 }
4935 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4936 rhsType->isRealFloatingType()) {
4937 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004938 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004939 if (swapped) std::swap(rex, lex);
4940 return lhsType;
4941 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004942 }
4943 }
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Nate Begemandde25982009-06-28 19:12:57 +00004945 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004946 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004947 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004948 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004949 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004950}
4951
Chris Lattner7ef655a2010-01-12 21:23:57 +00004952QualType Sema::CheckMultiplyDivideOperands(
4953 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004954 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004955 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004956
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004957 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004958
Chris Lattner7ef655a2010-01-12 21:23:57 +00004959 if (!lex->getType()->isArithmeticType() ||
4960 !rex->getType()->isArithmeticType())
4961 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004962
Chris Lattner7ef655a2010-01-12 21:23:57 +00004963 // Check for division by zero.
4964 if (isDiv &&
4965 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004966 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00004967 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004968
Chris Lattner7ef655a2010-01-12 21:23:57 +00004969 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004970}
4971
Chris Lattner7ef655a2010-01-12 21:23:57 +00004972QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004973 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004974 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4975 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4976 return CheckVectorOperands(Loc, lex, rex);
4977 return InvalidOperands(Loc, lex, rex);
4978 }
Steve Naroff90045e82007-07-13 23:32:42 +00004979
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004980 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004981
Chris Lattner7ef655a2010-01-12 21:23:57 +00004982 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4983 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004984
Chris Lattner7ef655a2010-01-12 21:23:57 +00004985 // Check for remainder by zero.
4986 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004987 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4988 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004989
Chris Lattner7ef655a2010-01-12 21:23:57 +00004990 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004991}
4992
Chris Lattner7ef655a2010-01-12 21:23:57 +00004993QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004994 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004995 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4996 QualType compType = CheckVectorOperands(Loc, lex, rex);
4997 if (CompLHSTy) *CompLHSTy = compType;
4998 return compType;
4999 }
Steve Naroff49b45262007-07-13 16:58:59 +00005000
Eli Friedmanab3a8522009-03-28 01:22:36 +00005001 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00005002
Reid Spencer5f016e22007-07-11 17:01:13 +00005003 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00005004 if (lex->getType()->isArithmeticType() &&
5005 rex->getType()->isArithmeticType()) {
5006 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005007 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005008 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005009
Eli Friedmand72d16e2008-05-18 18:08:51 +00005010 // Put any potential pointer into PExp
5011 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005012 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005013 std::swap(PExp, IExp);
5014
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005015 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Eli Friedmand72d16e2008-05-18 18:08:51 +00005017 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005018 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005019
Chris Lattnerb5f15622009-04-24 23:50:08 +00005020 // Check for arithmetic on pointers to incomplete types.
5021 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005022 if (getLangOptions().CPlusPlus) {
5023 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005024 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005025 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005026 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005027
5028 // GNU extension: arithmetic on pointer to void
5029 Diag(Loc, diag::ext_gnu_void_ptr)
5030 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005031 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005032 if (getLangOptions().CPlusPlus) {
5033 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5034 << lex->getType() << lex->getSourceRange();
5035 return QualType();
5036 }
5037
5038 // GNU extension: arithmetic on pointer to function
5039 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5040 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005041 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005042 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005043 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005044 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005045 PExp->getType()->isObjCObjectPointerType()) &&
5046 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005047 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5048 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005049 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005050 return QualType();
5051 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005052 // Diagnose bad cases where we step over interface counts.
5053 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5054 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5055 << PointeeTy << PExp->getSourceRange();
5056 return QualType();
5057 }
Mike Stump1eb44332009-09-09 15:08:12 +00005058
Eli Friedmanab3a8522009-03-28 01:22:36 +00005059 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005060 QualType LHSTy = Context.isPromotableBitField(lex);
5061 if (LHSTy.isNull()) {
5062 LHSTy = lex->getType();
5063 if (LHSTy->isPromotableIntegerType())
5064 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005065 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005066 *CompLHSTy = LHSTy;
5067 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005068 return PExp->getType();
5069 }
5070 }
5071
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005072 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005073}
5074
Chris Lattnereca7be62008-04-07 05:30:13 +00005075// C99 6.5.6
5076QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005077 SourceLocation Loc, QualType* CompLHSTy) {
5078 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5079 QualType compType = CheckVectorOperands(Loc, lex, rex);
5080 if (CompLHSTy) *CompLHSTy = compType;
5081 return compType;
5082 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005083
Eli Friedmanab3a8522009-03-28 01:22:36 +00005084 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005085
Chris Lattner6e4ab612007-12-09 21:53:25 +00005086 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005087
Chris Lattner6e4ab612007-12-09 21:53:25 +00005088 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005089 if (lex->getType()->isArithmeticType()
5090 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005091 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005092 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005093 }
Mike Stump1eb44332009-09-09 15:08:12 +00005094
Chris Lattner6e4ab612007-12-09 21:53:25 +00005095 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005096 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005097 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005098
Douglas Gregore7450f52009-03-24 19:52:54 +00005099 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005100
Douglas Gregore7450f52009-03-24 19:52:54 +00005101 bool ComplainAboutVoid = false;
5102 Expr *ComplainAboutFunc = 0;
5103 if (lpointee->isVoidType()) {
5104 if (getLangOptions().CPlusPlus) {
5105 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5106 << lex->getSourceRange() << rex->getSourceRange();
5107 return QualType();
5108 }
5109
5110 // GNU C extension: arithmetic on pointer to void
5111 ComplainAboutVoid = true;
5112 } else if (lpointee->isFunctionType()) {
5113 if (getLangOptions().CPlusPlus) {
5114 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005115 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005116 return QualType();
5117 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005118
5119 // GNU C extension: arithmetic on pointer to function
5120 ComplainAboutFunc = lex;
5121 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005122 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005123 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005124 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005125 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005126 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005127
Chris Lattnerb5f15622009-04-24 23:50:08 +00005128 // Diagnose bad cases where we step over interface counts.
5129 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5130 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5131 << lpointee << lex->getSourceRange();
5132 return QualType();
5133 }
Mike Stump1eb44332009-09-09 15:08:12 +00005134
Chris Lattner6e4ab612007-12-09 21:53:25 +00005135 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005136 if (rex->getType()->isIntegerType()) {
5137 if (ComplainAboutVoid)
5138 Diag(Loc, diag::ext_gnu_void_ptr)
5139 << lex->getSourceRange() << rex->getSourceRange();
5140 if (ComplainAboutFunc)
5141 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005142 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005143 << ComplainAboutFunc->getSourceRange();
5144
Eli Friedmanab3a8522009-03-28 01:22:36 +00005145 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005146 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005147 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005148
Chris Lattner6e4ab612007-12-09 21:53:25 +00005149 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005150 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005151 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005152
Douglas Gregore7450f52009-03-24 19:52:54 +00005153 // RHS must be a completely-type object type.
5154 // Handle the GNU void* extension.
5155 if (rpointee->isVoidType()) {
5156 if (getLangOptions().CPlusPlus) {
5157 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5158 << lex->getSourceRange() << rex->getSourceRange();
5159 return QualType();
5160 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005161
Douglas Gregore7450f52009-03-24 19:52:54 +00005162 ComplainAboutVoid = true;
5163 } else if (rpointee->isFunctionType()) {
5164 if (getLangOptions().CPlusPlus) {
5165 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005166 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005167 return QualType();
5168 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005169
5170 // GNU extension: arithmetic on pointer to function
5171 if (!ComplainAboutFunc)
5172 ComplainAboutFunc = rex;
5173 } else if (!rpointee->isDependentType() &&
5174 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005175 PDiag(diag::err_typecheck_sub_ptr_object)
5176 << rex->getSourceRange()
5177 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005178 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005179
Eli Friedman88d936b2009-05-16 13:54:38 +00005180 if (getLangOptions().CPlusPlus) {
5181 // Pointee types must be the same: C++ [expr.add]
5182 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5183 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5184 << lex->getType() << rex->getType()
5185 << lex->getSourceRange() << rex->getSourceRange();
5186 return QualType();
5187 }
5188 } else {
5189 // Pointee types must be compatible C99 6.5.6p3
5190 if (!Context.typesAreCompatible(
5191 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5192 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5193 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5194 << lex->getType() << rex->getType()
5195 << lex->getSourceRange() << rex->getSourceRange();
5196 return QualType();
5197 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005198 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005199
Douglas Gregore7450f52009-03-24 19:52:54 +00005200 if (ComplainAboutVoid)
5201 Diag(Loc, diag::ext_gnu_void_ptr)
5202 << lex->getSourceRange() << rex->getSourceRange();
5203 if (ComplainAboutFunc)
5204 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005205 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005206 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005207
5208 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005209 return Context.getPointerDiffType();
5210 }
5211 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005212
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005213 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005214}
5215
Chris Lattnereca7be62008-04-07 05:30:13 +00005216// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005217QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005218 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005219 // C99 6.5.7p2: Each of the operands shall have integer type.
5220 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005221 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005222
Nate Begeman2207d792009-10-25 02:26:48 +00005223 // Vector shifts promote their scalar inputs to vector type.
5224 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5225 return CheckVectorOperands(Loc, lex, rex);
5226
Chris Lattnerca5eede2007-12-12 05:47:28 +00005227 // Shifts don't perform usual arithmetic conversions, they just do integer
5228 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005229 QualType LHSTy = Context.isPromotableBitField(lex);
5230 if (LHSTy.isNull()) {
5231 LHSTy = lex->getType();
5232 if (LHSTy->isPromotableIntegerType())
5233 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005234 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005235 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005236 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005237
Chris Lattnerca5eede2007-12-12 05:47:28 +00005238 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005239
Ryan Flynnd0439682009-08-07 16:20:20 +00005240 // Sanity-check shift operands
5241 llvm::APSInt Right;
5242 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005243 if (!rex->isValueDependent() &&
5244 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005245 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005246 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5247 else {
5248 llvm::APInt LeftBits(Right.getBitWidth(),
5249 Context.getTypeSize(lex->getType()));
5250 if (Right.uge(LeftBits))
5251 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5252 }
5253 }
5254
Chris Lattnerca5eede2007-12-12 05:47:28 +00005255 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005256 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005257}
5258
Douglas Gregor0c6db942009-05-04 06:07:12 +00005259// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005260QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005261 unsigned OpaqueOpc, bool isRelational) {
5262 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5263
Chris Lattner02dd4b12009-12-05 05:40:13 +00005264 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005265 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005266 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005267
John McCalld1b47bf2010-03-11 19:43:18 +00005268 CheckSignCompare(lex, rex, Loc, &Opc);
John McCall45aa4552009-11-05 00:40:04 +00005269
Chris Lattnera5937dd2007-08-26 01:18:55 +00005270 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005271 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5272 UsualArithmeticConversions(lex, rex);
5273 else {
5274 UsualUnaryConversions(lex);
5275 UsualUnaryConversions(rex);
5276 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005277 QualType lType = lex->getType();
5278 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005279
Mike Stumpaf199f32009-05-07 18:43:07 +00005280 if (!lType->isFloatingType()
5281 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005282 // For non-floating point types, check for self-comparisons of the form
5283 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5284 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005285 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005286 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005287 Expr *LHSStripped = lex->IgnoreParens();
5288 Expr *RHSStripped = rex->IgnoreParens();
5289 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5290 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005291 if (DRL->getDecl() == DRR->getDecl() &&
5292 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005293 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005294
Chris Lattner55660a72009-03-08 19:39:53 +00005295 if (isa<CastExpr>(LHSStripped))
5296 LHSStripped = LHSStripped->IgnoreParenCasts();
5297 if (isa<CastExpr>(RHSStripped))
5298 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Chris Lattner55660a72009-03-08 19:39:53 +00005300 // Warn about comparisons against a string constant (unless the other
5301 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005302 Expr *literalString = 0;
5303 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005304 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005305 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005306 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005307 literalString = lex;
5308 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005309 } else if ((isa<StringLiteral>(RHSStripped) ||
5310 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005311 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005312 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005313 literalString = rex;
5314 literalStringStripped = RHSStripped;
5315 }
5316
5317 if (literalString) {
5318 std::string resultComparison;
5319 switch (Opc) {
5320 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5321 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5322 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5323 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5324 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5325 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5326 default: assert(false && "Invalid comparison operator");
5327 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005328
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005329 DiagRuntimeBehavior(Loc,
5330 PDiag(diag::warn_stringcompare)
5331 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00005332 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00005333 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005334 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005335
Douglas Gregor447b69e2008-11-19 03:25:36 +00005336 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005337 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005338
Chris Lattnera5937dd2007-08-26 01:18:55 +00005339 if (isRelational) {
5340 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005341 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005342 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005343 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005344 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005345 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005346
Chris Lattnera5937dd2007-08-26 01:18:55 +00005347 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005348 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005349 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005350
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005351 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005352 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005353 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005354 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005355
Chris Lattnera5937dd2007-08-26 01:18:55 +00005356 // All of the following pointer related warnings are GCC extensions, except
5357 // when handling null pointer constants. One day, we can consider making them
5358 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005359 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005360 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005361 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005362 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005363 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005364
Douglas Gregor0c6db942009-05-04 06:07:12 +00005365 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005366 if (LCanPointeeTy == RCanPointeeTy)
5367 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005368 if (!isRelational &&
5369 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5370 // Valid unless comparison between non-null pointer and function pointer
5371 // This is a gcc extension compatibility comparison.
5372 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5373 && !LHSIsNull && !RHSIsNull) {
5374 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5375 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5376 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5377 return ResultTy;
5378 }
5379 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005380 // C++ [expr.rel]p2:
5381 // [...] Pointer conversions (4.10) and qualification
5382 // conversions (4.4) are performed on pointer operands (or on
5383 // a pointer operand and a null pointer constant) to bring
5384 // them to their composite pointer type. [...]
5385 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005386 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005387 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005388 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005389 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005390 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005391 if (T.isNull()) {
5392 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5393 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5394 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005395 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005396 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005397 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005398 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005399 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005400 }
5401
Eli Friedman73c39ab2009-10-20 08:27:19 +00005402 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5403 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005404 return ResultTy;
5405 }
Eli Friedman3075e762009-08-23 00:27:47 +00005406 // C99 6.5.9p2 and C99 6.5.8p2
5407 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5408 RCanPointeeTy.getUnqualifiedType())) {
5409 // Valid unless a relational comparison of function pointers
5410 if (isRelational && LCanPointeeTy->isFunctionType()) {
5411 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5412 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5413 }
5414 } else if (!isRelational &&
5415 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5416 // Valid unless comparison between non-null pointer and function pointer
5417 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5418 && !LHSIsNull && !RHSIsNull) {
5419 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5420 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5421 }
5422 } else {
5423 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005424 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005425 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005426 }
Eli Friedman3075e762009-08-23 00:27:47 +00005427 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005428 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005429 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005430 }
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005432 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005433 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005434 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005435 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005436 (lType->isPointerType() ||
5437 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005438 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005439 return ResultTy;
5440 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005441 if (LHSIsNull &&
5442 (rType->isPointerType() ||
5443 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005444 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005445 return ResultTy;
5446 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005447
5448 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005449 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005450 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5451 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005452 // In addition, pointers to members can be compared, or a pointer to
5453 // member and a null pointer constant. Pointer to member conversions
5454 // (4.11) and qualification conversions (4.4) are performed to bring
5455 // them to a common type. If one operand is a null pointer constant,
5456 // the common type is the type of the other operand. Otherwise, the
5457 // common type is a pointer to member type similar (4.4) to the type
5458 // of one of the operands, with a cv-qualification signature (4.4)
5459 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005460 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005461 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005462 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005463 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005464 if (T.isNull()) {
5465 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005466 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005467 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005468 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005469 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005470 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005471 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005472 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005473 }
Mike Stump1eb44332009-09-09 15:08:12 +00005474
Eli Friedman73c39ab2009-10-20 08:27:19 +00005475 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5476 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005477 return ResultTy;
5478 }
Mike Stump1eb44332009-09-09 15:08:12 +00005479
Douglas Gregor20b3e992009-08-24 17:42:35 +00005480 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005481 if (lType->isNullPtrType() && rType->isNullPtrType())
5482 return ResultTy;
5483 }
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Steve Naroff1c7d0672008-09-04 15:10:53 +00005485 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005486 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005487 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5488 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005489
Steve Naroff1c7d0672008-09-04 15:10:53 +00005490 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005491 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005492 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005493 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005494 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005495 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005496 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005497 }
Steve Naroff59f53942008-09-28 01:11:11 +00005498 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005499 if (!isRelational
5500 && ((lType->isBlockPointerType() && rType->isPointerType())
5501 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005502 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005503 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005504 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005505 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005506 ->getPointeeType()->isVoidType())))
5507 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5508 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005509 }
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 Naroff59f53942008-09-28 01:11:11 +00005512 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005513
Steve Naroff14108da2009-07-10 23:34:53 +00005514 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005515 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005516 const PointerType *LPT = lType->getAs<PointerType>();
5517 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005518 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005519 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005520 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005521 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005522
Steve Naroffa8069f12008-11-17 19:49:16 +00005523 if (!LPtrToVoid && !RPtrToVoid &&
5524 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005525 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005526 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005527 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005528 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005529 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005530 }
Steve Naroff14108da2009-07-10 23:34:53 +00005531 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005532 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005533 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5534 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005535 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005536 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005537 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005538 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005539 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005540 unsigned DiagID = 0;
5541 if (RHSIsNull) {
5542 if (isRelational)
5543 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5544 } else if (isRelational)
5545 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5546 else
5547 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005548
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005549 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005550 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005551 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005552 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005553 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005554 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005555 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005556 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005557 unsigned DiagID = 0;
5558 if (LHSIsNull) {
5559 if (isRelational)
5560 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5561 } else if (isRelational)
5562 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5563 else
5564 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005566 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005567 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005568 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005569 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005570 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005571 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005572 }
Steve Naroff39218df2008-09-04 16:56:14 +00005573 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005574 if (!isRelational && RHSIsNull
5575 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005576 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005577 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005578 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005579 if (!isRelational && LHSIsNull
5580 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005581 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005582 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005583 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005584 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005585}
5586
Nate Begemanbe2341d2008-07-14 18:02:46 +00005587/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005588/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005589/// like a scalar comparison, a vector comparison produces a vector of integer
5590/// types.
5591QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005592 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005593 bool isRelational) {
5594 // Check to make sure we're operating on vectors of the same type and width,
5595 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005596 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005597 if (vType.isNull())
5598 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005599
Nate Begemanbe2341d2008-07-14 18:02:46 +00005600 QualType lType = lex->getType();
5601 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005602
Nate Begemanbe2341d2008-07-14 18:02:46 +00005603 // For non-floating point types, check for self-comparisons of the form
5604 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5605 // often indicate logic errors in the program.
5606 if (!lType->isFloatingType()) {
5607 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5608 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5609 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005610 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005611 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005612
Nate Begemanbe2341d2008-07-14 18:02:46 +00005613 // Check for comparisons of floating point operands using != and ==.
5614 if (!isRelational && lType->isFloatingType()) {
5615 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005616 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005617 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005618
Nate Begemanbe2341d2008-07-14 18:02:46 +00005619 // Return the type for the comparison, which is the same as vector type for
5620 // integer vectors, or an integer type of identical size and number of
5621 // elements for floating point vectors.
5622 if (lType->isIntegerType())
5623 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005624
John McCall183700f2009-09-21 23:43:11 +00005625 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005626 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005627 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005628 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005629 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005630 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5631
Mike Stumpeed9cac2009-02-19 03:04:26 +00005632 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005633 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005634 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5635}
5636
Reid Spencer5f016e22007-07-11 17:01:13 +00005637inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005638 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005639 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005640 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005641
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005642 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005643
Steve Naroffa4332e22007-07-17 00:58:39 +00005644 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005645 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005646 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005647}
5648
5649inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005650 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005651 if (!Context.getLangOptions().CPlusPlus) {
5652 UsualUnaryConversions(lex);
5653 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005654
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005655 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5656 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005657
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005658 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005659 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005660
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005661 // C++ [expr.log.and]p1
5662 // C++ [expr.log.or]p1
5663 // The operands are both implicitly converted to type bool (clause 4).
5664 StandardConversionSequence LHS;
5665 if (!IsStandardConversion(lex, Context.BoolTy,
5666 /*InOverloadResolution=*/false, LHS))
5667 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005668
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005669 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005670 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005671 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005672
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005673 StandardConversionSequence RHS;
5674 if (!IsStandardConversion(rex, Context.BoolTy,
5675 /*InOverloadResolution=*/false, RHS))
5676 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005677
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005678 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005679 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005680 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005681
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005682 // C++ [expr.log.and]p2
5683 // C++ [expr.log.or]p2
5684 // The result is a bool.
5685 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005686}
5687
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005688/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5689/// is a read-only property; return true if so. A readonly property expression
5690/// depends on various declarations and thus must be treated specially.
5691///
Mike Stump1eb44332009-09-09 15:08:12 +00005692static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005693 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5694 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5695 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5696 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005697 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005698 BaseType->getAsObjCInterfacePointerType())
5699 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5700 if (S.isPropertyReadonly(PDecl, IFace))
5701 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005702 }
5703 }
5704 return false;
5705}
5706
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005707/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5708/// emit an error and return true. If so, return false.
5709static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005710 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005711 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005712 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005713 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5714 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005715 if (IsLV == Expr::MLV_Valid)
5716 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005717
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005718 unsigned Diag = 0;
5719 bool NeedType = false;
5720 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005721 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005722 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005723 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5724 NeedType = true;
5725 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005726 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005727 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5728 NeedType = true;
5729 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005730 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005731 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5732 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005733 case Expr::MLV_Valid:
5734 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005735 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005736 case Expr::MLV_MemberFunction:
5737 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005738 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5739 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005740 case Expr::MLV_IncompleteType:
5741 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005742 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005743 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005744 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005745 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005746 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5747 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005748 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005749 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5750 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005751 case Expr::MLV_ReadonlyProperty:
5752 Diag = diag::error_readonly_property_assignment;
5753 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005754 case Expr::MLV_NoSetterProperty:
5755 Diag = diag::error_nosetter_property_assignment;
5756 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005757 case Expr::MLV_SubObjCPropertySetting:
5758 Diag = diag::error_no_subobject_property_setting;
5759 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005760 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005761
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005762 SourceRange Assign;
5763 if (Loc != OrigLoc)
5764 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005765 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005766 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005767 else
Mike Stump1eb44332009-09-09 15:08:12 +00005768 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005769 return true;
5770}
5771
5772
5773
5774// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005775QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5776 SourceLocation Loc,
5777 QualType CompoundType) {
5778 // Verify that LHS is a modifiable lvalue, and emit error if not.
5779 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005780 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005781
5782 QualType LHSType = LHS->getType();
5783 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005784
Chris Lattner5cf216b2008-01-04 18:04:52 +00005785 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005786 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005787 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005788 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005789 // Special case of NSObject attributes on c-style pointer types.
5790 if (ConvTy == IncompatiblePointer &&
5791 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005792 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005793 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005794 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005795 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005796
Chris Lattner2c156472008-08-21 18:04:13 +00005797 // If the RHS is a unary plus or minus, check to see if they = and + are
5798 // right next to each other. If so, the user may have typo'd "x =+ 4"
5799 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005800 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005801 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5802 RHSCheck = ICE->getSubExpr();
5803 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5804 if ((UO->getOpcode() == UnaryOperator::Plus ||
5805 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005806 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005807 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005808 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5809 // And there is a space or other character before the subexpr of the
5810 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005811 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5812 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005813 Diag(Loc, diag::warn_not_compound_assign)
5814 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5815 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005816 }
Chris Lattner2c156472008-08-21 18:04:13 +00005817 }
5818 } else {
5819 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005820 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005821 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005822
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005823 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005824 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005825 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005826
Reid Spencer5f016e22007-07-11 17:01:13 +00005827 // C99 6.5.16p3: The type of an assignment expression is the type of the
5828 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005829 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005830 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5831 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005832 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005833 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005834 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005835}
5836
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005837// C99 6.5.17
5838QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005839 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00005840 // C++ does not perform this conversion (C++ [expr.comma]p1).
5841 if (!getLangOptions().CPlusPlus)
5842 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005843
5844 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5845 // incomplete in C++).
5846
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005847 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005848}
5849
Steve Naroff49b45262007-07-13 16:58:59 +00005850/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5851/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005852QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5853 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005854 if (Op->isTypeDependent())
5855 return Context.DependentTy;
5856
Chris Lattner3528d352008-11-21 07:05:48 +00005857 QualType ResType = Op->getType();
5858 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005859
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005860 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5861 // Decrement of bool is not allowed.
5862 if (!isInc) {
5863 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5864 return QualType();
5865 }
5866 // Increment of bool sets it to true, but is deprecated.
5867 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5868 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005869 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005870 } else if (ResType->isAnyPointerType()) {
5871 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005872
Chris Lattner3528d352008-11-21 07:05:48 +00005873 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005874 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005875 if (getLangOptions().CPlusPlus) {
5876 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5877 << Op->getSourceRange();
5878 return QualType();
5879 }
5880
5881 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005882 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005883 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005884 if (getLangOptions().CPlusPlus) {
5885 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5886 << Op->getType() << Op->getSourceRange();
5887 return QualType();
5888 }
5889
5890 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005891 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005892 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005893 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005894 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005895 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005896 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005897 // Diagnose bad cases where we step over interface counts.
5898 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5899 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5900 << PointeeTy << Op->getSourceRange();
5901 return QualType();
5902 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005903 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005904 // C99 does not support ++/-- on complex types, we allow as an extension.
5905 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005906 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005907 } else {
5908 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005909 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005910 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005911 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005912 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005913 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005914 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005915 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005916 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005917}
5918
Anders Carlsson369dee42008-02-01 07:15:58 +00005919/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005920/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005921/// where the declaration is needed for type checking. We only need to
5922/// handle cases when the expression references a function designator
5923/// or is an lvalue. Here are some examples:
5924/// - &(x) => x
5925/// - &*****f => f for f a function designator.
5926/// - &s.xx => s
5927/// - &s.zz[1].yy -> s, if zz is an array
5928/// - *(x + 1) -> x, if x is an array
5929/// - &"123"[2] -> 0
5930/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005931static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005932 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005933 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005934 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005935 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005936 // If this is an arrow operator, the address is an offset from
5937 // the base's value, so the object the base refers to is
5938 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005939 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005940 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005941 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005942 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005943 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005944 // FIXME: This code shouldn't be necessary! We should catch the implicit
5945 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005946 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5947 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5948 if (ICE->getSubExpr()->getType()->isArrayType())
5949 return getPrimaryDecl(ICE->getSubExpr());
5950 }
5951 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005952 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005953 case Stmt::UnaryOperatorClass: {
5954 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005955
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005956 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005957 case UnaryOperator::Real:
5958 case UnaryOperator::Imag:
5959 case UnaryOperator::Extension:
5960 return getPrimaryDecl(UO->getSubExpr());
5961 default:
5962 return 0;
5963 }
5964 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005965 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005966 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005967 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005968 // If the result of an implicit cast is an l-value, we care about
5969 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005970 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005971 default:
5972 return 0;
5973 }
5974}
5975
5976/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005977/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005978/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005979/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005980/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005981/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005982/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005983QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005984 // Make sure to ignore parentheses in subsequent checks
5985 op = op->IgnoreParens();
5986
Douglas Gregor9103bb22008-12-17 22:52:20 +00005987 if (op->isTypeDependent())
5988 return Context.DependentTy;
5989
Steve Naroff08f19672008-01-13 17:10:08 +00005990 if (getLangOptions().C99) {
5991 // Implement C99-only parts of addressof rules.
5992 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5993 if (uOp->getOpcode() == UnaryOperator::Deref)
5994 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5995 // (assuming the deref expression is valid).
5996 return uOp->getSubExpr()->getType();
5997 }
5998 // Technically, there should be a check for array subscript
5999 // expressions here, but the result of one is always an lvalue anyway.
6000 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006001 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00006002 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00006003
Sebastian Redle27d87f2010-01-11 15:56:56 +00006004 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6005 if (lval == Expr::LV_MemberFunction && ME &&
6006 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6007 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6008 // &f where f is a member of the current object, or &o.f, or &p->f
6009 // All these are not allowed, and we need to catch them before the dcl
6010 // branch of the if, below.
6011 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6012 << dcl;
6013 // FIXME: Improve this diagnostic and provide a fixit.
6014
6015 // Now recover by acting as if the function had been accessed qualified.
6016 return Context.getMemberPointerType(op->getType(),
6017 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6018 .getTypePtr());
Douglas Gregore873fb72010-02-16 21:39:57 +00006019 } else if (lval == Expr::LV_ClassTemporary) {
6020 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6021 : diag::ext_typecheck_addrof_class_temporary)
6022 << op->getType() << op->getSourceRange();
6023 if (isSFINAEContext())
6024 return QualType();
Sebastian Redle27d87f2010-01-11 15:56:56 +00006025 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006026 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006027 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006028 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006029 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006030 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6031 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006032 return QualType();
6033 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006034 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006035 // The operand cannot be a bit-field
6036 Diag(OpLoc, diag::err_typecheck_address_of)
6037 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006038 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006039 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006040 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006041 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006042 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006043 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006044 } else if (isa<ObjCPropertyRefExpr>(op)) {
6045 // cannot take address of a property expression.
6046 Diag(OpLoc, diag::err_typecheck_address_of)
6047 << "property expression" << op->getSourceRange();
6048 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006049 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6050 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006051 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6052 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00006053 } else if (isa<UnresolvedLookupExpr>(op)) {
6054 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006055 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006056 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006057 // with the register storage-class specifier.
6058 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6059 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006060 Diag(OpLoc, diag::err_typecheck_address_of)
6061 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006062 return QualType();
6063 }
John McCallba135432009-11-21 08:51:07 +00006064 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006065 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006066 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006067 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006068 // Could be a pointer to member, though, if there is an explicit
6069 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006070 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006071 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006072 if (Ctx && Ctx->isRecord()) {
6073 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006074 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006075 diag::err_cannot_form_pointer_to_member_of_reference_type)
6076 << FD->getDeclName() << FD->getType();
6077 return QualType();
6078 }
Mike Stump1eb44332009-09-09 15:08:12 +00006079
Sebastian Redlebc07d52009-02-03 20:19:35 +00006080 return Context.getMemberPointerType(op->getType(),
6081 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006082 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006083 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006084 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006085 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006086 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006087 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6088 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006089 return Context.getMemberPointerType(op->getType(),
6090 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6091 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006092 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006093 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006094
Eli Friedman441cf102009-05-16 23:27:50 +00006095 if (lval == Expr::LV_IncompleteVoidType) {
6096 // Taking the address of a void variable is technically illegal, but we
6097 // allow it in cases which are otherwise valid.
6098 // Example: "extern void x; void* y = &x;".
6099 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6100 }
6101
Reid Spencer5f016e22007-07-11 17:01:13 +00006102 // If the operand has type "type", the result has type "pointer to type".
6103 return Context.getPointerType(op->getType());
6104}
6105
Chris Lattner22caddc2008-11-23 09:13:29 +00006106QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006107 if (Op->isTypeDependent())
6108 return Context.DependentTy;
6109
Chris Lattner22caddc2008-11-23 09:13:29 +00006110 UsualUnaryConversions(Op);
6111 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006112
Chris Lattner22caddc2008-11-23 09:13:29 +00006113 // Note that per both C89 and C99, this is always legal, even if ptype is an
6114 // incomplete type or void. It would be possible to warn about dereferencing
6115 // a void pointer, but it's completely well-defined, and such a warning is
6116 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006117 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006118 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006119
John McCall183700f2009-09-21 23:43:11 +00006120 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006121 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006122
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006123 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006124 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006125 return QualType();
6126}
6127
6128static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6129 tok::TokenKind Kind) {
6130 BinaryOperator::Opcode Opc;
6131 switch (Kind) {
6132 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006133 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6134 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006135 case tok::star: Opc = BinaryOperator::Mul; break;
6136 case tok::slash: Opc = BinaryOperator::Div; break;
6137 case tok::percent: Opc = BinaryOperator::Rem; break;
6138 case tok::plus: Opc = BinaryOperator::Add; break;
6139 case tok::minus: Opc = BinaryOperator::Sub; break;
6140 case tok::lessless: Opc = BinaryOperator::Shl; break;
6141 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6142 case tok::lessequal: Opc = BinaryOperator::LE; break;
6143 case tok::less: Opc = BinaryOperator::LT; break;
6144 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6145 case tok::greater: Opc = BinaryOperator::GT; break;
6146 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6147 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6148 case tok::amp: Opc = BinaryOperator::And; break;
6149 case tok::caret: Opc = BinaryOperator::Xor; break;
6150 case tok::pipe: Opc = BinaryOperator::Or; break;
6151 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6152 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6153 case tok::equal: Opc = BinaryOperator::Assign; break;
6154 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6155 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6156 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6157 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6158 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6159 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6160 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6161 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6162 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6163 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6164 case tok::comma: Opc = BinaryOperator::Comma; break;
6165 }
6166 return Opc;
6167}
6168
6169static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6170 tok::TokenKind Kind) {
6171 UnaryOperator::Opcode Opc;
6172 switch (Kind) {
6173 default: assert(0 && "Unknown unary op!");
6174 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6175 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6176 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6177 case tok::star: Opc = UnaryOperator::Deref; break;
6178 case tok::plus: Opc = UnaryOperator::Plus; break;
6179 case tok::minus: Opc = UnaryOperator::Minus; break;
6180 case tok::tilde: Opc = UnaryOperator::Not; break;
6181 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006182 case tok::kw___real: Opc = UnaryOperator::Real; break;
6183 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6184 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6185 }
6186 return Opc;
6187}
6188
Douglas Gregoreaebc752008-11-06 23:29:22 +00006189/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6190/// operator @p Opc at location @c TokLoc. This routine only supports
6191/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006192Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6193 unsigned Op,
6194 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006195 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006196 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006197 // The following two variables are used for compound assignment operators
6198 QualType CompLHSTy; // Type of LHS after promotions for computation
6199 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006200
6201 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006202 case BinaryOperator::Assign:
6203 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6204 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006205 case BinaryOperator::PtrMemD:
6206 case BinaryOperator::PtrMemI:
6207 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6208 Opc == BinaryOperator::PtrMemI);
6209 break;
6210 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006211 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006212 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6213 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006214 break;
6215 case BinaryOperator::Rem:
6216 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6217 break;
6218 case BinaryOperator::Add:
6219 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6220 break;
6221 case BinaryOperator::Sub:
6222 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6223 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006224 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006225 case BinaryOperator::Shr:
6226 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6227 break;
6228 case BinaryOperator::LE:
6229 case BinaryOperator::LT:
6230 case BinaryOperator::GE:
6231 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006232 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006233 break;
6234 case BinaryOperator::EQ:
6235 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006236 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006237 break;
6238 case BinaryOperator::And:
6239 case BinaryOperator::Xor:
6240 case BinaryOperator::Or:
6241 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6242 break;
6243 case BinaryOperator::LAnd:
6244 case BinaryOperator::LOr:
6245 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6246 break;
6247 case BinaryOperator::MulAssign:
6248 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006249 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6250 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006251 CompLHSTy = CompResultTy;
6252 if (!CompResultTy.isNull())
6253 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006254 break;
6255 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006256 CompResultTy = CheckRemainderOperands(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::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006262 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6263 if (!CompResultTy.isNull())
6264 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006265 break;
6266 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006267 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6268 if (!CompResultTy.isNull())
6269 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006270 break;
6271 case BinaryOperator::ShlAssign:
6272 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006273 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6274 CompLHSTy = CompResultTy;
6275 if (!CompResultTy.isNull())
6276 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006277 break;
6278 case BinaryOperator::AndAssign:
6279 case BinaryOperator::XorAssign:
6280 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006281 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6282 CompLHSTy = CompResultTy;
6283 if (!CompResultTy.isNull())
6284 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006285 break;
6286 case BinaryOperator::Comma:
6287 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6288 break;
6289 }
6290 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006291 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006292 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006293 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6294 else
6295 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006296 CompLHSTy, CompResultTy,
6297 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006298}
6299
Sebastian Redlaee3c932009-10-27 12:10:02 +00006300/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6301/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006302static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6303 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00006304 const PartialDiagnostic &FirstNote,
6305 SourceRange FirstParenRange,
6306 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006307 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00006308 Self.Diag(Loc, PD);
6309
6310 if (!FirstNote.getDiagID())
6311 return;
6312
6313 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6314 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6315 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006316 return;
6317 }
6318
Douglas Gregor55b38842010-04-14 16:09:52 +00006319 Self.Diag(Loc, FirstNote)
6320 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00006321 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006322
Douglas Gregor55b38842010-04-14 16:09:52 +00006323 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00006324 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006325
Douglas Gregor827feec2010-01-08 00:20:23 +00006326 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6327 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6328 // We can't display the parentheses, so just dig the
6329 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00006330 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00006331 return;
6332 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006333
Douglas Gregor55b38842010-04-14 16:09:52 +00006334 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00006335 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6336 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006337}
6338
Sebastian Redlaee3c932009-10-27 12:10:02 +00006339/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6340/// operators are mixed in a way that suggests that the programmer forgot that
6341/// comparison operators have higher precedence. The most typical example of
6342/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006343static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6344 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006345 typedef BinaryOperator BinOp;
6346 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6347 rhsopc = static_cast<BinOp::Opcode>(-1);
6348 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006349 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006350 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006351 rhsopc = BO->getOpcode();
6352
6353 // Subs are not binary operators.
6354 if (lhsopc == -1 && rhsopc == -1)
6355 return;
6356
6357 // Bitwise operations are sometimes used as eager logical ops.
6358 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006359 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6360 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006361 return;
6362
Sebastian Redlaee3c932009-10-27 12:10:02 +00006363 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006364 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006365 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006366 << SourceRange(lhs->getLocStart(), OpLoc)
6367 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006368 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006369 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006370 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6371 Self.PDiag(diag::note_precedence_bitwise_silence)
6372 << BinOp::getOpcodeStr(lhsopc),
6373 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00006374 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006375 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006376 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006377 << SourceRange(OpLoc, rhs->getLocEnd())
6378 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006379 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006380 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006381 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6382 Self.PDiag(diag::note_precedence_bitwise_silence)
6383 << BinOp::getOpcodeStr(rhsopc),
6384 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006385}
6386
6387/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6388/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6389/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6390static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6391 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006392 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006393 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6394}
6395
Reid Spencer5f016e22007-07-11 17:01:13 +00006396// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006397Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6398 tok::TokenKind Kind,
6399 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006400 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006401 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006402
Steve Narofff69936d2007-09-16 03:34:24 +00006403 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6404 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006405
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006406 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6407 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6408
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006409 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6410}
6411
6412Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6413 BinaryOperator::Opcode Opc,
6414 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006415 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006416 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006417 rhs->getType()->isOverloadableType())) {
6418 // Find all of the overloaded operators visible from this
6419 // point. We perform both an operator-name lookup from the local
6420 // scope and an argument-dependent lookup based on the types of
6421 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006422 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006423 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006424 if (S && OverOp != OO_None)
6425 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6426 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006427
Douglas Gregor063daf62009-03-13 18:40:31 +00006428 // Build the (potentially-overloaded, potentially-dependent)
6429 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006430 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006431 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006432
Douglas Gregoreaebc752008-11-06 23:29:22 +00006433 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006434 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006435}
6436
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006437Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006438 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006439 ExprArg InputArg) {
6440 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006441
Mike Stump390b4cc2009-05-16 07:39:55 +00006442 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006443 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006444 QualType resultType;
6445 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006446 case UnaryOperator::OffsetOf:
6447 assert(false && "Invalid unary operator");
6448 break;
6449
Reid Spencer5f016e22007-07-11 17:01:13 +00006450 case UnaryOperator::PreInc:
6451 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006452 case UnaryOperator::PostInc:
6453 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006454 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006455 Opc == UnaryOperator::PreInc ||
6456 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006457 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006458 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006459 resultType = CheckAddressOfOperand(Input, OpLoc);
6460 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006461 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006462 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006463 resultType = CheckIndirectionOperand(Input, OpLoc);
6464 break;
6465 case UnaryOperator::Plus:
6466 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006467 UsualUnaryConversions(Input);
6468 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006469 if (resultType->isDependentType())
6470 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006471 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6472 break;
6473 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6474 resultType->isEnumeralType())
6475 break;
6476 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6477 Opc == UnaryOperator::Plus &&
6478 resultType->isPointerType())
6479 break;
6480
Sebastian Redl0eb23302009-01-19 00:08:26 +00006481 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6482 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006483 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006484 UsualUnaryConversions(Input);
6485 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006486 if (resultType->isDependentType())
6487 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006488 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6489 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6490 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006491 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006492 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006493 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006494 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6495 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006496 break;
6497 case UnaryOperator::LNot: // logical negation
6498 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006499 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006500 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006501 if (resultType->isDependentType())
6502 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006503 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006504 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6505 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006506 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006507 // In C++, it's bool. C++ 5.3.1p8
6508 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006509 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006510 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006511 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006512 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006513 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006514 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006515 resultType = Input->getType();
6516 break;
6517 }
6518 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006519 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006520
6521 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006522 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006523}
6524
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006525Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6526 UnaryOperator::Opcode Opc,
6527 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006528 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006529 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6530 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006531 // Find all of the overloaded operators visible from this
6532 // point. We perform both an operator-name lookup from the local
6533 // scope and an argument-dependent lookup based on the types of
6534 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006535 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006536 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006537 if (S && OverOp != OO_None)
6538 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6539 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006540
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006541 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6542 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006543
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006544 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6545}
6546
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006547// Unary Operators. 'Tok' is the token for the operator.
6548Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6549 tok::TokenKind Op, ExprArg input) {
6550 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6551}
6552
Steve Naroff1b273c42007-09-16 14:56:35 +00006553/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006554Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6555 SourceLocation LabLoc,
6556 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006557 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006558 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006559
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006560 // If we haven't seen this label yet, create a forward reference. It
6561 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006562 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006563 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006564
Reid Spencer5f016e22007-07-11 17:01:13 +00006565 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006566 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6567 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006568}
6569
Sebastian Redlf53597f2009-03-15 17:47:39 +00006570Sema::OwningExprResult
6571Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6572 SourceLocation RPLoc) { // "({..})"
6573 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006574 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6575 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6576
Douglas Gregordd8f5692010-03-10 04:54:39 +00006577 bool isFileScope
6578 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006579 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006580 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006581
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006582 // FIXME: there are a variety of strange constraints to enforce here, for
6583 // example, it is not possible to goto into a stmt expression apparently.
6584 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006585
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006586 // If there are sub stmts in the compound stmt, take the type of the last one
6587 // as the type of the stmtexpr.
6588 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006589
Chris Lattner611b2ec2008-07-26 19:51:01 +00006590 if (!Compound->body_empty()) {
6591 Stmt *LastStmt = Compound->body_back();
6592 // If LastStmt is a label, skip down through into the body.
6593 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6594 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006595
Chris Lattner611b2ec2008-07-26 19:51:01 +00006596 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006597 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006598 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006599
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006600 // FIXME: Check that expression type is complete/non-abstract; statement
6601 // expressions are not lvalues.
6602
Sebastian Redlf53597f2009-03-15 17:47:39 +00006603 substmt.release();
6604 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006605}
Steve Naroffd34e9152007-08-01 22:05:33 +00006606
Sebastian Redlf53597f2009-03-15 17:47:39 +00006607Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6608 SourceLocation BuiltinLoc,
6609 SourceLocation TypeLoc,
6610 TypeTy *argty,
6611 OffsetOfComponent *CompPtr,
6612 unsigned NumComponents,
6613 SourceLocation RPLoc) {
6614 // FIXME: This function leaks all expressions in the offset components on
6615 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006616 // FIXME: Preserve type source info.
6617 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006618 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006619
Sebastian Redl28507842009-02-26 14:39:58 +00006620 bool Dependent = ArgTy->isDependentType();
6621
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006622 // We must have at least one component that refers to the type, and the first
6623 // one is known to be a field designator. Verify that the ArgTy represents
6624 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006625 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006626 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006627
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006628 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6629 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006630
Eli Friedman35183ac2009-02-27 06:44:11 +00006631 // Otherwise, create a null pointer as the base, and iteratively process
6632 // the offsetof designators.
6633 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6634 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006635 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006636 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006637
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006638 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6639 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006640 // FIXME: This diagnostic isn't actually visible because the location is in
6641 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006642 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006643 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6644 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006645
Sebastian Redl28507842009-02-26 14:39:58 +00006646 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006647 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006648
John McCalld00f2002009-11-04 03:03:43 +00006649 if (RequireCompleteType(TypeLoc, Res->getType(),
6650 diag::err_offsetof_incomplete_type))
6651 return ExprError();
6652
Sebastian Redl28507842009-02-26 14:39:58 +00006653 // FIXME: Dependent case loses a lot of information here. And probably
6654 // leaks like a sieve.
6655 for (unsigned i = 0; i != NumComponents; ++i) {
6656 const OffsetOfComponent &OC = CompPtr[i];
6657 if (OC.isBrackets) {
6658 // Offset of an array sub-field. TODO: Should we allow vector elements?
6659 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6660 if (!AT) {
6661 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006662 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6663 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006664 }
6665
6666 // FIXME: C++: Verify that operator[] isn't overloaded.
6667
Eli Friedman35183ac2009-02-27 06:44:11 +00006668 // Promote the array so it looks more like a normal array subscript
6669 // expression.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006670 DefaultFunctionArrayLvalueConversion(Res);
Eli Friedman35183ac2009-02-27 06:44:11 +00006671
Sebastian Redl28507842009-02-26 14:39:58 +00006672 // C99 6.5.2.1p1
6673 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006674 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006675 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006676 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006677 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006678 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006679
6680 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6681 OC.LocEnd);
6682 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006683 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006684
Ted Kremenek6217b802009-07-29 21:53:49 +00006685 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006686 if (!RC) {
6687 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006688 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6689 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006690 }
Chris Lattner704fe352007-08-30 17:59:59 +00006691
Sebastian Redl28507842009-02-26 14:39:58 +00006692 // Get the decl corresponding to this.
6693 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006694 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006695 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6696 DiagRuntimeBehavior(BuiltinLoc,
6697 PDiag(diag::warn_offsetof_non_pod_type)
6698 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6699 << Res->getType()))
6700 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006701 }
Mike Stump1eb44332009-09-09 15:08:12 +00006702
John McCalla24dc2e2009-11-17 02:14:36 +00006703 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6704 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006705
John McCall1bcee0a2009-12-02 08:25:40 +00006706 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006707 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006708 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006709 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6710 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006711
Sebastian Redl28507842009-02-26 14:39:58 +00006712 // FIXME: C++: Verify that MemberDecl isn't a static field.
6713 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006714 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006715 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006716 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006717 } else {
John McCall6bb80172010-03-30 21:47:33 +00006718 PerformObjectMemberConversion(Res, /*Qualifier=*/0,
6719 *R.begin(), MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006720 // MemberDecl->getType() doesn't get the right qualifiers, but it
6721 // doesn't matter here.
6722 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6723 MemberDecl->getType().getNonReferenceType());
6724 }
Sebastian Redl28507842009-02-26 14:39:58 +00006725 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006726 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006727
Sebastian Redlf53597f2009-03-15 17:47:39 +00006728 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6729 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006730}
6731
6732
Sebastian Redlf53597f2009-03-15 17:47:39 +00006733Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6734 TypeTy *arg1,TypeTy *arg2,
6735 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006736 // FIXME: Preserve type source info.
6737 QualType argT1 = GetTypeFromParser(arg1);
6738 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006739
Steve Naroffd34e9152007-08-01 22:05:33 +00006740 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006741
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006742 if (getLangOptions().CPlusPlus) {
6743 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6744 << SourceRange(BuiltinLoc, RPLoc);
6745 return ExprError();
6746 }
6747
Sebastian Redlf53597f2009-03-15 17:47:39 +00006748 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6749 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006750}
6751
Sebastian Redlf53597f2009-03-15 17:47:39 +00006752Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6753 ExprArg cond,
6754 ExprArg expr1, ExprArg expr2,
6755 SourceLocation RPLoc) {
6756 Expr *CondExpr = static_cast<Expr*>(cond.get());
6757 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6758 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006759
Steve Naroffd04fdd52007-08-03 21:21:27 +00006760 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6761
Sebastian Redl28507842009-02-26 14:39:58 +00006762 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006763 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006764 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006765 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006766 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006767 } else {
6768 // The conditional expression is required to be a constant expression.
6769 llvm::APSInt condEval(32);
6770 SourceLocation ExpLoc;
6771 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006772 return ExprError(Diag(ExpLoc,
6773 diag::err_typecheck_choose_expr_requires_constant)
6774 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006775
Sebastian Redl28507842009-02-26 14:39:58 +00006776 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6777 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006778 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6779 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006780 }
6781
Sebastian Redlf53597f2009-03-15 17:47:39 +00006782 cond.release(); expr1.release(); expr2.release();
6783 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006784 resType, RPLoc,
6785 resType->isDependentType(),
6786 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006787}
6788
Steve Naroff4eb206b2008-09-03 18:15:37 +00006789//===----------------------------------------------------------------------===//
6790// Clang Extensions.
6791//===----------------------------------------------------------------------===//
6792
6793/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006794void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006795 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
6796 PushBlockScope(BlockScope, Block);
6797 CurContext->addDecl(Block);
6798 PushDeclContext(BlockScope, Block);
Steve Naroff090276f2008-10-10 01:28:17 +00006799}
6800
Mike Stump98eb8a72009-02-04 22:31:32 +00006801void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006802 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006803 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006804
Mike Stump98eb8a72009-02-04 22:31:32 +00006805 if (ParamInfo.getNumTypeObjects() == 0
6806 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006807 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006808 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6809
Mike Stump4eeab842009-04-28 01:10:27 +00006810 if (T->isArrayType()) {
6811 Diag(ParamInfo.getSourceRange().getBegin(),
6812 diag::err_block_returns_array);
6813 return;
6814 }
6815
Mike Stump98eb8a72009-02-04 22:31:32 +00006816 // The parameter list is optional, if there was none, assume ().
6817 if (!T->isFunctionType())
Rafael Espindola264ba482010-03-30 20:24:48 +00006818 T = Context.getFunctionType(T, 0, 0, false, 0, false, false, 0, 0,
6819 FunctionType::ExtInfo());
Mike Stump98eb8a72009-02-04 22:31:32 +00006820
6821 CurBlock->hasPrototype = true;
6822 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006823 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006824 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006825 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006826 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006827 // FIXME: remove the attribute.
6828 }
John McCall183700f2009-09-21 23:43:11 +00006829 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006830
Chris Lattner9097af12009-04-11 19:27:54 +00006831 // Do not allow returning a objc interface by-value.
6832 if (RetTy->isObjCInterfaceType()) {
6833 Diag(ParamInfo.getSourceRange().getBegin(),
6834 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6835 return;
6836 }
Douglas Gregora873dfc2010-02-03 00:27:59 +00006837
6838 CurBlock->ReturnType = RetTy;
Mike Stump98eb8a72009-02-04 22:31:32 +00006839 return;
6840 }
6841
Steve Naroff4eb206b2008-09-03 18:15:37 +00006842 // Analyze arguments to block.
6843 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6844 "Not a function declarator!");
6845 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006846
Steve Naroff090276f2008-10-10 01:28:17 +00006847 CurBlock->hasPrototype = FTI.hasPrototype;
6848 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006849
Steve Naroff4eb206b2008-09-03 18:15:37 +00006850 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6851 // no arguments, not a function that takes a single void argument.
6852 if (FTI.hasPrototype &&
6853 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006854 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6855 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006856 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006857 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006858 } else if (FTI.hasPrototype) {
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00006859 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6860 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
6861 if (Param->getIdentifier() == 0 &&
6862 !Param->isImplicit() &&
6863 !Param->isInvalidDecl() &&
6864 !getLangOptions().CPlusPlus)
6865 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6866 CurBlock->Params.push_back(Param);
6867 }
Steve Naroff090276f2008-10-10 01:28:17 +00006868 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006869 }
Douglas Gregor838db382010-02-11 01:19:42 +00006870 CurBlock->TheDecl->setParams(CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006871 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006872 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006873 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00006874
6875 bool ShouldCheckShadow =
6876 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
6877
Steve Naroff090276f2008-10-10 01:28:17 +00006878 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00006879 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6880 (*AI)->setOwningFunction(CurBlock->TheDecl);
6881
Steve Naroff090276f2008-10-10 01:28:17 +00006882 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00006883 if ((*AI)->getIdentifier()) {
6884 if (ShouldCheckShadow)
6885 CheckShadow(CurBlock->TheScope, *AI);
6886
Steve Naroff090276f2008-10-10 01:28:17 +00006887 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00006888 }
John McCall7a9813c2010-01-22 00:28:27 +00006889 }
Chris Lattner9097af12009-04-11 19:27:54 +00006890
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006891 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006892 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006893 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006894 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006895 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006896 // FIXME: remove the attribute.
6897 }
Mike Stump1eb44332009-09-09 15:08:12 +00006898
Chris Lattner9097af12009-04-11 19:27:54 +00006899 // Analyze the return type.
6900 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006901 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006902
Chris Lattner9097af12009-04-11 19:27:54 +00006903 // Do not allow returning a objc interface by-value.
6904 if (RetTy->isObjCInterfaceType()) {
6905 Diag(ParamInfo.getSourceRange().getBegin(),
6906 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6907 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006908 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006909}
6910
6911/// ActOnBlockError - If there is an error parsing a block, this callback
6912/// is invoked to pop the information about the block from the action impl.
6913void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006914 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006915 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006916 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006917 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006918}
6919
6920/// ActOnBlockStmtExpr - This is called when the body of a block statement
6921/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006922Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6923 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006924 // If blocks are disabled, emit an error.
6925 if (!LangOpts.Blocks)
6926 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006927
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006928 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006929
Steve Naroff090276f2008-10-10 01:28:17 +00006930 PopDeclContext();
6931
Steve Naroff4eb206b2008-09-03 18:15:37 +00006932 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006933 if (!BSI->ReturnType.isNull())
6934 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006935
Steve Naroff4eb206b2008-09-03 18:15:37 +00006936 llvm::SmallVector<QualType, 8> ArgTypes;
6937 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6938 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006939
Mike Stump56925862009-07-28 22:04:01 +00006940 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006941 QualType BlockTy;
6942 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006943 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00006944 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006945 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006946 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006947 BSI->isVariadic, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00006948 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006949
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006950 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006951 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006952 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006953
Chris Lattner17a78302009-04-19 05:28:12 +00006954 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006955 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner17a78302009-04-19 05:28:12 +00006956 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00006957
Anders Carlssone9146f22009-05-01 19:49:17 +00006958 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00006959
6960 bool Good = true;
6961 // Check goto/label use.
6962 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6963 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6964 LabelStmt *L = I->second;
6965
6966 // Verify that we have no forward references left. If so, there was a goto
6967 // or address of a label taken, but no definition of it.
6968 if (L->getSubStmt() != 0)
6969 continue;
6970
6971 // Emit error.
6972 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6973 Good = false;
6974 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006975 if (!Good) {
6976 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00006977 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006978 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006979
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00006980 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00006981 const sema::AnalysisBasedWarnings::Policy &WP =
6982 AnalysisWarnings.getDefaultPolicy();
6983 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00006984
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006985 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6986 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006987 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006988 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006989}
6990
Sebastian Redlf53597f2009-03-15 17:47:39 +00006991Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6992 ExprArg expr, TypeTy *type,
6993 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006994 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006995 Expr *E = static_cast<Expr*>(expr.get());
6996 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006997
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006998 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006999
7000 // Get the va_list type
7001 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00007002 if (VaListType->isArrayType()) {
7003 // Deal with implicit array decay; for example, on x86-64,
7004 // va_list is an array, but it's supposed to decay to
7005 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007006 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00007007 // Make sure the input expression also decays appropriately.
7008 UsualUnaryConversions(E);
7009 } else {
7010 // Otherwise, the va_list argument must be an l-value because
7011 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00007012 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00007013 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00007014 return ExprError();
7015 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007016
Douglas Gregordd027302009-05-19 23:10:31 +00007017 if (!E->isTypeDependent() &&
7018 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00007019 return ExprError(Diag(E->getLocStart(),
7020 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007021 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00007022 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007023
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007024 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007025 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007026
Sebastian Redlf53597f2009-03-15 17:47:39 +00007027 expr.release();
7028 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
7029 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007030}
7031
Sebastian Redlf53597f2009-03-15 17:47:39 +00007032Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007033 // The type of __null will be int or long, depending on the size of
7034 // pointers on the target.
7035 QualType Ty;
7036 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7037 Ty = Context.IntTy;
7038 else
7039 Ty = Context.LongTy;
7040
Sebastian Redlf53597f2009-03-15 17:47:39 +00007041 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007042}
7043
Douglas Gregor849b2432010-03-31 17:46:05 +00007044static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
7045 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007046 if (!SemaRef.getLangOptions().ObjC1)
7047 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007048
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007049 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7050 if (!PT)
7051 return;
7052
7053 // Check if the destination is of type 'id'.
7054 if (!PT->isObjCIdType()) {
7055 // Check if the destination is the 'NSString' interface.
7056 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7057 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7058 return;
7059 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007060
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007061 // Strip off any parens and casts.
7062 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7063 if (!SL || SL->isWide())
7064 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007065
Douglas Gregor849b2432010-03-31 17:46:05 +00007066 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007067}
7068
Chris Lattner5cf216b2008-01-04 18:04:52 +00007069bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7070 SourceLocation Loc,
7071 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00007072 Expr *SrcExpr, AssignmentAction Action,
7073 bool *Complained) {
7074 if (Complained)
7075 *Complained = false;
7076
Chris Lattner5cf216b2008-01-04 18:04:52 +00007077 // Decode the result (notice that AST's are still created for extensions).
7078 bool isInvalid = false;
7079 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00007080 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007081
Chris Lattner5cf216b2008-01-04 18:04:52 +00007082 switch (ConvTy) {
7083 default: assert(0 && "Unknown conversion type");
7084 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007085 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007086 DiagKind = diag::ext_typecheck_convert_pointer_int;
7087 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007088 case IntToPointer:
7089 DiagKind = diag::ext_typecheck_convert_int_pointer;
7090 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007091 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00007092 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007093 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7094 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007095 case IncompatiblePointerSign:
7096 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7097 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007098 case FunctionVoidPointer:
7099 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7100 break;
7101 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007102 // If the qualifiers lost were because we were applying the
7103 // (deprecated) C++ conversion from a string literal to a char*
7104 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7105 // Ideally, this check would be performed in
7106 // CheckPointerTypesForAssignment. However, that would require a
7107 // bit of refactoring (so that the second argument is an
7108 // expression, rather than a type), which should be done as part
7109 // of a larger effort to fix CheckPointerTypesForAssignment for
7110 // C++ semantics.
7111 if (getLangOptions().CPlusPlus &&
7112 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7113 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007114 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7115 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007116 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007117 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007118 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007119 case IntToBlockPointer:
7120 DiagKind = diag::err_int_to_block_pointer;
7121 break;
7122 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007123 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007124 break;
Steve Naroff39579072008-10-14 22:18:38 +00007125 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007126 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007127 // it can give a more specific diagnostic.
7128 DiagKind = diag::warn_incompatible_qualified_id;
7129 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007130 case IncompatibleVectors:
7131 DiagKind = diag::warn_incompatible_vectors;
7132 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007133 case Incompatible:
7134 DiagKind = diag::err_typecheck_convert_incompatible;
7135 isInvalid = true;
7136 break;
7137 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007138
Douglas Gregord4eea832010-04-09 00:35:39 +00007139 QualType FirstType, SecondType;
7140 switch (Action) {
7141 case AA_Assigning:
7142 case AA_Initializing:
7143 // The destination type comes first.
7144 FirstType = DstType;
7145 SecondType = SrcType;
7146 break;
7147
7148 case AA_Returning:
7149 case AA_Passing:
7150 case AA_Converting:
7151 case AA_Sending:
7152 case AA_Casting:
7153 // The source type comes first.
7154 FirstType = SrcType;
7155 SecondType = DstType;
7156 break;
7157 }
7158
7159 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007160 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00007161 if (Complained)
7162 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007163 return isInvalid;
7164}
Anders Carlssone21555e2008-11-30 19:50:32 +00007165
Chris Lattner3bf68932009-04-25 21:59:05 +00007166bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007167 llvm::APSInt ICEResult;
7168 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7169 if (Result)
7170 *Result = ICEResult;
7171 return false;
7172 }
7173
Anders Carlssone21555e2008-11-30 19:50:32 +00007174 Expr::EvalResult EvalResult;
7175
Mike Stumpeed9cac2009-02-19 03:04:26 +00007176 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007177 EvalResult.HasSideEffects) {
7178 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7179
7180 if (EvalResult.Diag) {
7181 // We only show the note if it's not the usual "invalid subexpression"
7182 // or if it's actually in a subexpression.
7183 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7184 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7185 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7186 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007187
Anders Carlssone21555e2008-11-30 19:50:32 +00007188 return true;
7189 }
7190
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007191 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7192 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007193
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007194 if (EvalResult.Diag &&
7195 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7196 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007197
Anders Carlssone21555e2008-11-30 19:50:32 +00007198 if (Result)
7199 *Result = EvalResult.Val.getInt();
7200 return false;
7201}
Douglas Gregore0762c92009-06-19 23:52:42 +00007202
Douglas Gregor2afce722009-11-26 00:44:06 +00007203void
Mike Stump1eb44332009-09-09 15:08:12 +00007204Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007205 ExprEvalContexts.push_back(
7206 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007207}
7208
Mike Stump1eb44332009-09-09 15:08:12 +00007209void
Douglas Gregor2afce722009-11-26 00:44:06 +00007210Sema::PopExpressionEvaluationContext() {
7211 // Pop the current expression evaluation context off the stack.
7212 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7213 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007214
Douglas Gregor06d33692009-12-12 07:57:52 +00007215 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7216 if (Rec.PotentiallyReferenced) {
7217 // Mark any remaining declarations in the current position of the stack
7218 // as "referenced". If they were not meant to be referenced, semantic
7219 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007220 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007221 I = Rec.PotentiallyReferenced->begin(),
7222 IEnd = Rec.PotentiallyReferenced->end();
7223 I != IEnd; ++I)
7224 MarkDeclarationReferenced(I->first, I->second);
7225 }
7226
7227 if (Rec.PotentiallyDiagnosed) {
7228 // Emit any pending diagnostics.
7229 for (PotentiallyEmittedDiagnostics::iterator
7230 I = Rec.PotentiallyDiagnosed->begin(),
7231 IEnd = Rec.PotentiallyDiagnosed->end();
7232 I != IEnd; ++I)
7233 Diag(I->first, I->second);
7234 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007235 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007236
7237 // When are coming out of an unevaluated context, clear out any
7238 // temporaries that we may have created as part of the evaluation of
7239 // the expression in that context: they aren't relevant because they
7240 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007241 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007242 ExprTemporaries.size() > Rec.NumTemporaries)
7243 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7244 ExprTemporaries.end());
7245
7246 // Destroy the popped expression evaluation record.
7247 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007248}
Douglas Gregore0762c92009-06-19 23:52:42 +00007249
7250/// \brief Note that the given declaration was referenced in the source code.
7251///
7252/// This routine should be invoke whenever a given declaration is referenced
7253/// in the source code, and where that reference occurred. If this declaration
7254/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7255/// C99 6.9p3), then the declaration will be marked as used.
7256///
7257/// \param Loc the location where the declaration was referenced.
7258///
7259/// \param D the declaration that has been referenced by the source code.
7260void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7261 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007262
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007263 if (D->isUsed())
7264 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007265
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007266 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7267 // template or not. The reason for this is that unevaluated expressions
7268 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7269 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007270 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007271 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007272 D->setUsed(true);
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007273 return;
7274 }
7275
7276 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7277 return;
7278
Douglas Gregore0762c92009-06-19 23:52:42 +00007279 // Do not mark anything as "used" within a dependent context; wait for
7280 // an instantiation.
7281 if (CurContext->isDependentContext())
7282 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007283
Douglas Gregor2afce722009-11-26 00:44:06 +00007284 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007285 case Unevaluated:
7286 // We are in an expression that is not potentially evaluated; do nothing.
7287 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007288
Douglas Gregorac7610d2009-06-22 20:57:11 +00007289 case PotentiallyEvaluated:
7290 // We are in a potentially-evaluated expression, so this declaration is
7291 // "used"; handle this below.
7292 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007293
Douglas Gregorac7610d2009-06-22 20:57:11 +00007294 case PotentiallyPotentiallyEvaluated:
7295 // We are in an expression that may be potentially evaluated; queue this
7296 // declaration reference until we know whether the expression is
7297 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007298 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007299 return;
7300 }
Mike Stump1eb44332009-09-09 15:08:12 +00007301
Douglas Gregore0762c92009-06-19 23:52:42 +00007302 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007304 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007305 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7306 if (!Constructor->isUsed())
7307 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007308 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007309 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007310 if (!Constructor->isUsed())
7311 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7312 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007313
Anders Carlssond6a637f2009-12-07 08:24:59 +00007314 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007315 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7316 if (Destructor->isImplicit() && !Destructor->isUsed())
7317 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007318
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007319 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7320 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7321 MethodDecl->getOverloadedOperator() == OO_Equal) {
7322 if (!MethodDecl->isUsed())
7323 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7324 }
7325 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007326 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007327 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007328 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007329 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007330 bool AlreadyInstantiated = false;
7331 if (FunctionTemplateSpecializationInfo *SpecInfo
7332 = Function->getTemplateSpecializationInfo()) {
7333 if (SpecInfo->getPointOfInstantiation().isInvalid())
7334 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007335 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007336 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007337 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007338 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007339 = Function->getMemberSpecializationInfo()) {
7340 if (MSInfo->getPointOfInstantiation().isInvalid())
7341 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007342 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007343 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007344 AlreadyInstantiated = true;
7345 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007346
Douglas Gregor60406be2010-01-16 22:29:39 +00007347 if (!AlreadyInstantiated) {
7348 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7349 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7350 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7351 Loc));
7352 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007353 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007354 Loc));
7355 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007356 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007357
Douglas Gregore0762c92009-06-19 23:52:42 +00007358 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007359 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007360
Douglas Gregore0762c92009-06-19 23:52:42 +00007361 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007362 }
Mike Stump1eb44332009-09-09 15:08:12 +00007363
Douglas Gregore0762c92009-06-19 23:52:42 +00007364 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007365 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007366 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007367 Var->getInstantiatedFromStaticDataMember()) {
7368 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7369 assert(MSInfo && "Missing member specialization information?");
7370 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7371 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7372 MSInfo->setPointOfInstantiation(Loc);
7373 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7374 }
7375 }
Mike Stump1eb44332009-09-09 15:08:12 +00007376
Douglas Gregore0762c92009-06-19 23:52:42 +00007377 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007378
Douglas Gregore0762c92009-06-19 23:52:42 +00007379 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007380 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007381 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007382}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007383
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007384/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7385/// of the program being compiled.
7386///
7387/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007388/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007389/// possibility that the code will actually be executable. Code in sizeof()
7390/// expressions, code used only during overload resolution, etc., are not
7391/// potentially evaluated. This routine will suppress such diagnostics or,
7392/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007393/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007394/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007395///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007396/// This routine should be used for all diagnostics that describe the run-time
7397/// behavior of a program, such as passing a non-POD value through an ellipsis.
7398/// Failure to do so will likely result in spurious diagnostics or failures
7399/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007400bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007401 const PartialDiagnostic &PD) {
7402 switch (ExprEvalContexts.back().Context ) {
7403 case Unevaluated:
7404 // The argument will never be evaluated, so don't complain.
7405 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007406
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007407 case PotentiallyEvaluated:
7408 Diag(Loc, PD);
7409 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007410
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007411 case PotentiallyPotentiallyEvaluated:
7412 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7413 break;
7414 }
7415
7416 return false;
7417}
7418
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007419bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7420 CallExpr *CE, FunctionDecl *FD) {
7421 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7422 return false;
7423
7424 PartialDiagnostic Note =
7425 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7426 << FD->getDeclName() : PDiag();
7427 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007428
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007429 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007430 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007431 PDiag(diag::err_call_function_incomplete_return)
7432 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007433 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007434 << CE->getSourceRange(),
7435 std::make_pair(NoteLoc, Note)))
7436 return true;
7437
7438 return false;
7439}
7440
John McCall5a881bb2009-10-12 21:59:07 +00007441// Diagnose the common s/=/==/ typo. Note that adding parentheses
7442// will prevent this condition from triggering, which is what we want.
7443void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7444 SourceLocation Loc;
7445
John McCalla52ef082009-11-11 02:41:58 +00007446 unsigned diagnostic = diag::warn_condition_is_assignment;
7447
John McCall5a881bb2009-10-12 21:59:07 +00007448 if (isa<BinaryOperator>(E)) {
7449 BinaryOperator *Op = cast<BinaryOperator>(E);
7450 if (Op->getOpcode() != BinaryOperator::Assign)
7451 return;
7452
John McCallc8d8ac52009-11-12 00:06:05 +00007453 // Greylist some idioms by putting them into a warning subcategory.
7454 if (ObjCMessageExpr *ME
7455 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7456 Selector Sel = ME->getSelector();
7457
John McCallc8d8ac52009-11-12 00:06:05 +00007458 // self = [<foo> init...]
7459 if (isSelfExpr(Op->getLHS())
7460 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7461 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7462
7463 // <foo> = [<bar> nextObject]
7464 else if (Sel.isUnarySelector() &&
7465 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7466 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7467 }
John McCalla52ef082009-11-11 02:41:58 +00007468
John McCall5a881bb2009-10-12 21:59:07 +00007469 Loc = Op->getOperatorLoc();
7470 } else if (isa<CXXOperatorCallExpr>(E)) {
7471 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7472 if (Op->getOperator() != OO_Equal)
7473 return;
7474
7475 Loc = Op->getOperatorLoc();
7476 } else {
7477 // Not an assignment.
7478 return;
7479 }
7480
John McCall5a881bb2009-10-12 21:59:07 +00007481 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007482 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007483
Douglas Gregor55b38842010-04-14 16:09:52 +00007484 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00007485 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00007486 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00007487 Diag(Loc, diag::note_condition_assign_silence)
7488 << FixItHint::CreateInsertion(Open, "(")
7489 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00007490}
7491
7492bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7493 DiagnoseAssignmentAsCondition(E);
7494
7495 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007496 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007497
7498 QualType T = E->getType();
7499
7500 if (getLangOptions().CPlusPlus) {
7501 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7502 return true;
7503 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7504 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7505 << T << E->getSourceRange();
7506 return true;
7507 }
7508 }
7509
7510 return false;
7511}