blob: cc94050a6f9eb6d1836e4a44bf62fab913a7b8a7 [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000043
Sebastian Redl14b0c192011-09-24 17:48:00 +000044/// \brief Determine whether the use of this declaration is valid, without
45/// emitting diagnostics.
46bool Sema::CanUseDecl(NamedDecl *D) {
47 // See if this is an auto-typed variable whose initializer we are parsing.
48 if (ParsingInitForAutoVars.count(D))
49 return false;
50
51 // See if this is a deleted function.
52 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53 if (FD->isDeleted())
54 return false;
55 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000056
57 // See if this function is unavailable.
58 if (D->getAvailability() == AR_Unavailable &&
59 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
60 return false;
61
Sebastian Redl14b0c192011-09-24 17:48:00 +000062 return true;
63}
David Chisnall0f436562009-08-17 16:35:33 +000064
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000065static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
66 NamedDecl *D, SourceLocation Loc,
67 const ObjCInterfaceDecl *UnknownObjCClass) {
68 // See if this declaration is unavailable or deprecated.
69 std::string Message;
70 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000071 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
72 if (Result == AR_Available) {
73 const DeclContext *DC = ECD->getDeclContext();
74 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
75 Result = TheEnumDecl->getAvailability(&Message);
76 }
77
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000078 switch (Result) {
79 case AR_Available:
80 case AR_NotYetIntroduced:
81 break;
82
83 case AR_Deprecated:
84 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
85 break;
86
87 case AR_Unavailable:
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000088 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 if (Message.empty()) {
90 if (!UnknownObjCClass)
91 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
92 else
93 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
94 << D->getDeclName();
95 }
96 else
97 S.Diag(Loc, diag::err_unavailable_message)
98 << D->getDeclName() << Message;
99 S.Diag(D->getLocation(), diag::note_unavailable_here)
100 << isa<FunctionDecl>(D) << false;
101 }
102 break;
103 }
104 return Result;
105}
106
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000107/// \brief Determine whether the use of this declaration is valid, and
108/// emit any corresponding diagnostics.
109///
110/// This routine diagnoses various problems with referencing
111/// declarations that can occur when using a declaration. For example,
112/// it might warn if a deprecated or unavailable declaration is being
113/// used, or produce an error (and return true) if a C++0x deleted
114/// function is being used.
115///
116/// \returns true if there was an error (this declaration cannot be
117/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000118///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000119bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000120 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000121 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
122 // If there were any diagnostics suppressed by template argument deduction,
123 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000125 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
126 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000128 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
129 Diag(Suppressed[I].first, Suppressed[I].second);
130
131 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000132 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000133 // entry from the table, because we want to avoid ever emitting these
134 // diagnostics again.
135 Suppressed.clear();
136 }
137 }
138
Richard Smith34b41d92011-02-20 03:19:35 +0000139 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000140 if (ParsingInitForAutoVars.count(D)) {
141 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
142 << D->getDeclName();
143 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000144 }
145
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000146 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000147 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000148 if (FD->isDeleted()) {
149 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +0000150 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000151 return true;
152 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000153 }
Fariborz Jahanian70f30c52011-11-28 19:56:36 +0000154 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000155
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000156 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000157 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000158 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000159 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000160}
161
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000162/// \brief Retrieve the message suffix that should be added to a
163/// diagnostic complaining about the given function being deleted or
164/// unavailable.
165std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
166 // FIXME: C++0x implicitly-deleted special member functions could be
167 // detected here so that we could improve diagnostics to say, e.g.,
168 // "base class 'A' had a deleted copy constructor".
169 if (FD->isDeleted())
170 return std::string();
171
172 std::string Message;
173 if (FD->getAvailability(&Message))
174 return ": " + Message;
175
176 return std::string();
177}
178
John McCall3323fad2011-09-09 07:56:05 +0000179/// DiagnoseSentinelCalls - This routine checks whether a call or
180/// message-send is to a declaration with the sentinel attribute, and
181/// if so, it checks that the requirements of the sentinel are
182/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000183void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000184 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000185 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000186 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000187 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000188
John McCall3323fad2011-09-09 07:56:05 +0000189 // The number of formal parameters of the declaration.
190 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000191
John McCall3323fad2011-09-09 07:56:05 +0000192 // The kind of declaration. This is also an index into a %select in
193 // the diagnostic.
194 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
195
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000196 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000197 numFormalParams = MD->param_size();
198 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000199 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000200 numFormalParams = FD->param_size();
201 calleeType = CT_Function;
202 } else if (isa<VarDecl>(D)) {
203 QualType type = cast<ValueDecl>(D)->getType();
204 const FunctionType *fn = 0;
205 if (const PointerType *ptr = type->getAs<PointerType>()) {
206 fn = ptr->getPointeeType()->getAs<FunctionType>();
207 if (!fn) return;
208 calleeType = CT_Function;
209 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
210 fn = ptr->getPointeeType()->castAs<FunctionType>();
211 calleeType = CT_Block;
212 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000213 return;
John McCall3323fad2011-09-09 07:56:05 +0000214 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000215
John McCall3323fad2011-09-09 07:56:05 +0000216 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
217 numFormalParams = proto->getNumArgs();
218 } else {
219 numFormalParams = 0;
220 }
221 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000222 return;
223 }
John McCall3323fad2011-09-09 07:56:05 +0000224
225 // "nullPos" is the number of formal parameters at the end which
226 // effectively count as part of the variadic arguments. This is
227 // useful if you would prefer to not have *any* formal parameters,
228 // but the language forces you to have at least one.
229 unsigned nullPos = attr->getNullPos();
230 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
231 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
232
233 // The number of arguments which should follow the sentinel.
234 unsigned numArgsAfterSentinel = attr->getSentinel();
235
236 // If there aren't enough arguments for all the formal parameters,
237 // the sentinel, and the args after the sentinel, complain.
238 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000239 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000240 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000241 return;
242 }
John McCall3323fad2011-09-09 07:56:05 +0000243
244 // Otherwise, find the sentinel expression.
245 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000246 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000247 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000248
249 // nullptr_t is always treated as null.
250 if (sentinelExpr->getType()->isNullPtrType()) return;
251
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000252 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000253 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
254 Expr::NPC_ValueDependentIsNull))
255 return;
256
257 // Unfortunately, __null has type 'int'.
258 if (isa<GNUNullExpr>(sentinelExpr)) return;
259
John McCall3323fad2011-09-09 07:56:05 +0000260 // Pick a reasonable string to insert. Optimistically use 'nil' or
261 // 'NULL' if those are actually defined in the context. Only use
262 // 'nil' for ObjC methods, where it's much more likely that the
263 // variadic arguments form a list of object pointers.
264 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000265 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
266 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000267 if (calleeType == CT_Method &&
268 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000269 NullValue = "nil";
270 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
271 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000272 else
John McCall3323fad2011-09-09 07:56:05 +0000273 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000274
275 if (MissingNilLoc.isInvalid())
276 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
277 else
278 Diag(MissingNilLoc, diag::warn_missing_sentinel)
279 << calleeType
280 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000281 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000282}
283
Richard Trieuccd891a2011-09-09 01:45:06 +0000284SourceRange Sema::getExprRange(Expr *E) const {
285 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000286}
287
Chris Lattnere7a2e912008-07-25 21:10:04 +0000288//===----------------------------------------------------------------------===//
289// Standard Promotions and Conversions
290//===----------------------------------------------------------------------===//
291
Chris Lattnere7a2e912008-07-25 21:10:04 +0000292/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000293ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000294 // Handle any placeholder expressions which made it here.
295 if (E->getType()->isPlaceholderType()) {
296 ExprResult result = CheckPlaceholderExpr(E);
297 if (result.isInvalid()) return ExprError();
298 E = result.take();
299 }
300
Chris Lattnere7a2e912008-07-25 21:10:04 +0000301 QualType Ty = E->getType();
302 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
303
Chris Lattnere7a2e912008-07-25 21:10:04 +0000304 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000305 E = ImpCastExprToType(E, Context.getPointerType(Ty),
306 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000307 else if (Ty->isArrayType()) {
308 // In C90 mode, arrays only promote to pointers if the array expression is
309 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
310 // type 'array of type' is converted to an expression that has type 'pointer
311 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
312 // that has type 'array of type' ...". The relevant change is "an lvalue"
313 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000314 //
315 // C++ 4.2p1:
316 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
317 // T" can be converted to an rvalue of type "pointer to T".
318 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000319 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000320 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
321 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000322 }
John Wiegley429bb272011-04-08 18:41:53 +0000323 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000324}
325
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000326static void CheckForNullPointerDereference(Sema &S, Expr *E) {
327 // Check to see if we are dereferencing a null pointer. If so,
328 // and if not volatile-qualified, this is undefined behavior that the
329 // optimizer will delete, so warn about it. People sometimes try to use this
330 // to get a deterministic trap and are surprised by clang's behavior. This
331 // only handles the pattern "*null", which is a very syntactic check.
332 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
333 if (UO->getOpcode() == UO_Deref &&
334 UO->getSubExpr()->IgnoreParenCasts()->
335 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
336 !UO->getType().isVolatileQualified()) {
337 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
338 S.PDiag(diag::warn_indirection_through_null)
339 << UO->getSubExpr()->getSourceRange());
340 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
341 S.PDiag(diag::note_indirection_through_null));
342 }
343}
344
John Wiegley429bb272011-04-08 18:41:53 +0000345ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000346 // Handle any placeholder expressions which made it here.
347 if (E->getType()->isPlaceholderType()) {
348 ExprResult result = CheckPlaceholderExpr(E);
349 if (result.isInvalid()) return ExprError();
350 E = result.take();
351 }
352
John McCall0ae287a2010-12-01 04:43:34 +0000353 // C++ [conv.lval]p1:
354 // A glvalue of a non-function, non-array type T can be
355 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000356 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000357
John McCall409fa9a2010-12-06 20:48:59 +0000358 QualType T = E->getType();
359 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000360
Eli Friedmanb001de72011-10-06 23:00:33 +0000361 // We can't do lvalue-to-rvalue on atomics yet.
John McCall3c3b7f92011-10-25 17:37:35 +0000362 if (T->isAtomicType())
Eli Friedmanb001de72011-10-06 23:00:33 +0000363 return Owned(E);
364
John McCall409fa9a2010-12-06 20:48:59 +0000365 // We don't want to throw lvalue-to-rvalue casts on top of
366 // expressions of certain types in C++.
367 if (getLangOptions().CPlusPlus &&
368 (E->getType() == Context.OverloadTy ||
369 T->isDependentType() ||
370 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000371 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000372
373 // The C standard is actually really unclear on this point, and
374 // DR106 tells us what the result should be but not why. It's
375 // generally best to say that void types just doesn't undergo
376 // lvalue-to-rvalue at all. Note that expressions of unqualified
377 // 'void' type are never l-values, but qualified void can be.
378 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000379 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000380
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000381 CheckForNullPointerDereference(*this, E);
382
John McCall409fa9a2010-12-06 20:48:59 +0000383 // C++ [conv.lval]p1:
384 // [...] If T is a non-class type, the type of the prvalue is the
385 // cv-unqualified version of T. Otherwise, the type of the
386 // rvalue is T.
387 //
388 // C99 6.3.2.1p2:
389 // If the lvalue has qualified type, the value has the unqualified
390 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000391 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000392 if (T.hasQualifiers())
393 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000394
395 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
396 E, 0, VK_RValue));
397
398 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000399}
400
John Wiegley429bb272011-04-08 18:41:53 +0000401ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
402 ExprResult Res = DefaultFunctionArrayConversion(E);
403 if (Res.isInvalid())
404 return ExprError();
405 Res = DefaultLvalueConversion(Res.take());
406 if (Res.isInvalid())
407 return ExprError();
408 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000409}
410
411
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000413/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000414/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000415/// apply if the array is an argument to the sizeof or address (&) operators.
416/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000417ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000418 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000419 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
420 if (Res.isInvalid())
421 return Owned(E);
422 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000423
John McCall0ae287a2010-12-01 04:43:34 +0000424 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000425 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000426
427 // Half FP is a bit different: it's a storage-only type, meaning that any
428 // "use" of it should be promoted to float.
429 if (Ty->isHalfType())
430 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
431
John McCall0ae287a2010-12-01 04:43:34 +0000432 // Try to perform integral promotions if the object has a theoretically
433 // promotable type.
434 if (Ty->isIntegralOrUnscopedEnumerationType()) {
435 // C99 6.3.1.1p2:
436 //
437 // The following may be used in an expression wherever an int or
438 // unsigned int may be used:
439 // - an object or expression with an integer type whose integer
440 // conversion rank is less than or equal to the rank of int
441 // and unsigned int.
442 // - A bit-field of type _Bool, int, signed int, or unsigned int.
443 //
444 // If an int can represent all values of the original type, the
445 // value is converted to an int; otherwise, it is converted to an
446 // unsigned int. These are called the integer promotions. All
447 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000448
John McCall0ae287a2010-12-01 04:43:34 +0000449 QualType PTy = Context.isPromotableBitField(E);
450 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000451 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
452 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000453 }
454 if (Ty->isPromotableIntegerType()) {
455 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000456 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
457 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000458 }
Eli Friedman04e83572009-08-20 04:21:42 +0000459 }
John Wiegley429bb272011-04-08 18:41:53 +0000460 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000461}
462
Chris Lattner05faf172008-07-25 22:25:12 +0000463/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000464/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000465/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000466ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
467 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000468 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000469
John Wiegley429bb272011-04-08 18:41:53 +0000470 ExprResult Res = UsualUnaryConversions(E);
471 if (Res.isInvalid())
472 return Owned(E);
473 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000474
Chris Lattner05faf172008-07-25 22:25:12 +0000475 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000476 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000477 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
478
John McCall96a914a2011-08-27 22:06:17 +0000479 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000480 // promotion, even on class types, but note:
481 // C++11 [conv.lval]p2:
482 // When an lvalue-to-rvalue conversion occurs in an unevaluated
483 // operand or a subexpression thereof the value contained in the
484 // referenced object is not accessed. Otherwise, if the glvalue
485 // has a class type, the conversion copy-initializes a temporary
486 // of type T from the glvalue and the result of the conversion
487 // is a prvalue for the temporary.
488 // FIXME: add some way to gate this entire thing for correctness in
489 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000490 if (getLangOptions().CPlusPlus && E->isGLValue() &&
491 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000492 ExprResult Temp = PerformCopyInitialization(
493 InitializedEntity::InitializeTemporary(E->getType()),
494 E->getExprLoc(),
495 Owned(E));
496 if (Temp.isInvalid())
497 return ExprError();
498 E = Temp.get();
499 }
500
John Wiegley429bb272011-04-08 18:41:53 +0000501 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000502}
503
Chris Lattner312531a2009-04-12 08:11:20 +0000504/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
505/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000506/// interfaces passed by value.
507ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000508 FunctionDecl *FDecl) {
John McCall5acb0c92011-10-17 18:40:02 +0000509 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
510 // Strip the unbridged-cast placeholder expression off, if applicable.
511 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
512 (CT == VariadicMethod ||
513 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
514 E = stripARCUnbridgedCast(E);
515
516 // Otherwise, do normal placeholder checking.
517 } else {
518 ExprResult ExprRes = CheckPlaceholderExpr(E);
519 if (ExprRes.isInvalid())
520 return ExprError();
521 E = ExprRes.take();
522 }
523 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000524
John McCall5acb0c92011-10-17 18:40:02 +0000525 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000526 if (ExprRes.isInvalid())
527 return ExprError();
528 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000530 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000531 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000532 DiagRuntimeBehavior(E->getLocStart(), 0,
533 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
534 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000535 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000536
Douglas Gregorb8e778d2011-10-14 20:34:19 +0000537 // Complain about passing non-POD types through varargs. However, don't
538 // perform this check for incomplete types, which we can get here when we're
539 // in an unevaluated context.
540 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000541 // C++0x [expr.call]p7:
542 // Passing a potentially-evaluated argument of class type (Clause 9)
543 // having a non-trivial copy constructor, a non-trivial move constructor,
544 // or a non-trivial destructor, with no corresponding parameter,
545 // is conditionally-supported with implementation-defined semantics.
546 bool TrivialEnough = false;
547 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
548 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
549 if (Record->hasTrivialCopyConstructor() &&
550 Record->hasTrivialMoveConstructor() &&
Richard Smithebaf0e62011-10-18 20:49:44 +0000551 Record->hasTrivialDestructor()) {
552 DiagRuntimeBehavior(E->getLocStart(), 0,
553 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
554 << E->getType() << CT);
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000555 TrivialEnough = true;
Richard Smithebaf0e62011-10-18 20:49:44 +0000556 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000557 }
558 }
John McCallf85e1932011-06-15 23:02:42 +0000559
560 if (!TrivialEnough &&
561 getLangOptions().ObjCAutoRefCount &&
562 E->getType()->isObjCLifetimeType())
563 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000564
565 if (TrivialEnough) {
566 // Nothing to diagnose. This is okay.
567 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000568 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000569 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000570 << CT)) {
571 // Turn this into a trap.
572 CXXScopeSpec SS;
573 UnqualifiedId Name;
574 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
575 E->getLocStart());
576 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
577 if (TrapFn.isInvalid())
578 return ExprError();
579
580 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
581 MultiExprArg(), E->getLocEnd());
582 if (Call.isInvalid())
583 return ExprError();
584
585 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
586 Call.get(), E);
587 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000588 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000589 E = Comma.get();
590 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000591 }
592
John Wiegley429bb272011-04-08 18:41:53 +0000593 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000594}
595
Richard Trieu8289f492011-09-02 20:58:51 +0000596/// \brief Converts an integer to complex float type. Helper function of
597/// UsualArithmeticConversions()
598///
599/// \return false if the integer expression is an integer type and is
600/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000601static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
602 ExprResult &ComplexExpr,
603 QualType IntTy,
604 QualType ComplexTy,
605 bool SkipCast) {
606 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
607 if (SkipCast) return false;
608 if (IntTy->isIntegerType()) {
609 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
610 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
611 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000612 CK_FloatingRealToComplex);
613 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000614 assert(IntTy->isComplexIntegerType());
615 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000616 CK_IntegralComplexToFloatingComplex);
617 }
618 return false;
619}
620
621/// \brief Takes two complex float types and converts them to the same type.
622/// Helper function of UsualArithmeticConversions()
623static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000624handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
625 ExprResult &RHS, QualType LHSType,
626 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000627 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000628 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000629
630 if (order < 0) {
631 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000632 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000633 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
634 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000635 }
636 if (order > 0)
637 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000638 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
639 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000640}
641
642/// \brief Converts otherExpr to complex float and promotes complexExpr if
643/// necessary. Helper function of UsualArithmeticConversions()
644static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000645 ExprResult &ComplexExpr,
646 ExprResult &OtherExpr,
647 QualType ComplexTy,
648 QualType OtherTy,
649 bool ConvertComplexExpr,
650 bool ConvertOtherExpr) {
651 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000652
653 // If just the complexExpr is complex, the otherExpr needs to be converted,
654 // and the complexExpr might need to be promoted.
655 if (order > 0) { // complexExpr is wider
656 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000657 if (ConvertOtherExpr) {
658 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
659 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
660 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000661 CK_FloatingRealToComplex);
662 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000663 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000664 }
665
666 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000667 QualType result = (order == 0 ? ComplexTy :
668 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000669
670 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000671 if (ConvertOtherExpr)
672 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000673 CK_FloatingRealToComplex);
674
675 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000676 if (ConvertComplexExpr && order < 0)
677 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000678 CK_FloatingComplexCast);
679
680 return result;
681}
682
683/// \brief Handle arithmetic conversion with complex types. Helper function of
684/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000685static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
686 ExprResult &RHS, QualType LHSType,
687 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000688 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000689 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000690 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000691 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000692 return LHSType;
693 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000694 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000695 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000696
697 // This handles complex/complex, complex/float, or float/complex.
698 // When both operands are complex, the shorter operand is converted to the
699 // type of the longer, and that is the type of the result. This corresponds
700 // to what is done when combining two real floating-point operands.
701 // The fun begins when size promotion occur across type domains.
702 // From H&S 6.3.4: When one operand is complex and the other is a real
703 // floating-point type, the less precise type is converted, within it's
704 // real or complex domain, to the precision of the other type. For example,
705 // when combining a "long double" with a "double _Complex", the
706 // "double _Complex" is promoted to "long double _Complex".
707
Richard Trieucafd30b2011-09-06 18:25:09 +0000708 bool LHSComplexFloat = LHSType->isComplexType();
709 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000710
711 // If both are complex, just cast to the more precise type.
712 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000713 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
714 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000715 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000716
717 // If only one operand is complex, promote it if necessary and convert the
718 // other operand to complex.
719 if (LHSComplexFloat)
720 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000721 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000722 /*convertOtherExpr*/ true);
723
724 assert(RHSComplexFloat);
725 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000726 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000727 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000728}
729
730/// \brief Hande arithmetic conversion from integer to float. Helper function
731/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000732static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
733 ExprResult &IntExpr,
734 QualType FloatTy, QualType IntTy,
735 bool ConvertFloat, bool ConvertInt) {
736 if (IntTy->isIntegerType()) {
737 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000738 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000739 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000740 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000741 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000742 }
743
744 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000745 assert(IntTy->isComplexIntegerType());
746 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000747
748 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000749 if (ConvertInt)
750 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000751 CK_IntegralComplexToFloatingComplex);
752
753 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000754 if (ConvertFloat)
755 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000756 CK_FloatingRealToComplex);
757
758 return result;
759}
760
761/// \brief Handle arithmethic conversion with floating point types. Helper
762/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000763static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
764 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000765 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000766 bool LHSFloat = LHSType->isRealFloatingType();
767 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000768
769 // If we have two real floating types, convert the smaller operand
770 // to the bigger result.
771 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000772 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000773 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000774 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
775 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000776 }
777
778 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783
784 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000785 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000786 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000787 /*convertInt=*/ true);
788 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000789 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000790 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000791 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000792}
793
794/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000795/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000796// FIXME: if the operands are (int, _Complex long), we currently
797// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000798static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
799 ExprResult &RHS, QualType LHSType,
800 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000801 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000802 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
803 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000804
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000805 if (LHSComplexInt && RHSComplexInt) {
806 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
807 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000808 assert(order && "inequal types with equal element ordering");
809 if (order > 0) {
810 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000811 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
812 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000813 }
814
Richard Trieuccd891a2011-09-09 01:45:06 +0000815 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000816 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
817 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000818 }
819
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000820 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000821 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000822 // FIXME: This needs to take integer ranks into account
823 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
824 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000825 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
826 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000827 }
828
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000829 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000830 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000831 // FIXME: This needs to take integer ranks into account
832 if (!IsCompAssign) {
833 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
834 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000835 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000836 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000837 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000838}
839
840/// \brief Handle integer arithmetic conversions. Helper function of
841/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000842static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
843 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000844 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000845 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000846 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
847 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
848 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
849 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000850 // Same signedness; use the higher-ranked type
851 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000852 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
853 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000854 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000855 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
856 return RHSType;
857 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000858 // The unsigned type has greater than or equal rank to the
859 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000860 if (RHSSigned) {
861 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
862 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000863 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000864 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
865 return RHSType;
866 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000867 // The two types are different widths; if we are here, that
868 // means the signed type is larger than the unsigned type, so
869 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000870 if (LHSSigned) {
871 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
872 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000873 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000874 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
875 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000876 } else {
877 // The signed type is higher-ranked than the unsigned type,
878 // but isn't actually any bigger (like unsigned int and long
879 // on most 32-bit systems). Use the unsigned type corresponding
880 // to the signed type.
881 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000882 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
883 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000884 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000885 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000886 return result;
887 }
888}
889
Chris Lattnere7a2e912008-07-25 21:10:04 +0000890/// UsualArithmeticConversions - Performs various conversions that are common to
891/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000892/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000893/// responsible for emitting appropriate error diagnostics.
894/// FIXME: verify the conversion rules for "complex int" are consistent with
895/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000896QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000897 bool IsCompAssign) {
898 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000899 LHS = UsualUnaryConversions(LHS.take());
900 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000901 return QualType();
902 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000903
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000904 RHS = UsualUnaryConversions(RHS.take());
905 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000906 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000907
Mike Stump1eb44332009-09-09 15:08:12 +0000908 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000909 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000910 QualType LHSType =
911 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
912 QualType RHSType =
913 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000914
915 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000916 if (LHSType == RHSType)
917 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000918
919 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
920 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000921 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
922 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000923
John McCallcf33b242010-11-13 08:17:45 +0000924 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000925 QualType LHSUnpromotedType = LHSType;
926 if (LHSType->isPromotableIntegerType())
927 LHSType = Context.getPromotedIntegerType(LHSType);
928 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000929 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000930 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000931 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000932 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000933
John McCallcf33b242010-11-13 08:17:45 +0000934 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000935 if (LHSType == RHSType)
936 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000937
938 // At this point, we have two different arithmetic types.
939
940 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000941 if (LHSType->isComplexType() || RHSType->isComplexType())
942 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000943 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000944
945 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000946 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
947 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000948 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000949
950 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000951 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000952 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000953 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000954
955 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000956 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000957 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000958}
959
Chris Lattnere7a2e912008-07-25 21:10:04 +0000960//===----------------------------------------------------------------------===//
961// Semantic Analysis for various Expression Types
962//===----------------------------------------------------------------------===//
963
964
Peter Collingbournef111d932011-04-15 00:35:48 +0000965ExprResult
966Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
967 SourceLocation DefaultLoc,
968 SourceLocation RParenLoc,
969 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000970 MultiTypeArg ArgTypes,
971 MultiExprArg ArgExprs) {
972 unsigned NumAssocs = ArgTypes.size();
973 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000974
Richard Trieuccd891a2011-09-09 01:45:06 +0000975 ParsedType *ParsedTypes = ArgTypes.release();
976 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000977
978 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
979 for (unsigned i = 0; i < NumAssocs; ++i) {
980 if (ParsedTypes[i])
981 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
982 else
983 Types[i] = 0;
984 }
985
986 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
987 ControllingExpr, Types, Exprs,
988 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000989 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000990 return ER;
991}
992
993ExprResult
994Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
995 SourceLocation DefaultLoc,
996 SourceLocation RParenLoc,
997 Expr *ControllingExpr,
998 TypeSourceInfo **Types,
999 Expr **Exprs,
1000 unsigned NumAssocs) {
1001 bool TypeErrorFound = false,
1002 IsResultDependent = ControllingExpr->isTypeDependent(),
1003 ContainsUnexpandedParameterPack
1004 = ControllingExpr->containsUnexpandedParameterPack();
1005
1006 for (unsigned i = 0; i < NumAssocs; ++i) {
1007 if (Exprs[i]->containsUnexpandedParameterPack())
1008 ContainsUnexpandedParameterPack = true;
1009
1010 if (Types[i]) {
1011 if (Types[i]->getType()->containsUnexpandedParameterPack())
1012 ContainsUnexpandedParameterPack = true;
1013
1014 if (Types[i]->getType()->isDependentType()) {
1015 IsResultDependent = true;
1016 } else {
1017 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1018 // complete object type other than a variably modified type."
1019 unsigned D = 0;
1020 if (Types[i]->getType()->isIncompleteType())
1021 D = diag::err_assoc_type_incomplete;
1022 else if (!Types[i]->getType()->isObjectType())
1023 D = diag::err_assoc_type_nonobject;
1024 else if (Types[i]->getType()->isVariablyModifiedType())
1025 D = diag::err_assoc_type_variably_modified;
1026
1027 if (D != 0) {
1028 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1029 << Types[i]->getTypeLoc().getSourceRange()
1030 << Types[i]->getType();
1031 TypeErrorFound = true;
1032 }
1033
1034 // C1X 6.5.1.1p2 "No two generic associations in the same generic
1035 // selection shall specify compatible types."
1036 for (unsigned j = i+1; j < NumAssocs; ++j)
1037 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1038 Context.typesAreCompatible(Types[i]->getType(),
1039 Types[j]->getType())) {
1040 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1041 diag::err_assoc_compatible_types)
1042 << Types[j]->getTypeLoc().getSourceRange()
1043 << Types[j]->getType()
1044 << Types[i]->getType();
1045 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1046 diag::note_compat_assoc)
1047 << Types[i]->getTypeLoc().getSourceRange()
1048 << Types[i]->getType();
1049 TypeErrorFound = true;
1050 }
1051 }
1052 }
1053 }
1054 if (TypeErrorFound)
1055 return ExprError();
1056
1057 // If we determined that the generic selection is result-dependent, don't
1058 // try to compute the result expression.
1059 if (IsResultDependent)
1060 return Owned(new (Context) GenericSelectionExpr(
1061 Context, KeyLoc, ControllingExpr,
1062 Types, Exprs, NumAssocs, DefaultLoc,
1063 RParenLoc, ContainsUnexpandedParameterPack));
1064
Chris Lattner5f9e2722011-07-23 10:55:15 +00001065 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001066 unsigned DefaultIndex = -1U;
1067 for (unsigned i = 0; i < NumAssocs; ++i) {
1068 if (!Types[i])
1069 DefaultIndex = i;
1070 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1071 Types[i]->getType()))
1072 CompatIndices.push_back(i);
1073 }
1074
1075 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1076 // type compatible with at most one of the types named in its generic
1077 // association list."
1078 if (CompatIndices.size() > 1) {
1079 // We strip parens here because the controlling expression is typically
1080 // parenthesized in macro definitions.
1081 ControllingExpr = ControllingExpr->IgnoreParens();
1082 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1083 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1084 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001085 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001086 E = CompatIndices.end(); I != E; ++I) {
1087 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1088 diag::note_compat_assoc)
1089 << Types[*I]->getTypeLoc().getSourceRange()
1090 << Types[*I]->getType();
1091 }
1092 return ExprError();
1093 }
1094
1095 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1096 // its controlling expression shall have type compatible with exactly one of
1097 // the types named in its generic association list."
1098 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1099 // We strip parens here because the controlling expression is typically
1100 // parenthesized in macro definitions.
1101 ControllingExpr = ControllingExpr->IgnoreParens();
1102 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1103 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1104 return ExprError();
1105 }
1106
1107 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1108 // type name that is compatible with the type of the controlling expression,
1109 // then the result expression of the generic selection is the expression
1110 // in that generic association. Otherwise, the result expression of the
1111 // generic selection is the expression in the default generic association."
1112 unsigned ResultIndex =
1113 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1114
1115 return Owned(new (Context) GenericSelectionExpr(
1116 Context, KeyLoc, ControllingExpr,
1117 Types, Exprs, NumAssocs, DefaultLoc,
1118 RParenLoc, ContainsUnexpandedParameterPack,
1119 ResultIndex));
1120}
1121
Steve Narofff69936d2007-09-16 03:34:24 +00001122/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001123/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1124/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1125/// multiple tokens. However, the common case is that StringToks points to one
1126/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001127///
John McCall60d7b3a2010-08-24 06:29:42 +00001128ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001129Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 assert(NumStringToks && "Must have at least one string!");
1131
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001132 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001134 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001135
Chris Lattner5f9e2722011-07-23 10:55:15 +00001136 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 for (unsigned i = 0; i != NumStringToks; ++i)
1138 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001139
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001140 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001141 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001142 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001143 else if (Literal.isUTF16())
1144 StrTy = Context.Char16Ty;
1145 else if (Literal.isUTF32())
1146 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001147 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001148 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001149
Douglas Gregor5cee1192011-07-27 05:40:30 +00001150 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1151 if (Literal.isWide())
1152 Kind = StringLiteral::Wide;
1153 else if (Literal.isUTF8())
1154 Kind = StringLiteral::UTF8;
1155 else if (Literal.isUTF16())
1156 Kind = StringLiteral::UTF16;
1157 else if (Literal.isUTF32())
1158 Kind = StringLiteral::UTF32;
1159
Douglas Gregor77a52232008-09-12 00:47:35 +00001160 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001161 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001162 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001163
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001164 // Get an array type for the string, according to C99 6.4.5. This includes
1165 // the nul terminator character as well as the string length for pascal
1166 // strings.
1167 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001168 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001169 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001172 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001173 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001174 &StringTokLocs[0],
1175 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001176}
1177
John McCall469a1eb2011-02-02 13:00:07 +00001178enum CaptureResult {
1179 /// No capture is required.
1180 CR_NoCapture,
1181
1182 /// A capture is required.
1183 CR_Capture,
1184
John McCall6b5a61b2011-02-07 10:33:21 +00001185 /// A by-ref capture is required.
1186 CR_CaptureByRef,
1187
John McCall469a1eb2011-02-02 13:00:07 +00001188 /// An error occurred when trying to capture the given variable.
1189 CR_Error
1190};
1191
1192/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001193///
John McCall469a1eb2011-02-02 13:00:07 +00001194/// \param var - the variable referenced
1195/// \param DC - the context which we couldn't capture through
1196static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001197diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001198 VarDecl *var, DeclContext *DC) {
1199 switch (S.ExprEvalContexts.back().Context) {
1200 case Sema::Unevaluated:
1201 // The argument will never be evaluated, so don't complain.
1202 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001203
John McCall469a1eb2011-02-02 13:00:07 +00001204 case Sema::PotentiallyEvaluated:
1205 case Sema::PotentiallyEvaluatedIfUsed:
1206 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001207
John McCall469a1eb2011-02-02 13:00:07 +00001208 case Sema::PotentiallyPotentiallyEvaluated:
1209 // FIXME: delay these!
1210 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
John McCall469a1eb2011-02-02 13:00:07 +00001213 // Don't diagnose about capture if we're not actually in code right
1214 // now; in general, there are more appropriate places that will
1215 // diagnose this.
1216 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1217
John McCall4f38f412011-03-22 23:15:50 +00001218 // Certain madnesses can happen with parameter declarations, which
1219 // we want to ignore.
1220 if (isa<ParmVarDecl>(var)) {
1221 // - If the parameter still belongs to the translation unit, then
1222 // we're actually just using one parameter in the declaration of
1223 // the next. This is useful in e.g. VLAs.
1224 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1225 return CR_NoCapture;
1226
1227 // - This particular madness can happen in ill-formed default
1228 // arguments; claim it's okay and let downstream code handle it.
1229 if (S.CurContext == var->getDeclContext()->getParent())
1230 return CR_NoCapture;
1231 }
John McCall469a1eb2011-02-02 13:00:07 +00001232
1233 DeclarationName functionName;
1234 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1235 functionName = fn->getDeclName();
1236 // FIXME: variable from enclosing block that we couldn't capture from!
1237
1238 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1239 << var->getIdentifier() << functionName;
1240 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1241 << var->getIdentifier();
1242
1243 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001244}
1245
John McCall6b5a61b2011-02-07 10:33:21 +00001246/// There is a well-formed capture at a particular scope level;
1247/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001248static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1249 const BlockDecl::Capture &Capture) {
1250 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001251
1252 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001253 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001254 i != e; ++i) {
1255 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1256 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001257 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1258 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001259 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1260 }
1261
Richard Trieuccd891a2011-09-09 01:45:06 +00001262 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001263}
1264
1265/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001266/// given value in the current context requires a variable capture.
1267///
1268/// This also keeps the captures set in the BlockScopeInfo records
1269/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001270static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001271 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001272 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001273 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001274 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001275
1276 // Fast path: variables from the current context never require capture.
1277 DeclContext *DC = S.CurContext;
1278 if (var->getDeclContext() == DC) return CR_NoCapture;
1279
1280 // Only variables with local storage require capture.
1281 // FIXME: What about 'const' variables in C++?
1282 if (!var->hasLocalStorage()) return CR_NoCapture;
1283
1284 // Otherwise, we need to capture.
1285
1286 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001287 do {
1288 // Only blocks (and eventually C++0x closures) can capture; other
1289 // scopes don't work.
1290 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001291 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001292
1293 BlockScopeInfo *blockScope =
1294 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1295 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1296
John McCall6b5a61b2011-02-07 10:33:21 +00001297 // Check whether we've already captured it in this block. If so,
1298 // we're done.
1299 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1300 return propagateCapture(S, functionScopesIndex,
1301 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001302
1303 functionScopesIndex--;
1304 DC = cast<BlockDecl>(DC)->getDeclContext();
1305 } while (var->getDeclContext() != DC);
1306
John McCall6b5a61b2011-02-07 10:33:21 +00001307 // Okay, we descended all the way to the block that defines the variable.
1308 // Actually try to capture it.
1309 QualType type = var->getType();
Fariborz Jahanian05053212011-11-01 18:57:34 +00001310
John McCall6b5a61b2011-02-07 10:33:21 +00001311 // Prohibit variably-modified types.
1312 if (type->isVariablyModifiedType()) {
1313 S.Diag(loc, diag::err_ref_vm_type);
1314 S.Diag(var->getLocation(), diag::note_declared_at);
1315 return CR_Error;
1316 }
1317
1318 // Prohibit arrays, even in __block variables, but not references to
1319 // them.
1320 if (type->isArrayType()) {
1321 S.Diag(loc, diag::err_ref_array_type);
1322 S.Diag(var->getLocation(), diag::note_declared_at);
1323 return CR_Error;
1324 }
1325
1326 S.MarkDeclarationReferenced(loc, var);
1327
1328 // The BlocksAttr indicates the variable is bound by-reference.
1329 bool byRef = var->hasAttr<BlocksAttr>();
1330
1331 // Build a copy expression.
1332 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001333 const RecordType *rtype;
1334 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1335 (rtype = type->getAs<RecordType>())) {
1336
1337 // The capture logic needs the destructor, so make sure we mark it.
1338 // Usually this is unnecessary because most local variables have
1339 // their destructors marked at declaration time, but parameters are
1340 // an exception because it's technically only the call site that
1341 // actually requires the destructor.
1342 if (isa<ParmVarDecl>(var))
1343 S.FinalizeVarWithDestructor(var, rtype);
1344
John McCall6b5a61b2011-02-07 10:33:21 +00001345 // According to the blocks spec, the capture of a variable from
1346 // the stack requires a const copy constructor. This is not true
1347 // of the copy/move done to move a __block variable to the heap.
1348 type.addConst();
1349
1350 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1351 ExprResult result =
1352 S.PerformCopyInitialization(
1353 InitializedEntity::InitializeBlock(var->getLocation(),
1354 type, false),
1355 loc, S.Owned(declRef));
1356
1357 // Build a full-expression copy expression if initialization
1358 // succeeded and used a non-trivial constructor. Recover from
1359 // errors by pretending that the copy isn't necessary.
1360 if (!result.isInvalid() &&
1361 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1362 result = S.MaybeCreateExprWithCleanups(result);
1363 copyExpr = result.take();
1364 }
1365 }
1366
1367 // We're currently at the declarer; go back to the closure.
1368 functionScopesIndex++;
1369 BlockScopeInfo *blockScope =
1370 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1371
1372 // Build a valid capture in this scope.
1373 blockScope->Captures.push_back(
1374 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1375 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1376
1377 // Propagate that to inner captures if necessary.
1378 return propagateCapture(S, functionScopesIndex,
1379 blockScope->Captures.back());
1380}
1381
Richard Trieuccd891a2011-09-09 01:45:06 +00001382static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001383 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001384 bool ByRef) {
1385 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001386
Richard Trieuccd891a2011-09-09 01:45:06 +00001387 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001388 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001389 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001390
1391 QualType exprType = var->getType().getNonReferenceType();
1392
1393 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001394 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001395 // The variable will be bound by copy; make it const within the
1396 // closure, but record that this was done in the expression.
1397 bool constAdded = !exprType.isConstQualified();
1398 exprType.addConst();
1399
1400 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1401 NameInfo.getLoc(), false,
1402 constAdded);
1403 } else {
1404 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1405 NameInfo.getLoc(), true);
1406 }
1407
1408 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001409}
Chris Lattner639e2d32008-10-20 05:16:36 +00001410
John McCall60d7b3a2010-08-24 06:29:42 +00001411ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001412Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001413 SourceLocation Loc,
1414 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001415 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001416 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001417}
1418
John McCall76a40212011-02-09 01:13:10 +00001419/// BuildDeclRefExpr - Build an expression that references a
1420/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001421ExprResult
John McCall76a40212011-02-09 01:13:10 +00001422Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001423 const DeclarationNameInfo &NameInfo,
1424 const CXXScopeSpec *SS) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001425 if (getLangOptions().CUDA)
1426 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1427 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1428 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1429 CalleeTarget = IdentifyCUDATarget(Callee);
1430 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1431 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1432 << CalleeTarget << D->getIdentifier() << CallerTarget;
1433 Diag(D->getLocation(), diag::note_previous_decl)
1434 << D->getIdentifier();
1435 return ExprError();
1436 }
1437 }
1438
Abramo Bagnara25777432010-08-11 22:01:17 +00001439 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCall7eb0a9e2010-11-24 05:12:34 +00001441 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001442 SS? SS->getWithLocInContext(Context)
1443 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001444 D, NameInfo, Ty, VK);
1445
1446 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001447 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1448 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001449 E->setObjectKind(OK_BitField);
1450
1451 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001452}
1453
Abramo Bagnara25777432010-08-11 22:01:17 +00001454/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001455/// possibly a list of template arguments.
1456///
1457/// If this produces template arguments, it is permitted to call
1458/// DecomposeTemplateName.
1459///
1460/// This actually loses a lot of source location information for
1461/// non-standard name kinds; we should consider preserving that in
1462/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001463void
1464Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1465 TemplateArgumentListInfo &Buffer,
1466 DeclarationNameInfo &NameInfo,
1467 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001468 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1469 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1470 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1471
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001473 Id.TemplateId->getTemplateArgs(),
1474 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001475 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001476 TemplateArgsPtr.release();
1477
John McCall2b5289b2010-08-23 07:28:44 +00001478 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001479 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001480 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001481 TemplateArgs = &Buffer;
1482 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001483 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001484 TemplateArgs = 0;
1485 }
1486}
1487
John McCall578b69b2009-12-16 08:11:27 +00001488/// Diagnose an empty lookup.
1489///
1490/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001491bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001492 CorrectTypoContext CTC,
1493 TemplateArgumentListInfo *ExplicitTemplateArgs,
1494 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001495 DeclarationName Name = R.getLookupName();
1496
John McCall578b69b2009-12-16 08:11:27 +00001497 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001498 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001499 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1500 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001501 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001502 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001503 diagnostic_suggest = diag::err_undeclared_use_suggest;
1504 }
John McCall578b69b2009-12-16 08:11:27 +00001505
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001506 // If the original lookup was an unqualified lookup, fake an
1507 // unqualified lookup. This is useful when (for example) the
1508 // original lookup would not have found something because it was a
1509 // dependent name.
Francois Pichetc8ff9152011-11-25 01:10:54 +00001510 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1511 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001512 if (isa<CXXRecordDecl>(DC)) {
1513 LookupQualifiedName(R, DC);
1514
1515 if (!R.empty()) {
1516 // Don't give errors about ambiguities in this lookup.
1517 R.suppressDiagnostics();
1518
Francois Pichete6226ae2011-11-17 03:44:24 +00001519 // During a default argument instantiation the CurContext points
1520 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1521 // function parameter list, hence add an explicit check.
1522 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1523 ActiveTemplateInstantiations.back().Kind ==
1524 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001525 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1526 bool isInstance = CurMethod &&
1527 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001528 DC == CurMethod->getParent() && !isDefaultArgument;
1529
John McCall578b69b2009-12-16 08:11:27 +00001530
1531 // Give a code modification hint to insert 'this->'.
1532 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1533 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001534 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001535 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1536 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001537 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001538 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001539 if (DepMethod) {
Francois Pichete614d6c2011-11-15 23:33:34 +00001540 if (getLangOptions().MicrosoftMode)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001541 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001542 Diag(R.getNameLoc(), diagnostic) << Name
1543 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1544 QualType DepThisType = DepMethod->getThisType(Context);
1545 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546 R.getNameLoc(), DepThisType, false);
1547 TemplateArgumentListInfo TList;
1548 if (ULE->hasExplicitTemplateArgs())
1549 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001550
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001551 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001552 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001553 CXXDependentScopeMemberExpr *DepExpr =
1554 CXXDependentScopeMemberExpr::Create(
1555 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001556 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001557 R.getLookupNameInfo(),
1558 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001559 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001560 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001561 // FIXME: we should be able to handle this case too. It is correct
1562 // to add this-> here. This is a workaround for PR7947.
1563 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001564 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001565 } else {
Francois Pichete614d6c2011-11-15 23:33:34 +00001566 if (getLangOptions().MicrosoftMode)
1567 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCall578b69b2009-12-16 08:11:27 +00001568 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001569 }
John McCall578b69b2009-12-16 08:11:27 +00001570
1571 // Do we really want to note all of these?
1572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1573 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1574
Francois Pichete6226ae2011-11-17 03:44:24 +00001575 // Return true if we are inside a default argument instantiation
1576 // and the found name refers to an instance member function, otherwise
1577 // the function calling DiagnoseEmptyLookup will try to create an
1578 // implicit member call and this is wrong for default argument.
1579 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1580 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1581 return true;
1582 }
1583
John McCall578b69b2009-12-16 08:11:27 +00001584 // Tell the callee to try to recover.
1585 return false;
1586 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001587
1588 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001589 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001590
1591 // In Microsoft mode, if we are performing lookup from within a friend
1592 // function definition declared at class scope then we must set
1593 // DC to the lexical parent to be able to search into the parent
1594 // class.
Lang Hames36ef7022011-11-29 22:37:13 +00001595 if (getLangOptions().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001596 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1597 DC->getLexicalParent()->isRecord())
1598 DC = DC->getLexicalParent();
1599 else
1600 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001601 }
1602
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001603 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001604 TypoCorrection Corrected;
1605 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1606 S, &SS, NULL, false, CTC))) {
1607 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1608 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1609 R.setLookupName(Corrected.getCorrection());
1610
Hans Wennborg701d1e72011-07-12 08:45:31 +00001611 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001612 if (Corrected.isOverloaded()) {
1613 OverloadCandidateSet OCS(R.getNameLoc());
1614 OverloadCandidateSet::iterator Best;
1615 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1616 CDEnd = Corrected.end();
1617 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001618 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001619 dyn_cast<FunctionTemplateDecl>(*CD))
1620 AddTemplateOverloadCandidate(
1621 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1622 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001623 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1624 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1625 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1626 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001627 }
1628 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1629 case OR_Success:
1630 ND = Best->Function;
1631 break;
1632 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001633 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001634 }
1635 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001636 R.addDecl(ND);
1637 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001638 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001639 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1640 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001641 else
1642 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001643 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001644 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001645 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1646 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001647 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001648 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001649
1650 // Tell the callee to try to recover.
1651 return false;
1652 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001653
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001654 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001655 // FIXME: If we ended up with a typo for a type name or
1656 // Objective-C class name, we're in trouble because the parser
1657 // is in the wrong place to recover. Suggest the typo
1658 // correction, but don't make it a fix-it since we're not going
1659 // to recover well anyway.
1660 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001661 Diag(R.getNameLoc(), diagnostic_suggest)
1662 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001663 else
1664 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001665 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001666 << SS.getRange();
1667
1668 // Don't try to recover; it won't work.
1669 return true;
1670 }
1671 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001672 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001673 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001674 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001675 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001676 else
Douglas Gregord203a162010-01-01 00:15:04 +00001677 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001678 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001679 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001680 return true;
1681 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001682 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001683 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001684
1685 // Emit a special diagnostic for failed member lookups.
1686 // FIXME: computing the declaration context might fail here (?)
1687 if (!SS.isEmpty()) {
1688 Diag(R.getNameLoc(), diag::err_no_member)
1689 << Name << computeDeclContext(SS, false)
1690 << SS.getRange();
1691 return true;
1692 }
1693
John McCall578b69b2009-12-16 08:11:27 +00001694 // Give up, we can't recover.
1695 Diag(R.getNameLoc(), diagnostic) << Name;
1696 return true;
1697}
1698
John McCall60d7b3a2010-08-24 06:29:42 +00001699ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001700 CXXScopeSpec &SS,
1701 UnqualifiedId &Id,
1702 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001703 bool IsAddressOfOperand) {
1704 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001705 "cannot be direct & operand and have a trailing lparen");
1706
1707 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001708 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001709
John McCall129e2df2009-11-30 22:42:35 +00001710 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001711
1712 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001713 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001714 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001715 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001716
Abramo Bagnara25777432010-08-11 22:01:17 +00001717 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001718 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001719 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001720
John McCallf7a1a742009-11-24 19:00:30 +00001721 // C++ [temp.dep.expr]p3:
1722 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001723 // -- an identifier that was declared with a dependent type,
1724 // (note: handled after lookup)
1725 // -- a template-id that is dependent,
1726 // (note: handled in BuildTemplateIdExpr)
1727 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001728 // -- a nested-name-specifier that contains a class-name that
1729 // names a dependent type.
1730 // Determine whether this is a member of an unknown specialization;
1731 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001732 bool DependentID = false;
1733 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1734 Name.getCXXNameType()->isDependentType()) {
1735 DependentID = true;
1736 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001737 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001738 if (RequireCompleteDeclContext(SS, DC))
1739 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001740 } else {
1741 DependentID = true;
1742 }
1743 }
1744
Chris Lattner337e5502011-02-18 01:27:55 +00001745 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001746 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001747 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001748
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001749 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001750 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001751 LookupResult R(*this, NameInfo,
1752 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1753 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001755 // Lookup the template name again to correctly establish the context in
1756 // which it was found. This is really unfortunate as we already did the
1757 // lookup to determine that it was a template name in the first place. If
1758 // this becomes a performance hit, we can work harder to preserve those
1759 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001760 bool MemberOfUnknownSpecialization;
1761 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1762 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001763
1764 if (MemberOfUnknownSpecialization ||
1765 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001766 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001767 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001768 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001769 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001770 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001772 // If the result might be in a dependent base class, this is a dependent
1773 // id-expression.
1774 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001775 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001776 TemplateArgs);
1777
John McCallf7a1a742009-11-24 19:00:30 +00001778 // If this reference is in an Objective-C method, then we need to do
1779 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001780 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001781 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001782 if (E.isInvalid())
1783 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Chris Lattner337e5502011-02-18 01:27:55 +00001785 if (Expr *Ex = E.takeAs<Expr>())
1786 return Owned(Ex);
1787
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001788 // for further use, this must be set to false if in class method.
1789 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001790 }
Chris Lattner8a934232008-03-31 00:36:02 +00001791 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001792
John McCallf7a1a742009-11-24 19:00:30 +00001793 if (R.isAmbiguous())
1794 return ExprError();
1795
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001796 // Determine whether this name might be a candidate for
1797 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001798 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001799
John McCallf7a1a742009-11-24 19:00:30 +00001800 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001802 // in C90, extension in C99, forbidden in C++).
1803 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1804 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1805 if (D) R.addDecl(D);
1806 }
1807
1808 // If this name wasn't predeclared and if this is not a function
1809 // call, diagnose the problem.
1810 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001811
1812 // In Microsoft mode, if we are inside a template class member function
1813 // and we can't resolve an identifier then assume the identifier is type
1814 // dependent. The goal is to postpone name lookup to instantiation time
1815 // to be able to search into type dependent base classes.
1816 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1817 isa<CXXMethodDecl>(CurContext))
1818 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1819 TemplateArgs);
1820
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001821 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001822 return ExprError();
1823
1824 assert(!R.empty() &&
1825 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001826
1827 // If we found an Objective-C instance variable, let
1828 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001829 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001830 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1831 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001832 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001833 // In a hopelessly buggy code, Objective-C instance variable
1834 // lookup fails and no expression will be built to reference it.
1835 if (!E.isInvalid() && !E.get())
1836 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001837 return move(E);
1838 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 }
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
John McCallf7a1a742009-11-24 19:00:30 +00001842 // This is guaranteed from this point on.
1843 assert(!R.empty() || ADL);
1844
John McCallaa81e162009-12-01 22:10:20 +00001845 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001846 // C++ [class.mfct.non-static]p3:
1847 // When an id-expression that is not part of a class member access
1848 // syntax and not used to form a pointer to member is used in the
1849 // body of a non-static member function of class X, if name lookup
1850 // resolves the name in the id-expression to a non-static non-type
1851 // member of some class C, the id-expression is transformed into a
1852 // class member access expression using (*this) as the
1853 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001854 //
1855 // But we don't actually need to do this for '&' operands if R
1856 // resolved to a function or overloaded function set, because the
1857 // expression is ill-formed if it actually works out to be a
1858 // non-static member function:
1859 //
1860 // C++ [expr.ref]p4:
1861 // Otherwise, if E1.E2 refers to a non-static member function. . .
1862 // [t]he expression can be used only as the left-hand operand of a
1863 // member function call.
1864 //
1865 // There are other safeguards against such uses, but it's important
1866 // to get this right here so that we don't end up making a
1867 // spuriously dependent expression if we're inside a dependent
1868 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001869 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001870 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001871 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001872 MightBeImplicitMember = true;
1873 else if (!SS.isEmpty())
1874 MightBeImplicitMember = false;
1875 else if (R.isOverloadedResult())
1876 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001877 else if (R.isUnresolvableResult())
1878 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001879 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001880 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1881 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001882
1883 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001884 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001885 }
1886
John McCallf7a1a742009-11-24 19:00:30 +00001887 if (TemplateArgs)
1888 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001889
John McCallf7a1a742009-11-24 19:00:30 +00001890 return BuildDeclarationNameExpr(SS, R, ADL);
1891}
1892
John McCall129e2df2009-11-30 22:42:35 +00001893/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1894/// declaration name, generally during template instantiation.
1895/// There's a large number of things which don't need to be done along
1896/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001897ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001898Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001899 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001900 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001901 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001902 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001903
John McCall77bb1aa2010-05-01 00:40:08 +00001904 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001905 return ExprError();
1906
Abramo Bagnara25777432010-08-11 22:01:17 +00001907 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001908 LookupQualifiedName(R, DC);
1909
1910 if (R.isAmbiguous())
1911 return ExprError();
1912
1913 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001914 Diag(NameInfo.getLoc(), diag::err_no_member)
1915 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001916 return ExprError();
1917 }
1918
1919 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1920}
1921
1922/// LookupInObjCMethod - The parser has read a name in, and Sema has
1923/// detected that we're currently inside an ObjC method. Perform some
1924/// additional lookup.
1925///
1926/// Ideally, most of this would be done by lookup, but there's
1927/// actually quite a lot of extra work involved.
1928///
1929/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001930ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001931Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001932 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001933 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001934 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001935
John McCallf7a1a742009-11-24 19:00:30 +00001936 // There are two cases to handle here. 1) scoped lookup could have failed,
1937 // in which case we should look for an ivar. 2) scoped lookup could have
1938 // found a decl, but that decl is outside the current instance method (i.e.
1939 // a global variable). In these two cases, we do a lookup for an ivar with
1940 // this name, if the lookup sucedes, we replace it our current decl.
1941
1942 // If we're in a class method, we don't normally want to look for
1943 // ivars. But if we don't find anything else, and there's an
1944 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001945 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001946
1947 bool LookForIvars;
1948 if (Lookup.empty())
1949 LookForIvars = true;
1950 else if (IsClassMethod)
1951 LookForIvars = false;
1952 else
1953 LookForIvars = (Lookup.isSingleResult() &&
1954 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001955 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001956 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001957 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001958 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001959 ObjCIvarDecl *IV = 0;
1960 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001961 // Diagnose using an ivar in a class method.
1962 if (IsClassMethod)
1963 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1964 << IV->getDeclName());
1965
1966 // If we're referencing an invalid decl, just return this as a silent
1967 // error node. The error diagnostic was already emitted on the decl.
1968 if (IV->isInvalidDecl())
1969 return ExprError();
1970
1971 // Check if referencing a field with __attribute__((deprecated)).
1972 if (DiagnoseUseOfDecl(IV, Loc))
1973 return ExprError();
1974
1975 // Diagnose the use of an ivar outside of the declaring class.
1976 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1977 ClassDeclared != IFace)
1978 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1979
1980 // FIXME: This should use a new expr for a direct reference, don't
1981 // turn this into Self->ivar, just return a BareIVarExpr or something.
1982 IdentifierInfo &II = Context.Idents.get("self");
1983 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001984 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001985 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001986 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001987 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001988 SelfName, false, false);
1989 if (SelfExpr.isInvalid())
1990 return ExprError();
1991
John Wiegley429bb272011-04-08 18:41:53 +00001992 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1993 if (SelfExpr.isInvalid())
1994 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001995
John McCallf7a1a742009-11-24 19:00:30 +00001996 MarkDeclarationReferenced(Loc, IV);
1997 return Owned(new (Context)
1998 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001999 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002000 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002001 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002002 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002003 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2004 ObjCInterfaceDecl *ClassDeclared;
2005 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2006 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2007 IFace == ClassDeclared)
2008 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2009 }
John McCallf7a1a742009-11-24 19:00:30 +00002010 }
2011 }
2012
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002013 if (Lookup.empty() && II && AllowBuiltinCreation) {
2014 // FIXME. Consolidate this with similar code in LookupName.
2015 if (unsigned BuiltinID = II->getBuiltinID()) {
2016 if (!(getLangOptions().CPlusPlus &&
2017 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2018 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2019 S, Lookup.isForRedeclaration(),
2020 Lookup.getNameLoc());
2021 if (D) Lookup.addDecl(D);
2022 }
2023 }
2024 }
John McCallf7a1a742009-11-24 19:00:30 +00002025 // Sentinel value saying that we didn't do anything special.
2026 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002027}
John McCallba135432009-11-21 08:51:07 +00002028
John McCall6bb80172010-03-30 21:47:33 +00002029/// \brief Cast a base object to a member's actual type.
2030///
2031/// Logically this happens in three phases:
2032///
2033/// * First we cast from the base type to the naming class.
2034/// The naming class is the class into which we were looking
2035/// when we found the member; it's the qualifier type if a
2036/// qualifier was provided, and otherwise it's the base type.
2037///
2038/// * Next we cast from the naming class to the declaring class.
2039/// If the member we found was brought into a class's scope by
2040/// a using declaration, this is that class; otherwise it's
2041/// the class declaring the member.
2042///
2043/// * Finally we cast from the declaring class to the "true"
2044/// declaring class of the member. This conversion does not
2045/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002046ExprResult
2047Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002048 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002049 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002050 NamedDecl *Member) {
2051 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2052 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002053 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002054
Douglas Gregor5fccd362010-03-03 23:55:11 +00002055 QualType DestRecordType;
2056 QualType DestType;
2057 QualType FromRecordType;
2058 QualType FromType = From->getType();
2059 bool PointerConversions = false;
2060 if (isa<FieldDecl>(Member)) {
2061 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002062
Douglas Gregor5fccd362010-03-03 23:55:11 +00002063 if (FromType->getAs<PointerType>()) {
2064 DestType = Context.getPointerType(DestRecordType);
2065 FromRecordType = FromType->getPointeeType();
2066 PointerConversions = true;
2067 } else {
2068 DestType = DestRecordType;
2069 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002070 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002071 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2072 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002073 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002074
Douglas Gregor5fccd362010-03-03 23:55:11 +00002075 DestType = Method->getThisType(Context);
2076 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002077
Douglas Gregor5fccd362010-03-03 23:55:11 +00002078 if (FromType->getAs<PointerType>()) {
2079 FromRecordType = FromType->getPointeeType();
2080 PointerConversions = true;
2081 } else {
2082 FromRecordType = FromType;
2083 DestType = DestRecordType;
2084 }
2085 } else {
2086 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002087 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002088 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002089
Douglas Gregor5fccd362010-03-03 23:55:11 +00002090 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002091 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002092
Douglas Gregor5fccd362010-03-03 23:55:11 +00002093 // If the unqualified types are the same, no conversion is necessary.
2094 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002095 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002096
John McCall6bb80172010-03-30 21:47:33 +00002097 SourceRange FromRange = From->getSourceRange();
2098 SourceLocation FromLoc = FromRange.getBegin();
2099
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002100 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002101
Douglas Gregor5fccd362010-03-03 23:55:11 +00002102 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002103 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002104 // class name.
2105 //
2106 // If the member was a qualified name and the qualified referred to a
2107 // specific base subobject type, we'll cast to that intermediate type
2108 // first and then to the object in which the member is declared. That allows
2109 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2110 //
2111 // class Base { public: int x; };
2112 // class Derived1 : public Base { };
2113 // class Derived2 : public Base { };
2114 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2115 //
2116 // void VeryDerived::f() {
2117 // x = 17; // error: ambiguous base subobjects
2118 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2119 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002120 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002121 QualType QType = QualType(Qualifier->getAsType(), 0);
2122 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2123 assert(QType->isRecordType() && "lookup done with non-record type");
2124
2125 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2126
2127 // In C++98, the qualifier type doesn't actually have to be a base
2128 // type of the object type, in which case we just ignore it.
2129 // Otherwise build the appropriate casts.
2130 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002131 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002132 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002133 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002134 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002135
Douglas Gregor5fccd362010-03-03 23:55:11 +00002136 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002137 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002138 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2139 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002140
2141 FromType = QType;
2142 FromRecordType = QRecordType;
2143
2144 // If the qualifier type was the same as the destination type,
2145 // we're done.
2146 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002147 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002148 }
2149 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002150
John McCall6bb80172010-03-30 21:47:33 +00002151 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002152
John McCall6bb80172010-03-30 21:47:33 +00002153 // If we actually found the member through a using declaration, cast
2154 // down to the using declaration's type.
2155 //
2156 // Pointer equality is fine here because only one declaration of a
2157 // class ever has member declarations.
2158 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2159 assert(isa<UsingShadowDecl>(FoundDecl));
2160 QualType URecordType = Context.getTypeDeclType(
2161 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2162
2163 // We only need to do this if the naming-class to declaring-class
2164 // conversion is non-trivial.
2165 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2166 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002167 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002168 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002169 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002170 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002171
John McCall6bb80172010-03-30 21:47:33 +00002172 QualType UType = URecordType;
2173 if (PointerConversions)
2174 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002175 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2176 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002177 FromType = UType;
2178 FromRecordType = URecordType;
2179 }
2180
2181 // We don't do access control for the conversion from the
2182 // declaring class to the true declaring class.
2183 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002184 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002185
John McCallf871d0c2010-08-07 06:22:56 +00002186 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002187 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2188 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002189 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002190 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002191
John Wiegley429bb272011-04-08 18:41:53 +00002192 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2193 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002194}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002195
John McCallf7a1a742009-11-24 19:00:30 +00002196bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002197 const LookupResult &R,
2198 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002199 // Only when used directly as the postfix-expression of a call.
2200 if (!HasTrailingLParen)
2201 return false;
2202
2203 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002204 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002205 return false;
2206
2207 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002208 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002209 return false;
2210
2211 // Turn off ADL when we find certain kinds of declarations during
2212 // normal lookup:
2213 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2214 NamedDecl *D = *I;
2215
2216 // C++0x [basic.lookup.argdep]p3:
2217 // -- a declaration of a class member
2218 // Since using decls preserve this property, we check this on the
2219 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002220 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002221 return false;
2222
2223 // C++0x [basic.lookup.argdep]p3:
2224 // -- a block-scope function declaration that is not a
2225 // using-declaration
2226 // NOTE: we also trigger this for function templates (in fact, we
2227 // don't check the decl type at all, since all other decl types
2228 // turn off ADL anyway).
2229 if (isa<UsingShadowDecl>(D))
2230 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2231 else if (D->getDeclContext()->isFunctionOrMethod())
2232 return false;
2233
2234 // C++0x [basic.lookup.argdep]p3:
2235 // -- a declaration that is neither a function or a function
2236 // template
2237 // And also for builtin functions.
2238 if (isa<FunctionDecl>(D)) {
2239 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2240
2241 // But also builtin functions.
2242 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2243 return false;
2244 } else if (!isa<FunctionTemplateDecl>(D))
2245 return false;
2246 }
2247
2248 return true;
2249}
2250
2251
John McCallba135432009-11-21 08:51:07 +00002252/// Diagnoses obvious problems with the use of the given declaration
2253/// as an expression. This is only actually called for lookups that
2254/// were not overloaded, and it doesn't promise that the declaration
2255/// will in fact be used.
2256static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002257 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002258 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2259 return true;
2260 }
2261
2262 if (isa<ObjCInterfaceDecl>(D)) {
2263 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2264 return true;
2265 }
2266
2267 if (isa<NamespaceDecl>(D)) {
2268 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2269 return true;
2270 }
2271
2272 return false;
2273}
2274
John McCall60d7b3a2010-08-24 06:29:42 +00002275ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002276Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002277 LookupResult &R,
2278 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002279 // If this is a single, fully-resolved result and we don't need ADL,
2280 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002281 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002282 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2283 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002284
2285 // We only need to check the declaration if there's exactly one
2286 // result, because in the overloaded case the results can only be
2287 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002288 if (R.isSingleResult() &&
2289 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002290 return ExprError();
2291
John McCallc373d482010-01-27 01:50:18 +00002292 // Otherwise, just build an unresolved lookup expression. Suppress
2293 // any lookup-related diagnostics; we'll hash these out later, when
2294 // we've picked a target.
2295 R.suppressDiagnostics();
2296
John McCallba135432009-11-21 08:51:07 +00002297 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002298 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002299 SS.getWithLocInContext(Context),
2300 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002301 NeedsADL, R.isOverloadedResult(),
2302 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002303
2304 return Owned(ULE);
2305}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002306
John McCallba135432009-11-21 08:51:07 +00002307/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002308ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002309Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002310 const DeclarationNameInfo &NameInfo,
2311 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002312 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002313 assert(!isa<FunctionTemplateDecl>(D) &&
2314 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002315
Abramo Bagnara25777432010-08-11 22:01:17 +00002316 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002317 if (CheckDeclInExpr(*this, Loc, D))
2318 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002319
Douglas Gregor9af2f522009-12-01 16:58:18 +00002320 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2321 // Specifically diagnose references to class templates that are missing
2322 // a template argument list.
2323 Diag(Loc, diag::err_template_decl_ref)
2324 << Template << SS.getRange();
2325 Diag(Template->getLocation(), diag::note_template_decl_here);
2326 return ExprError();
2327 }
2328
2329 // Make sure that we're referring to a value.
2330 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2331 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002332 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002333 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002334 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002335 return ExprError();
2336 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002337
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002338 // Check whether this declaration can be used. Note that we suppress
2339 // this check when we're going to perform argument-dependent lookup
2340 // on this function name, because this might not be the function
2341 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002342 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002343 return ExprError();
2344
Steve Naroffdd972f22008-09-05 22:11:13 +00002345 // Only create DeclRefExpr's for valid Decl's.
2346 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002347 return ExprError();
2348
John McCall5808ce42011-02-03 08:15:49 +00002349 // Handle members of anonymous structs and unions. If we got here,
2350 // and the reference is to a class member indirect field, then this
2351 // must be the subject of a pointer-to-member expression.
2352 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2353 if (!indirectField->isCXXClassMember())
2354 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2355 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002356
Chris Lattner639e2d32008-10-20 05:16:36 +00002357 // If the identifier reference is inside a block, and it refers to a value
2358 // that is outside the block, create a BlockDeclRefExpr instead of a
2359 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2360 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002361 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002362 // We do not do this for things like enum constants, global variables, etc,
2363 // as they do not get snapshotted.
2364 //
John McCall6b5a61b2011-02-07 10:33:21 +00002365 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002366 case CR_Error:
2367 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002368
John McCall469a1eb2011-02-02 13:00:07 +00002369 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002370 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2371 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2372
2373 case CR_CaptureByRef:
2374 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2375 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002376
2377 case CR_NoCapture: {
2378 // If this reference is not in a block or if the referenced
2379 // variable is within the block, create a normal DeclRefExpr.
2380
2381 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002382 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002383
2384 switch (D->getKind()) {
2385 // Ignore all the non-ValueDecl kinds.
2386#define ABSTRACT_DECL(kind)
2387#define VALUE(type, base)
2388#define DECL(type, base) \
2389 case Decl::type:
2390#include "clang/AST/DeclNodes.inc"
2391 llvm_unreachable("invalid value decl kind");
2392 return ExprError();
2393
2394 // These shouldn't make it here.
2395 case Decl::ObjCAtDefsField:
2396 case Decl::ObjCIvar:
2397 llvm_unreachable("forming non-member reference to ivar?");
2398 return ExprError();
2399
2400 // Enum constants are always r-values and never references.
2401 // Unresolved using declarations are dependent.
2402 case Decl::EnumConstant:
2403 case Decl::UnresolvedUsingValue:
2404 valueKind = VK_RValue;
2405 break;
2406
2407 // Fields and indirect fields that got here must be for
2408 // pointer-to-member expressions; we just call them l-values for
2409 // internal consistency, because this subexpression doesn't really
2410 // exist in the high-level semantics.
2411 case Decl::Field:
2412 case Decl::IndirectField:
2413 assert(getLangOptions().CPlusPlus &&
2414 "building reference to field in C?");
2415
2416 // These can't have reference type in well-formed programs, but
2417 // for internal consistency we do this anyway.
2418 type = type.getNonReferenceType();
2419 valueKind = VK_LValue;
2420 break;
2421
2422 // Non-type template parameters are either l-values or r-values
2423 // depending on the type.
2424 case Decl::NonTypeTemplateParm: {
2425 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2426 type = reftype->getPointeeType();
2427 valueKind = VK_LValue; // even if the parameter is an r-value reference
2428 break;
2429 }
2430
2431 // For non-references, we need to strip qualifiers just in case
2432 // the template parameter was declared as 'const int' or whatever.
2433 valueKind = VK_RValue;
2434 type = type.getUnqualifiedType();
2435 break;
2436 }
2437
2438 case Decl::Var:
2439 // In C, "extern void blah;" is valid and is an r-value.
2440 if (!getLangOptions().CPlusPlus &&
2441 !type.hasQualifiers() &&
2442 type->isVoidType()) {
2443 valueKind = VK_RValue;
2444 break;
2445 }
2446 // fallthrough
2447
2448 case Decl::ImplicitParam:
2449 case Decl::ParmVar:
2450 // These are always l-values.
2451 valueKind = VK_LValue;
2452 type = type.getNonReferenceType();
2453 break;
2454
2455 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002456 const FunctionType *fty = type->castAs<FunctionType>();
2457
2458 // If we're referring to a function with an __unknown_anytype
2459 // result type, make the entire expression __unknown_anytype.
2460 if (fty->getResultType() == Context.UnknownAnyTy) {
2461 type = Context.UnknownAnyTy;
2462 valueKind = VK_RValue;
2463 break;
2464 }
2465
John McCall76a40212011-02-09 01:13:10 +00002466 // Functions are l-values in C++.
2467 if (getLangOptions().CPlusPlus) {
2468 valueKind = VK_LValue;
2469 break;
2470 }
2471
2472 // C99 DR 316 says that, if a function type comes from a
2473 // function definition (without a prototype), that type is only
2474 // used for checking compatibility. Therefore, when referencing
2475 // the function, we pretend that we don't have the full function
2476 // type.
John McCall755d8492011-04-12 00:42:48 +00002477 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2478 isa<FunctionProtoType>(fty))
2479 type = Context.getFunctionNoProtoType(fty->getResultType(),
2480 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002481
2482 // Functions are r-values in C.
2483 valueKind = VK_RValue;
2484 break;
2485 }
2486
2487 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002488 // If we're referring to a method with an __unknown_anytype
2489 // result type, make the entire expression __unknown_anytype.
2490 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002491 if (const FunctionProtoType *proto
2492 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002493 if (proto->getResultType() == Context.UnknownAnyTy) {
2494 type = Context.UnknownAnyTy;
2495 valueKind = VK_RValue;
2496 break;
2497 }
2498
John McCall76a40212011-02-09 01:13:10 +00002499 // C++ methods are l-values if static, r-values if non-static.
2500 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2501 valueKind = VK_LValue;
2502 break;
2503 }
2504 // fallthrough
2505
2506 case Decl::CXXConversion:
2507 case Decl::CXXDestructor:
2508 case Decl::CXXConstructor:
2509 valueKind = VK_RValue;
2510 break;
2511 }
2512
2513 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2514 }
2515
John McCall469a1eb2011-02-02 13:00:07 +00002516 }
John McCallf89e55a2010-11-18 06:31:45 +00002517
John McCall6b5a61b2011-02-07 10:33:21 +00002518 llvm_unreachable("unknown capture result");
2519 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002520}
2521
John McCall755d8492011-04-12 00:42:48 +00002522ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002523 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002526 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002527 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2528 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2529 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002531
Chris Lattnerfa28b302008-01-12 08:14:25 +00002532 // Pre-defined identifiers are of type char[x], where x is the length of the
2533 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Anders Carlsson3a082d82009-09-08 18:24:21 +00002535 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002536 if (!currentDecl && getCurBlock())
2537 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002538 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002539 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002540 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002541 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002542
Anders Carlsson773f3972009-09-11 01:22:35 +00002543 QualType ResTy;
2544 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2545 ResTy = Context.DependentTy;
2546 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002547 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002548
Anders Carlsson773f3972009-09-11 01:22:35 +00002549 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002550 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002551 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2552 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002553 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002554}
2555
John McCall60d7b3a2010-08-24 06:29:42 +00002556ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002558 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002560 if (Invalid)
2561 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002562
Benjamin Kramerddeea562010-02-27 13:44:12 +00002563 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002564 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002566 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002567
Chris Lattnere8337df2009-12-30 21:19:39 +00002568 QualType Ty;
2569 if (!getLangOptions().CPlusPlus)
2570 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2571 else if (Literal.isWide())
2572 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002573 else if (Literal.isUTF16())
2574 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2575 else if (Literal.isUTF32())
2576 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002577 else if (Literal.isMultiChar())
2578 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002579 else
2580 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002581
Douglas Gregor5cee1192011-07-27 05:40:30 +00002582 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2583 if (Literal.isWide())
2584 Kind = CharacterLiteral::Wide;
2585 else if (Literal.isUTF16())
2586 Kind = CharacterLiteral::UTF16;
2587 else if (Literal.isUTF32())
2588 Kind = CharacterLiteral::UTF32;
2589
2590 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2591 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002592}
2593
John McCall60d7b3a2010-08-24 06:29:42 +00002594ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002595 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2597 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002598 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002599 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002600 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002601 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 }
Ted Kremenek28396602009-01-13 23:19:12 +00002603
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002605 // Add padding so that NumericLiteralParser can overread by one character.
2606 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002608
Reid Spencer5f016e22007-07-11 17:01:13 +00002609 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002610 bool Invalid = false;
2611 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2612 if (Invalid)
2613 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002614
Mike Stump1eb44332009-09-09 15:08:12 +00002615 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 Tok.getLocation(), PP);
2617 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002618 return ExprError();
2619
Chris Lattner5d661452007-08-26 03:42:43 +00002620 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002621
Chris Lattner5d661452007-08-26 03:42:43 +00002622 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002623 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002624 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002625 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002626 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002627 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002628 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002629 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002630
2631 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2632
John McCall94c939d2009-12-24 09:08:04 +00002633 using llvm::APFloat;
2634 APFloat Val(Format);
2635
2636 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002637
2638 // Overflow is always an error, but underflow is only an error if
2639 // we underflowed to zero (APFloat reports denormals as underflow).
2640 if ((result & APFloat::opOverflow) ||
2641 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002642 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002643 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002644 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002645 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002646 APFloat::getLargest(Format).toString(buffer);
2647 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002648 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002649 APFloat::getSmallest(Format).toString(buffer);
2650 }
2651
2652 Diag(Tok.getLocation(), diagnostic)
2653 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002654 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002655 }
2656
2657 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002658 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002659
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002660 if (Ty == Context.DoubleTy) {
2661 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002662 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002663 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2664 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002665 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002666 }
2667 }
Chris Lattner5d661452007-08-26 03:42:43 +00002668 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002670 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002671 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002672
Neil Boothb9449512007-08-29 22:00:19 +00002673 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +00002674 if (!getLangOptions().C99 && Literal.isLongLong)
2675 Diag(Tok.getLocation(),
2676 getLangOptions().CPlusPlus0x ?
2677 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002678
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002680 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002681
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 if (Literal.GetIntegerValue(ResultVal)) {
2683 // If this value didn't fit into uintmax_t, warn and force to ull.
2684 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002685 Ty = Context.UnsignedLongLongTy;
2686 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002687 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 } else {
2689 // If this value fits into a ULL, try to figure out what else it fits into
2690 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002691
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2693 // be an unsigned int.
2694 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2695
2696 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002697 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002698 if (!Literal.isLong && !Literal.isLongLong) {
2699 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002700 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002701
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 // Does it fit in a unsigned int?
2703 if (ResultVal.isIntN(IntSize)) {
2704 // Does it fit in a signed int?
2705 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002706 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002708 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002709 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002712
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002714 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002715 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002716
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 // Does it fit in a unsigned long?
2718 if (ResultVal.isIntN(LongSize)) {
2719 // Does it fit in a signed long?
2720 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002721 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002723 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002724 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002726 }
2727
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002729 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002730 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 // Does it fit in a unsigned long long?
2733 if (ResultVal.isIntN(LongLongSize)) {
2734 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002735 // To be compatible with MSVC, hex integer literals ending with the
2736 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002737 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet62ec1f22011-09-17 17:15:52 +00002738 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002739 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002741 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002742 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 }
2744 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 // If we still couldn't decide a type, we probably have something that
2747 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002748 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002750 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002751 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002753
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002754 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002755 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002757 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002759
Chris Lattner5d661452007-08-26 03:42:43 +00002760 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2761 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002762 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002763 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002764
2765 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002766}
2767
Richard Trieuccd891a2011-09-09 01:45:06 +00002768ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002769 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002770 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002771}
2772
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002773static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2774 SourceLocation Loc,
2775 SourceRange ArgRange) {
2776 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2777 // scalar or vector data type argument..."
2778 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2779 // type (C99 6.2.5p18) or void.
2780 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2781 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2782 << T << ArgRange;
2783 return true;
2784 }
2785
2786 assert((T->isVoidType() || !T->isIncompleteType()) &&
2787 "Scalar types should always be complete");
2788 return false;
2789}
2790
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002791static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2792 SourceLocation Loc,
2793 SourceRange ArgRange,
2794 UnaryExprOrTypeTrait TraitKind) {
2795 // C99 6.5.3.4p1:
2796 if (T->isFunctionType()) {
2797 // alignof(function) is allowed as an extension.
2798 if (TraitKind == UETT_SizeOf)
2799 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2800 return false;
2801 }
2802
2803 // Allow sizeof(void)/alignof(void) as an extension.
2804 if (T->isVoidType()) {
2805 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2806 return false;
2807 }
2808
2809 return true;
2810}
2811
2812static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2813 SourceLocation Loc,
2814 SourceRange ArgRange,
2815 UnaryExprOrTypeTrait TraitKind) {
2816 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2817 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2818 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2819 << T << (TraitKind == UETT_SizeOf)
2820 << ArgRange;
2821 return true;
2822 }
2823
2824 return false;
2825}
2826
Chandler Carruth9d342d02011-05-26 08:53:10 +00002827/// \brief Check the constrains on expression operands to unary type expression
2828/// and type traits.
2829///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002830/// Completes any types necessary and validates the constraints on the operand
2831/// expression. The logic mostly mirrors the type-based overload, but may modify
2832/// the expression as it completes the type for that expression through template
2833/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002834bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002835 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002836 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002837
2838 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2839 // the result is the size of the referenced type."
2840 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2841 // result shall be the alignment of the referenced type."
2842 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2843 ExprTy = Ref->getPointeeType();
2844
2845 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002846 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2847 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002848
2849 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002850 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2851 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002852 return false;
2853
Richard Trieuccd891a2011-09-09 01:45:06 +00002854 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002855 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002856 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002857 std::make_pair(SourceLocation(), PDiag(0))))
2858 return true;
2859
2860 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002861 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002862 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2863 ExprTy = Ref->getPointeeType();
2864
Richard Trieuccd891a2011-09-09 01:45:06 +00002865 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2866 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002867 return true;
2868
Nico Webercf739922011-06-15 02:47:03 +00002869 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002870 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002871 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2872 QualType OType = PVD->getOriginalType();
2873 QualType Type = PVD->getType();
2874 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002875 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002876 << Type << OType;
2877 Diag(PVD->getLocation(), diag::note_declared_at);
2878 }
2879 }
2880 }
2881 }
2882
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002883 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002884}
2885
2886/// \brief Check the constraints on operands to unary expression and type
2887/// traits.
2888///
2889/// This will complete any types necessary, and validate the various constraints
2890/// on those operands.
2891///
Reid Spencer5f016e22007-07-11 17:01:13 +00002892/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002893/// C99 6.3.2.1p[2-4] all state:
2894/// Except when it is the operand of the sizeof operator ...
2895///
2896/// C++ [expr.sizeof]p4
2897/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2898/// standard conversions are not applied to the operand of sizeof.
2899///
2900/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002901bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002902 SourceLocation OpLoc,
2903 SourceRange ExprRange,
2904 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002905 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002906 return false;
2907
Sebastian Redl5d484e82009-11-23 17:18:46 +00002908 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2909 // the result is the size of the referenced type."
2910 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2911 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002912 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2913 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002914
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002915 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002916 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002917
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002918 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002919 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002920 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002921 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Richard Trieuccd891a2011-09-09 01:45:06 +00002923 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002924 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002925 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002926 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Richard Trieuccd891a2011-09-09 01:45:06 +00002928 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002929 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002930 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Chris Lattner1efaa952009-04-24 00:30:45 +00002932 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002933}
2934
Chandler Carruth9d342d02011-05-26 08:53:10 +00002935static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002936 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002937
Mike Stump1eb44332009-09-09 15:08:12 +00002938 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002939 if (isa<DeclRefExpr>(E))
2940 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002941
2942 // Cannot know anything else if the expression is dependent.
2943 if (E->isTypeDependent())
2944 return false;
2945
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002946 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002947 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2948 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002949 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002950 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002951
2952 // Alignment of a field access is always okay, so long as it isn't a
2953 // bit-field.
2954 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002955 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002956 return false;
2957
Chandler Carruth9d342d02011-05-26 08:53:10 +00002958 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002959}
2960
Chandler Carruth9d342d02011-05-26 08:53:10 +00002961bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002962 E = E->IgnoreParens();
2963
2964 // Cannot know anything else if the expression is dependent.
2965 if (E->isTypeDependent())
2966 return false;
2967
Chandler Carruth9d342d02011-05-26 08:53:10 +00002968 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002969}
2970
Douglas Gregorba498172009-03-13 21:01:28 +00002971/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002972ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002973Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2974 SourceLocation OpLoc,
2975 UnaryExprOrTypeTrait ExprKind,
2976 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002977 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002978 return ExprError();
2979
John McCalla93c9342009-12-07 02:54:59 +00002980 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002981
Douglas Gregorba498172009-03-13 21:01:28 +00002982 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002983 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002984 return ExprError();
2985
2986 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002987 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2988 Context.getSizeType(),
2989 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002990}
2991
2992/// \brief Build a sizeof or alignof expression given an expression
2993/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002994ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002995Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2996 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002997 ExprResult PE = CheckPlaceholderExpr(E);
2998 if (PE.isInvalid())
2999 return ExprError();
3000
3001 E = PE.get();
3002
Douglas Gregorba498172009-03-13 21:01:28 +00003003 // Verify that the operand is valid.
3004 bool isInvalid = false;
3005 if (E->isTypeDependent()) {
3006 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003007 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003008 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003009 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003010 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003011 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003012 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003013 isInvalid = true;
3014 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003015 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003016 }
3017
3018 if (isInvalid)
3019 return ExprError();
3020
3021 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003022 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003023 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003024 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003025}
3026
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003027/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3028/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003029/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003030ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003031Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003032 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003033 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003035 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003036
Richard Trieuccd891a2011-09-09 01:45:06 +00003037 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003038 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003039 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003040 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003041 }
Sebastian Redl05189992008-11-11 17:56:53 +00003042
Douglas Gregorba498172009-03-13 21:01:28 +00003043 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003044 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003045 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003046}
3047
John Wiegley429bb272011-04-08 18:41:53 +00003048static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003049 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003050 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003051 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003052
John McCallf6a16482010-12-04 03:47:34 +00003053 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003054 if (V.get()->getObjectKind() != OK_Ordinary) {
3055 V = S.DefaultLvalueConversion(V.take());
3056 if (V.isInvalid())
3057 return QualType();
3058 }
John McCallf6a16482010-12-04 03:47:34 +00003059
Chris Lattnercc26ed72007-08-26 05:39:26 +00003060 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003061 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003062 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Chris Lattnercc26ed72007-08-26 05:39:26 +00003064 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003065 if (V.get()->getType()->isArithmeticType())
3066 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003067
John McCall2cd11fe2010-10-12 02:09:17 +00003068 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003069 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003070 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003071 if (PR.get() != V.get()) {
3072 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00003073 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003074 }
3075
Chris Lattnercc26ed72007-08-26 05:39:26 +00003076 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003077 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003078 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003079 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003080}
3081
3082
Reid Spencer5f016e22007-07-11 17:01:13 +00003083
John McCall60d7b3a2010-08-24 06:29:42 +00003084ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003085Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003086 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003087 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003088 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003089 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003090 case tok::plusplus: Opc = UO_PostInc; break;
3091 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003093
John McCall9ae2f072010-08-23 23:25:46 +00003094 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003095}
3096
John McCall60d7b3a2010-08-24 06:29:42 +00003097ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003098Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3099 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003100 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003101 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003102 if (Result.isInvalid()) return ExprError();
3103 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003104
John McCall9ae2f072010-08-23 23:25:46 +00003105 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Douglas Gregor337c6b92008-11-19 17:17:41 +00003107 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003108 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003109 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003110 Context.DependentTy,
3111 VK_LValue, OK_Ordinary,
3112 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003113 }
3114
Mike Stump1eb44332009-09-09 15:08:12 +00003115 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003116 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003117 LHSExp->getType()->isEnumeralType() ||
3118 RHSExp->getType()->isRecordType() ||
3119 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003120 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003121 }
3122
John McCall9ae2f072010-08-23 23:25:46 +00003123 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003124}
3125
3126
John McCall60d7b3a2010-08-24 06:29:42 +00003127ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003128Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003129 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003130 Expr *LHSExp = Base;
3131 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003132
Chris Lattner12d9ff62007-07-16 00:14:47 +00003133 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003134 if (!LHSExp->getType()->getAs<VectorType>()) {
3135 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3136 if (Result.isInvalid())
3137 return ExprError();
3138 LHSExp = Result.take();
3139 }
3140 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3141 if (Result.isInvalid())
3142 return ExprError();
3143 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003144
Chris Lattner12d9ff62007-07-16 00:14:47 +00003145 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003146 ExprValueKind VK = VK_LValue;
3147 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003148
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003150 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003151 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003152 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003153 Expr *BaseExpr, *IndexExpr;
3154 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003155 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3156 BaseExpr = LHSExp;
3157 IndexExpr = RHSExp;
3158 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003159 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003160 BaseExpr = LHSExp;
3161 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003162 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003163 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003164 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003165 BaseExpr = RHSExp;
3166 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003167 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003168 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003169 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003170 BaseExpr = LHSExp;
3171 IndexExpr = RHSExp;
3172 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003173 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003174 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003175 // Handle the uncommon case of "123[Ptr]".
3176 BaseExpr = RHSExp;
3177 IndexExpr = LHSExp;
3178 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003179 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003180 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003181 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003182 VK = LHSExp->getValueKind();
3183 if (VK != VK_RValue)
3184 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003185
Chris Lattner12d9ff62007-07-16 00:14:47 +00003186 // FIXME: need to deal with const...
3187 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003188 } else if (LHSTy->isArrayType()) {
3189 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003190 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003191 // wasn't promoted because of the C90 rule that doesn't
3192 // allow promoting non-lvalue arrays. Warn, then
3193 // force the promotion here.
3194 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3195 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003196 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3197 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003198 LHSTy = LHSExp->getType();
3199
3200 BaseExpr = LHSExp;
3201 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003202 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003203 } else if (RHSTy->isArrayType()) {
3204 // Same as previous, except for 123[f().a] case
3205 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3206 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003207 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3208 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003209 RHSTy = RHSExp->getType();
3210
3211 BaseExpr = RHSExp;
3212 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003213 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003214 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003215 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3216 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003217 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003219 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003220 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3221 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003222
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003223 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003224 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3225 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003226 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3227
Douglas Gregore7450f52009-03-24 19:52:54 +00003228 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003229 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3230 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003231 // incomplete types are not object types.
3232 if (ResultType->isFunctionType()) {
3233 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3234 << ResultType << BaseExpr->getSourceRange();
3235 return ExprError();
3236 }
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Abramo Bagnara46358452010-09-13 06:50:07 +00003238 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3239 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003240 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3241 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003242
3243 // C forbids expressions of unqualified void type from being l-values.
3244 // See IsCForbiddenLValueType.
3245 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003246 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003247 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003248 PDiag(diag::err_subscript_incomplete_type)
3249 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003250 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Chris Lattner1efaa952009-04-24 00:30:45 +00003252 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003253 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003254 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3255 << ResultType << BaseExpr->getSourceRange();
3256 return ExprError();
3257 }
Mike Stump1eb44332009-09-09 15:08:12 +00003258
John McCall09431682010-11-18 19:01:18 +00003259 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003260 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003261
Mike Stumpeed9cac2009-02-19 03:04:26 +00003262 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003263 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003264}
3265
John McCall60d7b3a2010-08-24 06:29:42 +00003266ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003267 FunctionDecl *FD,
3268 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003269 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003270 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003271 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003272 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003273 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003274 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003275 return ExprError();
3276 }
3277
3278 if (Param->hasUninstantiatedDefaultArg()) {
3279 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003280
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003281 // Instantiate the expression.
3282 MultiLevelTemplateArgumentList ArgList
3283 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003284
Nico Weber08e41a62010-11-29 18:19:25 +00003285 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003286 = ArgList.getInnermost();
3287 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3288 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003289
Nico Weber08e41a62010-11-29 18:19:25 +00003290 ExprResult Result;
3291 {
3292 // C++ [dcl.fct.default]p5:
3293 // The names in the [default argument] expression are bound, and
3294 // the semantic constraints are checked, at the point where the
3295 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003296 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003297 Result = SubstExpr(UninstExpr, ArgList);
3298 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003299 if (Result.isInvalid())
3300 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003302 // Check the expression as an initializer for the parameter.
3303 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003304 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003305 InitializationKind Kind
3306 = InitializationKind::CreateCopy(Param->getLocation(),
3307 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3308 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003309
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003310 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3311 Result = InitSeq.Perform(*this, Entity, Kind,
3312 MultiExprArg(*this, &ResultE, 1));
3313 if (Result.isInvalid())
3314 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003315
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003316 // Build the default argument expression.
3317 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3318 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003319 }
3320
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003321 // If the default expression creates temporaries, we need to
3322 // push them to the current stack of expression temporaries so they'll
3323 // be properly destroyed.
3324 // FIXME: We should really be rebuilding the default argument with new
3325 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003326 // We don't need to do that with block decls, though, because
3327 // blocks in default argument expression can never capture anything.
3328 if (isa<ExprWithCleanups>(Param->getInit())) {
3329 // Set the "needs cleanups" bit regardless of whether there are
3330 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003331 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003332
3333 // Append all the objects to the cleanup list. Right now, this
3334 // should always be a no-op, because blocks in default argument
3335 // expressions should never be able to capture anything.
3336 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3337 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003338 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003339
3340 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003341 // Just mark all of the declarations in this potentially-evaluated expression
3342 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003343 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003344 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003345}
3346
Douglas Gregor88a35142008-12-22 05:46:06 +00003347/// ConvertArgumentsForCall - Converts the arguments specified in
3348/// Args/NumArgs to the parameter types of the function FDecl with
3349/// function prototype Proto. Call is the call expression itself, and
3350/// Fn is the function expression. For a C++ member function, this
3351/// routine does not attempt to convert the object argument. Returns
3352/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003353bool
3354Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003355 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003356 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003357 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003358 SourceLocation RParenLoc,
3359 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003360 // Bail out early if calling a builtin with custom typechecking.
3361 // We don't need to do this in the
3362 if (FDecl)
3363 if (unsigned ID = FDecl->getBuiltinID())
3364 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3365 return false;
3366
Mike Stumpeed9cac2009-02-19 03:04:26 +00003367 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003368 // assignment, to the types of the corresponding parameter, ...
3369 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003370 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003371 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003372 unsigned FnKind = Fn->getType()->isBlockPointerType()
3373 ? 1 /* block */
3374 : (IsExecConfig ? 3 /* kernel function (exec config) */
3375 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003376
Douglas Gregor88a35142008-12-22 05:46:06 +00003377 // If too few arguments are available (and we don't have default
3378 // arguments for the remaining parameters), don't make the call.
3379 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003380 if (NumArgs < MinArgs) {
3381 Diag(RParenLoc, MinArgs == NumArgsInProto
3382 ? diag::err_typecheck_call_too_few_args
3383 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003384 << FnKind
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003385 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003386
3387 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003388 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003389 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3390 << FDecl;
3391
3392 return true;
3393 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003394 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003395 }
3396
3397 // If too many are passed and not variadic, error on the extras and drop
3398 // them.
3399 if (NumArgs > NumArgsInProto) {
3400 if (!Proto->isVariadic()) {
3401 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003402 MinArgs == NumArgsInProto
3403 ? diag::err_typecheck_call_too_many_args
3404 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003405 << FnKind
Eric Christopherccfa9632010-04-16 04:56:46 +00003406 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003407 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3408 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003409
3410 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003411 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003412 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3413 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003414
Douglas Gregor88a35142008-12-22 05:46:06 +00003415 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003416 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003417 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003418 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003420 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003421 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003422 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3423 if (Fn->getType()->isBlockPointerType())
3424 CallType = VariadicBlock; // Block
3425 else if (isa<MemberExpr>(Fn))
3426 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003427 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003428 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003429 if (Invalid)
3430 return true;
3431 unsigned TotalNumArgs = AllArgs.size();
3432 for (unsigned i = 0; i < TotalNumArgs; ++i)
3433 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003434
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003435 return false;
3436}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003437
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003438bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3439 FunctionDecl *FDecl,
3440 const FunctionProtoType *Proto,
3441 unsigned FirstProtoArg,
3442 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003443 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003444 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003445 unsigned NumArgsInProto = Proto->getNumArgs();
3446 unsigned NumArgsToCheck = NumArgs;
3447 bool Invalid = false;
3448 if (NumArgs != NumArgsInProto)
3449 // Use default arguments for missing arguments
3450 NumArgsToCheck = NumArgsInProto;
3451 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003452 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003453 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003454 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003455
Douglas Gregor88a35142008-12-22 05:46:06 +00003456 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003457 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003458 if (ArgIx < NumArgs) {
3459 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003460
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003461 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3462 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003463 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003464 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003465 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003466
Douglas Gregora188ff22009-12-22 16:09:06 +00003467 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003468 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003469 if (FDecl && i < FDecl->getNumParams())
3470 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003471
John McCall5acb0c92011-10-17 18:40:02 +00003472 // Strip the unbridged-cast placeholder expression off, if applicable.
3473 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3474 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3475 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3476 Arg = stripARCUnbridgedCast(Arg);
3477
Douglas Gregora188ff22009-12-22 16:09:06 +00003478 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003479 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003480 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3481 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003482 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003483 SourceLocation(),
3484 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003485 if (ArgE.isInvalid())
3486 return true;
3487
3488 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003489 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003490 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003491
John McCall60d7b3a2010-08-24 06:29:42 +00003492 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003493 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003494 if (ArgExpr.isInvalid())
3495 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003496
Anders Carlsson56c5e332009-08-25 03:49:14 +00003497 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003498 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003499
3500 // Check for array bounds violations for each argument to the call. This
3501 // check only triggers warnings when the argument isn't a more complex Expr
3502 // with its own checking, such as a BinaryOperator.
3503 CheckArrayAccess(Arg);
3504
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003505 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3506 CheckStaticArrayArgument(CallLoc, Param, Arg);
3507
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003508 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003509 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003510
Douglas Gregor88a35142008-12-22 05:46:06 +00003511 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003512 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003513
3514 // Assume that extern "C" functions with variadic arguments that
3515 // return __unknown_anytype aren't *really* variadic.
3516 if (Proto->getResultType() == Context.UnknownAnyTy &&
3517 FDecl && FDecl->isExternC()) {
3518 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3519 ExprResult arg;
3520 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3521 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3522 else
3523 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3524 Invalid |= arg.isInvalid();
3525 AllArgs.push_back(arg.take());
3526 }
3527
3528 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3529 } else {
3530 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003531 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3532 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003533 Invalid |= Arg.isInvalid();
3534 AllArgs.push_back(Arg.take());
3535 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003536 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003537
3538 // Check for array bounds violations.
3539 for (unsigned i = ArgIx; i != NumArgs; ++i)
3540 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003541 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003542 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003543}
3544
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003545static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3546 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3547 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3548 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3549 << ATL->getLocalSourceRange();
3550}
3551
3552/// CheckStaticArrayArgument - If the given argument corresponds to a static
3553/// array parameter, check that it is non-null, and that if it is formed by
3554/// array-to-pointer decay, the underlying array is sufficiently large.
3555///
3556/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3557/// array type derivation, then for each call to the function, the value of the
3558/// corresponding actual argument shall provide access to the first element of
3559/// an array with at least as many elements as specified by the size expression.
3560void
3561Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3562 ParmVarDecl *Param,
3563 const Expr *ArgExpr) {
3564 // Static array parameters are not supported in C++.
3565 if (!Param || getLangOptions().CPlusPlus)
3566 return;
3567
3568 QualType OrigTy = Param->getOriginalType();
3569
3570 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3571 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3572 return;
3573
3574 if (ArgExpr->isNullPointerConstant(Context,
3575 Expr::NPC_NeverValueDependent)) {
3576 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3577 DiagnoseCalleeStaticArrayParam(*this, Param);
3578 return;
3579 }
3580
3581 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3582 if (!CAT)
3583 return;
3584
3585 const ConstantArrayType *ArgCAT =
3586 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3587 if (!ArgCAT)
3588 return;
3589
3590 if (ArgCAT->getSize().ult(CAT->getSize())) {
3591 Diag(CallLoc, diag::warn_static_array_too_small)
3592 << ArgExpr->getSourceRange()
3593 << (unsigned) ArgCAT->getSize().getZExtValue()
3594 << (unsigned) CAT->getSize().getZExtValue();
3595 DiagnoseCalleeStaticArrayParam(*this, Param);
3596 }
3597}
3598
John McCall755d8492011-04-12 00:42:48 +00003599/// Given a function expression of unknown-any type, try to rebuild it
3600/// to have a function type.
3601static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3602
Steve Narofff69936d2007-09-16 03:34:24 +00003603/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003604/// This provides the location of the left/right parens and a list of comma
3605/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003606ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003607Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003608 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003609 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003610 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003611
3612 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003613 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003614 if (Result.isInvalid()) return ExprError();
3615 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Richard Trieuccd891a2011-09-09 01:45:06 +00003617 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Douglas Gregor88a35142008-12-22 05:46:06 +00003619 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003620 // If this is a pseudo-destructor expression, build the call immediately.
3621 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3622 if (NumArgs > 0) {
3623 // Pseudo-destructor calls should not have any arguments.
3624 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003625 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003626 SourceRange(Args[0]->getLocStart(),
3627 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Douglas Gregora71d8192009-09-04 17:36:40 +00003629 NumArgs = 0;
3630 }
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Douglas Gregora71d8192009-09-04 17:36:40 +00003632 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003633 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003634 }
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Douglas Gregor17330012009-02-04 15:01:18 +00003636 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003637 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003638 // FIXME: Will need to cache the results of name lookup (including ADL) in
3639 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003640 bool Dependent = false;
3641 if (Fn->isTypeDependent())
3642 Dependent = true;
3643 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3644 Dependent = true;
3645
Peter Collingbournee08ce652011-02-09 21:07:24 +00003646 if (Dependent) {
3647 if (ExecConfig) {
3648 return Owned(new (Context) CUDAKernelCallExpr(
3649 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3650 Context.DependentTy, VK_RValue, RParenLoc));
3651 } else {
3652 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3653 Context.DependentTy, VK_RValue,
3654 RParenLoc));
3655 }
3656 }
Douglas Gregor17330012009-02-04 15:01:18 +00003657
3658 // Determine whether this is a call to an object (C++ [over.call.object]).
3659 if (Fn->getType()->isRecordType())
3660 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003661 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003662
John McCall755d8492011-04-12 00:42:48 +00003663 if (Fn->getType() == Context.UnknownAnyTy) {
3664 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3665 if (result.isInvalid()) return ExprError();
3666 Fn = result.take();
3667 }
3668
John McCall864c0412011-04-26 20:42:42 +00003669 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003670 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003671 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003672 }
John McCall864c0412011-04-26 20:42:42 +00003673 }
John McCall129e2df2009-11-30 22:42:35 +00003674
John McCall864c0412011-04-26 20:42:42 +00003675 // Check for overloaded calls. This can happen even in C due to extensions.
3676 if (Fn->getType() == Context.OverloadTy) {
3677 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3678
Douglas Gregoree697e62011-10-13 18:10:35 +00003679 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003680 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003681 OverloadExpr *ovl = find.Expression;
3682 if (isa<UnresolvedLookupExpr>(ovl)) {
3683 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3684 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3685 RParenLoc, ExecConfig);
3686 } else {
John McCallaa81e162009-12-01 22:10:20 +00003687 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003688 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003689 }
3690 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003691 }
3692
Douglas Gregorfa047642009-02-04 00:32:51 +00003693 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003694 if (Fn->getType() == Context.UnknownAnyTy) {
3695 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3696 if (result.isInvalid()) return ExprError();
3697 Fn = result.take();
3698 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003699
Eli Friedmanefa42f72009-12-26 03:35:45 +00003700 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003701
John McCall3b4294e2009-12-16 12:17:52 +00003702 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003703 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3704 if (UnOp->getOpcode() == UO_AddrOf)
3705 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3706
John McCall3b4294e2009-12-16 12:17:52 +00003707 if (isa<DeclRefExpr>(NakedFn))
3708 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003709 else if (isa<MemberExpr>(NakedFn))
3710 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003711
Peter Collingbournee08ce652011-02-09 21:07:24 +00003712 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003713 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003714}
3715
3716ExprResult
3717Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003718 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003719 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3720 if (!ConfigDecl)
3721 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3722 << "cudaConfigureCall");
3723 QualType ConfigQTy = ConfigDecl->getType();
3724
3725 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3726 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3727
Peter Collingbourne1f240762011-10-02 23:49:29 +00003728 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3729 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003730}
3731
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003732/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3733///
3734/// __builtin_astype( value, dst type )
3735///
Richard Trieuccd891a2011-09-09 01:45:06 +00003736ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003737 SourceLocation BuiltinLoc,
3738 SourceLocation RParenLoc) {
3739 ExprValueKind VK = VK_RValue;
3740 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003741 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3742 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003743 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3744 return ExprError(Diag(BuiltinLoc,
3745 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003746 << DstTy
3747 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003748 << E->getSourceRange());
3749 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003750 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003751}
3752
John McCall3b4294e2009-12-16 12:17:52 +00003753/// BuildResolvedCallExpr - Build a call to a resolved expression,
3754/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003755/// unary-convert to an expression of function-pointer or
3756/// block-pointer type.
3757///
3758/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003759ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003760Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3761 SourceLocation LParenLoc,
3762 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003763 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003764 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003765 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3766
Chris Lattner04421082008-04-08 04:40:51 +00003767 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003768 ExprResult Result = UsualUnaryConversions(Fn);
3769 if (Result.isInvalid())
3770 return ExprError();
3771 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003772
Chris Lattner925e60d2007-12-28 05:29:59 +00003773 // Make the call expr early, before semantic checks. This guarantees cleanup
3774 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003775 CallExpr *TheCall;
3776 if (Config) {
3777 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3778 cast<CallExpr>(Config),
3779 Args, NumArgs,
3780 Context.BoolTy,
3781 VK_RValue,
3782 RParenLoc);
3783 } else {
3784 TheCall = new (Context) CallExpr(Context, Fn,
3785 Args, NumArgs,
3786 Context.BoolTy,
3787 VK_RValue,
3788 RParenLoc);
3789 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003790
John McCall8e10f3b2011-02-26 05:39:39 +00003791 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3792
3793 // Bail out early if calling a builtin with custom typechecking.
3794 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3795 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3796
John McCall1de4d4e2011-04-07 08:22:57 +00003797 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003798 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003799 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003800 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3801 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003802 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003803 if (FuncT == 0)
3804 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3805 << Fn->getType() << Fn->getSourceRange());
3806 } else if (const BlockPointerType *BPT =
3807 Fn->getType()->getAs<BlockPointerType>()) {
3808 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3809 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003810 // Handle calls to expressions of unknown-any type.
3811 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003812 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003813 if (rewrite.isInvalid()) return ExprError();
3814 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003815 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003816 goto retry;
3817 }
3818
Sebastian Redl0eb23302009-01-19 00:08:26 +00003819 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3820 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003821 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003822
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003823 if (getLangOptions().CUDA) {
3824 if (Config) {
3825 // CUDA: Kernel calls must be to global functions
3826 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3827 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3828 << FDecl->getName() << Fn->getSourceRange());
3829
3830 // CUDA: Kernel function must have 'void' return type
3831 if (!FuncT->getResultType()->isVoidType())
3832 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3833 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003834 } else {
3835 // CUDA: Calls to global functions must be configured
3836 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3837 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3838 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003839 }
3840 }
3841
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003842 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003843 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003844 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003845 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003846 return ExprError();
3847
Chris Lattner925e60d2007-12-28 05:29:59 +00003848 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003849 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003850 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003851
Douglas Gregor72564e72009-02-26 23:50:07 +00003852 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003853 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003854 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003855 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003856 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003857 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003858
Douglas Gregor74734d52009-04-02 15:37:10 +00003859 if (FDecl) {
3860 // Check if we have too few/too many template arguments, based
3861 // on our knowledge of the function definition.
3862 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003863 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003864 const FunctionProtoType *Proto
3865 = Def->getType()->getAs<FunctionProtoType>();
3866 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003867 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3868 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003869 }
Douglas Gregor46542412010-10-25 20:39:23 +00003870
3871 // If the function we're calling isn't a function prototype, but we have
3872 // a function prototype from a prior declaratiom, use that prototype.
3873 if (!FDecl->hasPrototype())
3874 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003875 }
3876
Steve Naroffb291ab62007-08-28 23:30:39 +00003877 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003878 for (unsigned i = 0; i != NumArgs; i++) {
3879 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003880
3881 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003882 InitializedEntity Entity
3883 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003884 Proto->getArgType(i),
3885 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003886 ExprResult ArgE = PerformCopyInitialization(Entity,
3887 SourceLocation(),
3888 Owned(Arg));
3889 if (ArgE.isInvalid())
3890 return true;
3891
3892 Arg = ArgE.takeAs<Expr>();
3893
3894 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003895 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3896
3897 if (ArgE.isInvalid())
3898 return true;
3899
3900 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003901 }
3902
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003903 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3904 Arg->getType(),
3905 PDiag(diag::err_call_incomplete_argument)
3906 << Arg->getSourceRange()))
3907 return ExprError();
3908
Chris Lattner925e60d2007-12-28 05:29:59 +00003909 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003910 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003911 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003912
Douglas Gregor88a35142008-12-22 05:46:06 +00003913 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3914 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003915 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3916 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003917
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003918 // Check for sentinels
3919 if (NDecl)
3920 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Chris Lattner59907c42007-08-10 20:18:51 +00003922 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003923 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003924 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003925 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003926
John McCall8e10f3b2011-02-26 05:39:39 +00003927 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003928 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003929 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003930 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003931 return ExprError();
3932 }
Chris Lattner59907c42007-08-10 20:18:51 +00003933
John McCall9ae2f072010-08-23 23:25:46 +00003934 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003935}
3936
John McCall60d7b3a2010-08-24 06:29:42 +00003937ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003938Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003939 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003940 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003941 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003942 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003943
3944 TypeSourceInfo *TInfo;
3945 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3946 if (!TInfo)
3947 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3948
John McCall9ae2f072010-08-23 23:25:46 +00003949 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003950}
3951
John McCall60d7b3a2010-08-24 06:29:42 +00003952ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003953Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003954 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003955 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003956
Eli Friedman6223c222008-05-20 05:22:08 +00003957 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003958 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3959 PDiag(diag::err_illegal_decl_array_incomplete_type)
3960 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003961 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003962 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003963 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003964 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003965 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003966 } else if (!literalType->isDependentType() &&
3967 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003968 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003969 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003970 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003971 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003972
Douglas Gregor99a2e602009-12-16 01:38:02 +00003973 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003974 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003975 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003976 = InitializationKind::CreateCStyleCast(LParenLoc,
3977 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003978 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003979 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003980 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003981 &literalType);
3982 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003983 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003984 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003985
Chris Lattner371f2582008-12-04 23:50:19 +00003986 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003987 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003988 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003989 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003990 }
Eli Friedman08544622009-12-22 02:35:53 +00003991
John McCallf89e55a2010-11-18 06:31:45 +00003992 // In C, compound literals are l-values for some reason.
3993 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3994
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003995 return MaybeBindToTemporary(
3996 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003997 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003998}
3999
John McCall60d7b3a2010-08-24 06:29:42 +00004000ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004001Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004002 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004003 unsigned NumInit = InitArgList.size();
4004 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004005
John McCall3c3b7f92011-10-25 17:37:35 +00004006 // Immediately handle non-overload placeholders. Overloads can be
4007 // resolved contextually, but everything else here can't.
4008 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004009 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004010 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4011
4012 // Ignore failures; dropping the entire initializer list because
4013 // of one failure would be terrible for indexing/etc.
4014 if (result.isInvalid()) continue;
4015
4016 InitList[I] = result.take();
4017 }
4018 }
4019
Steve Naroff08d92e42007-09-15 18:49:24 +00004020 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004021 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004022
Ted Kremenek709210f2010-04-13 23:39:13 +00004023 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4024 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004025 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004026 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004027}
4028
John McCalldc05b112011-09-10 01:16:55 +00004029/// Do an explicit extend of the given block pointer if we're in ARC.
4030static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4031 assert(E.get()->getType()->isBlockPointerType());
4032 assert(E.get()->isRValue());
4033
4034 // Only do this in an r-value context.
4035 if (!S.getLangOptions().ObjCAutoRefCount) return;
4036
4037 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004038 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004039 /*base path*/ 0, VK_RValue);
4040 S.ExprNeedsCleanups = true;
4041}
4042
4043/// Prepare a conversion of the given expression to an ObjC object
4044/// pointer type.
4045CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4046 QualType type = E.get()->getType();
4047 if (type->isObjCObjectPointerType()) {
4048 return CK_BitCast;
4049 } else if (type->isBlockPointerType()) {
4050 maybeExtendBlockObject(*this, E);
4051 return CK_BlockPointerToObjCPointerCast;
4052 } else {
4053 assert(type->isPointerType());
4054 return CK_CPointerToObjCPointerCast;
4055 }
4056}
4057
John McCallf3ea8cf2010-11-14 08:17:51 +00004058/// Prepares for a scalar cast, performing all the necessary stages
4059/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004060CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004061 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4062 // Also, callers should have filtered out the invalid cases with
4063 // pointers. Everything else should be possible.
4064
John Wiegley429bb272011-04-08 18:41:53 +00004065 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004066 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004067 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004068
John McCall1d9b3b22011-09-09 05:25:32 +00004069 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004070 case Type::STK_MemberPointer:
4071 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004072
John McCall1d9b3b22011-09-09 05:25:32 +00004073 case Type::STK_CPointer:
4074 case Type::STK_BlockPointer:
4075 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004076 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004077 case Type::STK_CPointer:
4078 return CK_BitCast;
4079 case Type::STK_BlockPointer:
4080 return (SrcKind == Type::STK_BlockPointer
4081 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4082 case Type::STK_ObjCObjectPointer:
4083 if (SrcKind == Type::STK_ObjCObjectPointer)
4084 return CK_BitCast;
4085 else if (SrcKind == Type::STK_CPointer)
4086 return CK_CPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00004087 else {
John McCalla180f042011-10-06 23:25:11 +00004088 maybeExtendBlockObject(*this, Src);
John McCall1d9b3b22011-09-09 05:25:32 +00004089 return CK_BlockPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00004090 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004091 case Type::STK_Bool:
4092 return CK_PointerToBoolean;
4093 case Type::STK_Integral:
4094 return CK_PointerToIntegral;
4095 case Type::STK_Floating:
4096 case Type::STK_FloatingComplex:
4097 case Type::STK_IntegralComplex:
4098 case Type::STK_MemberPointer:
4099 llvm_unreachable("illegal cast from pointer");
4100 }
4101 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004102
John McCalldaa8e4e2010-11-15 09:13:47 +00004103 case Type::STK_Bool: // casting from bool is like casting from an integer
4104 case Type::STK_Integral:
4105 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004106 case Type::STK_CPointer:
4107 case Type::STK_ObjCObjectPointer:
4108 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004109 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004110 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004111 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004112 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004113 case Type::STK_Bool:
4114 return CK_IntegralToBoolean;
4115 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004116 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004117 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004118 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004119 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004120 Src = ImpCastExprToType(Src.take(),
4121 DestTy->castAs<ComplexType>()->getElementType(),
4122 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004123 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004124 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004125 Src = ImpCastExprToType(Src.take(),
4126 DestTy->castAs<ComplexType>()->getElementType(),
4127 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004128 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004129 case Type::STK_MemberPointer:
4130 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004131 }
4132 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004133
John McCalldaa8e4e2010-11-15 09:13:47 +00004134 case Type::STK_Floating:
4135 switch (DestTy->getScalarTypeKind()) {
4136 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004137 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004138 case Type::STK_Bool:
4139 return CK_FloatingToBoolean;
4140 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004141 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004142 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004143 Src = ImpCastExprToType(Src.take(),
4144 DestTy->castAs<ComplexType>()->getElementType(),
4145 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004146 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004147 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004148 Src = ImpCastExprToType(Src.take(),
4149 DestTy->castAs<ComplexType>()->getElementType(),
4150 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004151 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004152 case Type::STK_CPointer:
4153 case Type::STK_ObjCObjectPointer:
4154 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004155 llvm_unreachable("valid float->pointer cast?");
4156 case Type::STK_MemberPointer:
4157 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004158 }
4159 break;
4160
John McCalldaa8e4e2010-11-15 09:13:47 +00004161 case Type::STK_FloatingComplex:
4162 switch (DestTy->getScalarTypeKind()) {
4163 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004164 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004165 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004166 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004167 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004168 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4169 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004170 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004171 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004172 return CK_FloatingCast;
4173 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004174 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004175 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004176 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004177 Src = ImpCastExprToType(Src.take(),
4178 SrcTy->castAs<ComplexType>()->getElementType(),
4179 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004180 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004181 case Type::STK_CPointer:
4182 case Type::STK_ObjCObjectPointer:
4183 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004184 llvm_unreachable("valid complex float->pointer cast?");
4185 case Type::STK_MemberPointer:
4186 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004187 }
4188 break;
4189
John McCalldaa8e4e2010-11-15 09:13:47 +00004190 case Type::STK_IntegralComplex:
4191 switch (DestTy->getScalarTypeKind()) {
4192 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004193 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004194 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004195 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004196 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004197 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4198 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004199 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004200 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004201 return CK_IntegralCast;
4202 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004203 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004204 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004205 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004206 Src = ImpCastExprToType(Src.take(),
4207 SrcTy->castAs<ComplexType>()->getElementType(),
4208 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004209 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004210 case Type::STK_CPointer:
4211 case Type::STK_ObjCObjectPointer:
4212 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004213 llvm_unreachable("valid complex int->pointer cast?");
4214 case Type::STK_MemberPointer:
4215 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004216 }
4217 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004218 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004219
John McCallf3ea8cf2010-11-14 08:17:51 +00004220 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004221}
4222
Anders Carlssonc3516322009-10-16 02:48:28 +00004223bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004224 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004225 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004226
Anders Carlssona64db8f2007-11-27 05:51:55 +00004227 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004228 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004229 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004230 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004231 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004232 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004233 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004234 } else
4235 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004236 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004237 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004238
John McCall2de56d12010-08-25 11:45:40 +00004239 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004240 return false;
4241}
4242
John Wiegley429bb272011-04-08 18:41:53 +00004243ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4244 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004245 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004246
Anders Carlsson16a89042009-10-16 05:23:41 +00004247 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004248
Nate Begeman9b10da62009-06-27 22:05:55 +00004249 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4250 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004251 // In OpenCL, casts between vectors of different types are not allowed.
4252 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004253 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004254 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4255 || (getLangOptions().OpenCL &&
4256 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004257 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004258 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004259 return ExprError();
4260 }
John McCall2de56d12010-08-25 11:45:40 +00004261 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004262 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004263 }
4264
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004265 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004266 // conversion will take place first from scalar to elt type, and then
4267 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004268 if (SrcTy->isPointerType())
4269 return Diag(R.getBegin(),
4270 diag::err_invalid_conversion_between_vector_and_scalar)
4271 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004272
4273 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004274 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004275 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004276 if (CastExprRes.isInvalid())
4277 return ExprError();
4278 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004279
John McCall2de56d12010-08-25 11:45:40 +00004280 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004281 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004282}
4283
John McCall60d7b3a2010-08-24 06:29:42 +00004284ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004285Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4286 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004287 SourceLocation RParenLoc, Expr *CastExpr) {
4288 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004289 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004290
Richard Trieuccd891a2011-09-09 01:45:06 +00004291 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004292 if (D.isInvalidType())
4293 return ExprError();
4294
4295 if (getLangOptions().CPlusPlus) {
4296 // Check that there are no default arguments (C++ only).
4297 CheckExtraCXXDefaultArguments(D);
4298 }
4299
John McCalle82247a2011-10-01 05:17:03 +00004300 checkUnusedDeclAttributes(D);
4301
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004302 QualType castType = castTInfo->getType();
4303 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004305 bool isVectorLiteral = false;
4306
4307 // Check for an altivec or OpenCL literal,
4308 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004309 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4310 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser37c31c22011-09-21 18:28:29 +00004311 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4312 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004313 if (PLE && PLE->getNumExprs() == 0) {
4314 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4315 return ExprError();
4316 }
4317 if (PE || PLE->getNumExprs() == 1) {
4318 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4319 if (!E->getType()->isVectorType())
4320 isVectorLiteral = true;
4321 }
4322 else
4323 isVectorLiteral = true;
4324 }
4325
4326 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4327 // then handle it as such.
4328 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004329 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004330
Nate Begeman2ef13e52009-08-10 23:49:36 +00004331 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004332 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4333 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004334 if (isa<ParenListExpr>(CastExpr)) {
4335 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004336 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004337 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004338 }
John McCallb042fdf2010-01-15 18:56:44 +00004339
Richard Trieuccd891a2011-09-09 01:45:06 +00004340 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004341}
4342
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004343ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4344 SourceLocation RParenLoc, Expr *E,
4345 TypeSourceInfo *TInfo) {
4346 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4347 "Expected paren or paren list expression");
4348
4349 Expr **exprs;
4350 unsigned numExprs;
4351 Expr *subExpr;
4352 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4353 exprs = PE->getExprs();
4354 numExprs = PE->getNumExprs();
4355 } else {
4356 subExpr = cast<ParenExpr>(E)->getSubExpr();
4357 exprs = &subExpr;
4358 numExprs = 1;
4359 }
4360
4361 QualType Ty = TInfo->getType();
4362 assert(Ty->isVectorType() && "Expected vector type");
4363
Chris Lattner5f9e2722011-07-23 10:55:15 +00004364 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004365 const VectorType *VTy = Ty->getAs<VectorType>();
4366 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4367
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004368 // '(...)' form of vector initialization in AltiVec: the number of
4369 // initializers must be one or must match the size of the vector.
4370 // If a single value is specified in the initializer then it will be
4371 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004372 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004373 // The number of initializers must be one or must match the size of the
4374 // vector. If a single value is specified in the initializer then it will
4375 // be replicated to all the components of the vector
4376 if (numExprs == 1) {
4377 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004378 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4379 if (Literal.isInvalid())
4380 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004381 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004382 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004383 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4384 }
4385 else if (numExprs < numElems) {
4386 Diag(E->getExprLoc(),
4387 diag::err_incorrect_number_of_vector_initializers);
4388 return ExprError();
4389 }
4390 else
4391 for (unsigned i = 0, e = numExprs; i != e; ++i)
4392 initExprs.push_back(exprs[i]);
4393 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004394 else {
4395 // For OpenCL, when the number of initializers is a single value,
4396 // it will be replicated to all components of the vector.
4397 if (getLangOptions().OpenCL &&
4398 VTy->getVectorKind() == VectorType::GenericVector &&
4399 numExprs == 1) {
4400 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004401 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4402 if (Literal.isInvalid())
4403 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004404 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004405 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004406 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4407 }
4408
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004409 for (unsigned i = 0, e = numExprs; i != e; ++i)
4410 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004411 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004412 // FIXME: This means that pretty-printing the final AST will produce curly
4413 // braces instead of the original commas.
4414 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4415 &initExprs[0],
4416 initExprs.size(), RParenLoc);
4417 initE->setType(Ty);
4418 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4419}
4420
Nate Begeman2ef13e52009-08-10 23:49:36 +00004421/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4422/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004423ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004424Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4425 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004426 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004427 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004428
John McCall60d7b3a2010-08-24 06:29:42 +00004429 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Nate Begeman2ef13e52009-08-10 23:49:36 +00004431 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004432 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4433 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004434
John McCall9ae2f072010-08-23 23:25:46 +00004435 if (Result.isInvalid()) return ExprError();
4436
4437 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004438}
4439
John McCall60d7b3a2010-08-24 06:29:42 +00004440ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004441 SourceLocation R,
4442 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004443 unsigned nexprs = Val.size();
4444 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004445 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4446 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004447 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004448 expr = new (Context) ParenExpr(L, R, exprs[0]);
4449 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004450 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4451 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004452 return Owned(expr);
4453}
4454
Chandler Carruth82214a82011-02-18 23:54:50 +00004455/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004456/// constant and the other is not a pointer. Returns true if a diagnostic is
4457/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004458bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004459 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004460 Expr *NullExpr = LHSExpr;
4461 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004462 Expr::NullPointerConstantKind NullKind =
4463 NullExpr->isNullPointerConstant(Context,
4464 Expr::NPC_ValueDependentIsNotNull);
4465
4466 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004467 NullExpr = RHSExpr;
4468 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004469 NullKind =
4470 NullExpr->isNullPointerConstant(Context,
4471 Expr::NPC_ValueDependentIsNotNull);
4472 }
4473
4474 if (NullKind == Expr::NPCK_NotNull)
4475 return false;
4476
4477 if (NullKind == Expr::NPCK_ZeroInteger) {
4478 // In this case, check to make sure that we got here from a "NULL"
4479 // string in the source code.
4480 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004481 SourceLocation loc = NullExpr->getExprLoc();
4482 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004483 return false;
4484 }
4485
4486 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4487 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4488 << NonPointerExpr->getType() << DiagType
4489 << NonPointerExpr->getSourceRange();
4490 return true;
4491}
4492
Richard Trieu26f96072011-09-02 01:51:02 +00004493/// \brief Return false if the condition expression is valid, true otherwise.
4494static bool checkCondition(Sema &S, Expr *Cond) {
4495 QualType CondTy = Cond->getType();
4496
4497 // C99 6.5.15p2
4498 if (CondTy->isScalarType()) return false;
4499
4500 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4501 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4502 return false;
4503
4504 // Emit the proper error message.
4505 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4506 diag::err_typecheck_cond_expect_scalar :
4507 diag::err_typecheck_cond_expect_scalar_or_vector)
4508 << CondTy;
4509 return true;
4510}
4511
4512/// \brief Return false if the two expressions can be converted to a vector,
4513/// true otherwise
4514static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4515 ExprResult &RHS,
4516 QualType CondTy) {
4517 // Both operands should be of scalar type.
4518 if (!LHS.get()->getType()->isScalarType()) {
4519 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4520 << CondTy;
4521 return true;
4522 }
4523 if (!RHS.get()->getType()->isScalarType()) {
4524 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4525 << CondTy;
4526 return true;
4527 }
4528
4529 // Implicity convert these scalars to the type of the condition.
4530 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4531 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4532 return false;
4533}
4534
4535/// \brief Handle when one or both operands are void type.
4536static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4537 ExprResult &RHS) {
4538 Expr *LHSExpr = LHS.get();
4539 Expr *RHSExpr = RHS.get();
4540
4541 if (!LHSExpr->getType()->isVoidType())
4542 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4543 << RHSExpr->getSourceRange();
4544 if (!RHSExpr->getType()->isVoidType())
4545 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4546 << LHSExpr->getSourceRange();
4547 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4548 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4549 return S.Context.VoidTy;
4550}
4551
4552/// \brief Return false if the NullExpr can be promoted to PointerTy,
4553/// true otherwise.
4554static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4555 QualType PointerTy) {
4556 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4557 !NullExpr.get()->isNullPointerConstant(S.Context,
4558 Expr::NPC_ValueDependentIsNull))
4559 return true;
4560
4561 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4562 return false;
4563}
4564
4565/// \brief Checks compatibility between two pointers and return the resulting
4566/// type.
4567static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4568 ExprResult &RHS,
4569 SourceLocation Loc) {
4570 QualType LHSTy = LHS.get()->getType();
4571 QualType RHSTy = RHS.get()->getType();
4572
4573 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4574 // Two identical pointers types are always compatible.
4575 return LHSTy;
4576 }
4577
4578 QualType lhptee, rhptee;
4579
4580 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004581 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4582 lhptee = LHSBTy->getPointeeType();
4583 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004584 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004585 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4586 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004587 }
4588
4589 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4590 rhptee.getUnqualifiedType())) {
4591 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4592 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4593 << RHS.get()->getSourceRange();
4594 // In this situation, we assume void* type. No especially good
4595 // reason, but this is what gcc does, and we do have to pick
4596 // to get a consistent AST.
4597 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4598 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4599 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4600 return incompatTy;
4601 }
4602
4603 // The pointer types are compatible.
4604 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4605 // differently qualified versions of compatible types, the result type is
4606 // a pointer to an appropriately qualified version of the *composite*
4607 // type.
4608 // FIXME: Need to calculate the composite type.
4609 // FIXME: Need to add qualifiers
4610
4611 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4612 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4613 return LHSTy;
4614}
4615
4616/// \brief Return the resulting type when the operands are both block pointers.
4617static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4618 ExprResult &LHS,
4619 ExprResult &RHS,
4620 SourceLocation Loc) {
4621 QualType LHSTy = LHS.get()->getType();
4622 QualType RHSTy = RHS.get()->getType();
4623
4624 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4625 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4626 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4627 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4628 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4629 return destType;
4630 }
4631 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4632 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4633 << RHS.get()->getSourceRange();
4634 return QualType();
4635 }
4636
4637 // We have 2 block pointer types.
4638 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4639}
4640
4641/// \brief Return the resulting type when the operands are both pointers.
4642static QualType
4643checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4644 ExprResult &RHS,
4645 SourceLocation Loc) {
4646 // get the pointer types
4647 QualType LHSTy = LHS.get()->getType();
4648 QualType RHSTy = RHS.get()->getType();
4649
4650 // get the "pointed to" types
4651 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4652 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4653
4654 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4655 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4656 // Figure out necessary qualifiers (C99 6.5.15p6)
4657 QualType destPointee
4658 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4659 QualType destType = S.Context.getPointerType(destPointee);
4660 // Add qualifiers if necessary.
4661 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4662 // Promote to void*.
4663 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4664 return destType;
4665 }
4666 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4667 QualType destPointee
4668 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4669 QualType destType = S.Context.getPointerType(destPointee);
4670 // Add qualifiers if necessary.
4671 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4672 // Promote to void*.
4673 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4674 return destType;
4675 }
4676
4677 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4678}
4679
4680/// \brief Return false if the first expression is not an integer and the second
4681/// expression is not a pointer, true otherwise.
4682static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4683 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004684 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004685 if (!PointerExpr->getType()->isPointerType() ||
4686 !Int.get()->getType()->isIntegerType())
4687 return false;
4688
Richard Trieuccd891a2011-09-09 01:45:06 +00004689 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4690 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004691
4692 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4693 << Expr1->getType() << Expr2->getType()
4694 << Expr1->getSourceRange() << Expr2->getSourceRange();
4695 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4696 CK_IntegralToPointer);
4697 return true;
4698}
4699
Richard Trieu33fc7572011-09-06 20:06:39 +00004700/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4701/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004702/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004703QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4704 ExprResult &RHS, ExprValueKind &VK,
4705 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004706 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004707
Richard Trieu33fc7572011-09-06 20:06:39 +00004708 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4709 if (!LHSResult.isUsable()) return QualType();
4710 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004711
Richard Trieu33fc7572011-09-06 20:06:39 +00004712 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4713 if (!RHSResult.isUsable()) return QualType();
4714 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004715
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004716 // C++ is sufficiently different to merit its own checker.
4717 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004718 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004719
4720 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004721 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004722
John Wiegley429bb272011-04-08 18:41:53 +00004723 Cond = UsualUnaryConversions(Cond.take());
4724 if (Cond.isInvalid())
4725 return QualType();
4726 LHS = UsualUnaryConversions(LHS.take());
4727 if (LHS.isInvalid())
4728 return QualType();
4729 RHS = UsualUnaryConversions(RHS.take());
4730 if (RHS.isInvalid())
4731 return QualType();
4732
4733 QualType CondTy = Cond.get()->getType();
4734 QualType LHSTy = LHS.get()->getType();
4735 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004736
Reid Spencer5f016e22007-07-11 17:01:13 +00004737 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004738 if (checkCondition(*this, Cond.get()))
4739 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004740
Chris Lattner70d67a92008-01-06 22:42:25 +00004741 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004742 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004743 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004744
Nate Begeman6155d732010-09-20 22:41:17 +00004745 // OpenCL: If the condition is a vector, and both operands are scalar,
4746 // attempt to implicity convert them to the vector type to act like the
4747 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004748 if (getLangOptions().OpenCL && CondTy->isVectorType())
4749 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004750 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004751
Chris Lattner70d67a92008-01-06 22:42:25 +00004752 // If both operands have arithmetic type, do the usual arithmetic conversions
4753 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004754 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4755 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004756 if (LHS.isInvalid() || RHS.isInvalid())
4757 return QualType();
4758 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004759 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004760
Chris Lattner70d67a92008-01-06 22:42:25 +00004761 // If both operands are the same structure or union type, the result is that
4762 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004763 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4764 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004765 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004767 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004768 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004769 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004770 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004771
Chris Lattner70d67a92008-01-06 22:42:25 +00004772 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004773 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004774 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004775 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004776 }
Richard Trieu26f96072011-09-02 01:51:02 +00004777
Steve Naroffb6d54e52008-01-08 01:11:38 +00004778 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4779 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004780 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4781 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004782
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004783 // All objective-c pointer type analysis is done here.
4784 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4785 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004786 if (LHS.isInvalid() || RHS.isInvalid())
4787 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004788 if (!compositeType.isNull())
4789 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004790
4791
Steve Naroff7154a772009-07-01 14:36:47 +00004792 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004793 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4794 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4795 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004796
Steve Naroff7154a772009-07-01 14:36:47 +00004797 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004798 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4799 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4800 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004801
John McCall404cd162010-11-13 01:35:44 +00004802 // GCC compatibility: soften pointer/integer mismatch. Note that
4803 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004804 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4805 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004806 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004807 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4808 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004809 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004810
Chandler Carruth82214a82011-02-18 23:54:50 +00004811 // Emit a better diagnostic if one of the expressions is a null pointer
4812 // constant and the other is not a pointer type. In this case, the user most
4813 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004814 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004815 return QualType();
4816
Chris Lattner70d67a92008-01-06 22:42:25 +00004817 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004818 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004819 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4820 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004821 return QualType();
4822}
4823
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004824/// FindCompositeObjCPointerType - Helper method to find composite type of
4825/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004826QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004827 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004828 QualType LHSTy = LHS.get()->getType();
4829 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004830
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004831 // Handle things like Class and struct objc_class*. Here we case the result
4832 // to the pseudo-builtin, because that will be implicitly cast back to the
4833 // redefinition type if an attempt is made to access its fields.
4834 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004835 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004836 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004837 return LHSTy;
4838 }
4839 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004840 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004841 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004842 return RHSTy;
4843 }
4844 // And the same for struct objc_object* / id
4845 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004846 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004847 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004848 return LHSTy;
4849 }
4850 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004851 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004852 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004853 return RHSTy;
4854 }
4855 // And the same for struct objc_selector* / SEL
4856 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004857 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004858 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004859 return LHSTy;
4860 }
4861 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004862 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004863 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004864 return RHSTy;
4865 }
4866 // Check constraints for Objective-C object pointers types.
4867 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004868
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004869 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4870 // Two identical object pointer types are always compatible.
4871 return LHSTy;
4872 }
John McCall1d9b3b22011-09-09 05:25:32 +00004873 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4874 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004875 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004876
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004877 // If both operands are interfaces and either operand can be
4878 // assigned to the other, use that type as the composite
4879 // type. This allows
4880 // xxx ? (A*) a : (B*) b
4881 // where B is a subclass of A.
4882 //
4883 // Additionally, as for assignment, if either type is 'id'
4884 // allow silent coercion. Finally, if the types are
4885 // incompatible then make sure to use 'id' as the composite
4886 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004887
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004888 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4889 // It could return the composite type.
4890 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4891 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4892 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4893 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4894 } else if ((LHSTy->isObjCQualifiedIdType() ||
4895 RHSTy->isObjCQualifiedIdType()) &&
4896 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4897 // Need to handle "id<xx>" explicitly.
4898 // GCC allows qualified id and any Objective-C type to devolve to
4899 // id. Currently localizing to here until clear this should be
4900 // part of ObjCQualifiedIdTypesAreCompatible.
4901 compositeType = Context.getObjCIdType();
4902 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4903 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004904 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004905 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4906 ;
4907 else {
4908 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4909 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004910 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004911 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004912 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4913 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004914 return incompatTy;
4915 }
4916 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004917 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4918 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004919 return compositeType;
4920 }
4921 // Check Objective-C object pointer types and 'void *'
4922 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4923 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4924 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4925 QualType destPointee
4926 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4927 QualType destType = Context.getPointerType(destPointee);
4928 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004929 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004930 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004931 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004932 return destType;
4933 }
4934 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4935 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4936 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4937 QualType destPointee
4938 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4939 QualType destType = Context.getPointerType(destPointee);
4940 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004941 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004942 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004943 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004944 return destType;
4945 }
4946 return QualType();
4947}
4948
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004949/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004950/// ParenRange in parentheses.
4951static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004952 const PartialDiagnostic &Note,
4953 SourceRange ParenRange) {
4954 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4955 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4956 EndLoc.isValid()) {
4957 Self.Diag(Loc, Note)
4958 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4959 << FixItHint::CreateInsertion(EndLoc, ")");
4960 } else {
4961 // We can't display the parentheses, so just show the bare note.
4962 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004963 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004964}
4965
4966static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4967 return Opc >= BO_Mul && Opc <= BO_Shr;
4968}
4969
Hans Wennborg2f072b42011-06-09 17:06:51 +00004970/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4971/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00004972/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4973/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00004974static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00004975 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004976 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4977 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004978 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004979 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004980
4981 // Built-in binary operator.
4982 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4983 if (IsArithmeticOp(OP->getOpcode())) {
4984 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00004985 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004986 return true;
4987 }
4988 }
4989
4990 // Overloaded operator.
4991 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4992 if (Call->getNumArgs() != 2)
4993 return false;
4994
4995 // Make sure this is really a binary operator that is safe to pass into
4996 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4997 OverloadedOperatorKind OO = Call->getOperator();
4998 if (OO < OO_Plus || OO > OO_Arrow)
4999 return false;
5000
5001 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5002 if (IsArithmeticOp(OpKind)) {
5003 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005004 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005005 return true;
5006 }
5007 }
5008
5009 return false;
5010}
5011
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005012static bool IsLogicOp(BinaryOperatorKind Opc) {
5013 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5014}
5015
Hans Wennborg2f072b42011-06-09 17:06:51 +00005016/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5017/// or is a logical expression such as (x==y) which has int type, but is
5018/// commonly interpreted as boolean.
5019static bool ExprLooksBoolean(Expr *E) {
5020 E = E->IgnoreParenImpCasts();
5021
5022 if (E->getType()->isBooleanType())
5023 return true;
5024 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5025 return IsLogicOp(OP->getOpcode());
5026 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5027 return OP->getOpcode() == UO_LNot;
5028
5029 return false;
5030}
5031
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005032/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5033/// and binary operator are mixed in a way that suggests the programmer assumed
5034/// the conditional operator has higher precedence, for example:
5035/// "int x = a + someBinaryCondition ? 1 : 2".
5036static void DiagnoseConditionalPrecedence(Sema &Self,
5037 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005038 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005039 Expr *LHSExpr,
5040 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005041 BinaryOperatorKind CondOpcode;
5042 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005043
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005044 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005045 return;
5046 if (!ExprLooksBoolean(CondRHS))
5047 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005048
Hans Wennborg2f072b42011-06-09 17:06:51 +00005049 // The condition is an arithmetic binary expression, with a right-
5050 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005051
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005052 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005053 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005054 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005055
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005056 SuggestParentheses(Self, OpLoc,
5057 Self.PDiag(diag::note_precedence_conditional_silence)
5058 << BinaryOperator::getOpcodeStr(CondOpcode),
5059 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005060
5061 SuggestParentheses(Self, OpLoc,
5062 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005063 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005064}
5065
Steve Narofff69936d2007-09-16 03:34:24 +00005066/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005067/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005068ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005069 SourceLocation ColonLoc,
5070 Expr *CondExpr, Expr *LHSExpr,
5071 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005072 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5073 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005074 OpaqueValueExpr *opaqueValue = 0;
5075 Expr *commonExpr = 0;
5076 if (LHSExpr == 0) {
5077 commonExpr = CondExpr;
5078
5079 // We usually want to apply unary conversions *before* saving, except
5080 // in the special case of a C++ l-value conditional.
5081 if (!(getLangOptions().CPlusPlus
5082 && !commonExpr->isTypeDependent()
5083 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5084 && commonExpr->isGLValue()
5085 && commonExpr->isOrdinaryOrBitFieldObject()
5086 && RHSExpr->isOrdinaryOrBitFieldObject()
5087 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005088 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5089 if (commonRes.isInvalid())
5090 return ExprError();
5091 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005092 }
5093
5094 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5095 commonExpr->getType(),
5096 commonExpr->getValueKind(),
5097 commonExpr->getObjectKind());
5098 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005099 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005100
John McCallf89e55a2010-11-18 06:31:45 +00005101 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005102 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005103 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5104 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005105 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005106 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5107 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005108 return ExprError();
5109
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005110 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5111 RHS.get());
5112
John McCall56ca35d2011-02-17 10:25:35 +00005113 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005114 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5115 LHS.take(), ColonLoc,
5116 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005117
5118 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005119 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005120 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5121 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005122}
5123
John McCalle4be87e2011-01-31 23:13:11 +00005124// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005125// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005126// routine is it effectively iqnores the qualifiers on the top level pointee.
5127// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5128// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005129static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005130checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5131 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5132 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005133
Reid Spencer5f016e22007-07-11 17:01:13 +00005134 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005135 const Type *lhptee, *rhptee;
5136 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005137 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5138 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005139
John McCalle4be87e2011-01-31 23:13:11 +00005140 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005141
5142 // C99 6.5.16.1p1: This following citation is common to constraints
5143 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5144 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005145 Qualifiers lq;
5146
John McCallf85e1932011-06-15 23:02:42 +00005147 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5148 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5149 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5150 // Ignore lifetime for further calculation.
5151 lhq.removeObjCLifetime();
5152 rhq.removeObjCLifetime();
5153 }
5154
John McCall86c05f32011-02-01 00:10:29 +00005155 if (!lhq.compatiblyIncludes(rhq)) {
5156 // Treat address-space mismatches as fatal. TODO: address subspaces
5157 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5158 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5159
John McCallf85e1932011-06-15 23:02:42 +00005160 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005161 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005162 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5163 .compatiblyIncludes(
5164 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005165 && (lhptee->isVoidType() || rhptee->isVoidType()))
5166 ; // keep old
5167
John McCallf85e1932011-06-15 23:02:42 +00005168 // Treat lifetime mismatches as fatal.
5169 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5170 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5171
John McCall86c05f32011-02-01 00:10:29 +00005172 // For GCC compatibility, other qualifier mismatches are treated
5173 // as still compatible in C.
5174 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5175 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005176
Mike Stumpeed9cac2009-02-19 03:04:26 +00005177 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5178 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005179 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005180 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005181 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005182 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005183
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005184 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005185 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005186 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005187 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005188
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005189 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005190 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005191 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005192
5193 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005194 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005195 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005196 }
John McCall86c05f32011-02-01 00:10:29 +00005197
Mike Stumpeed9cac2009-02-19 03:04:26 +00005198 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005199 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005200 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5201 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005202 // Check if the pointee types are compatible ignoring the sign.
5203 // We explicitly check for char so that we catch "char" vs
5204 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005205 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005206 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005207 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005208 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005209
Chris Lattner6a2b9262009-10-17 20:33:28 +00005210 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005211 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005212 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005213 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005214
John McCall86c05f32011-02-01 00:10:29 +00005215 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005216 // Types are compatible ignoring the sign. Qualifier incompatibility
5217 // takes priority over sign incompatibility because the sign
5218 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005219 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005220 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005221
John McCalle4be87e2011-01-31 23:13:11 +00005222 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005223 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005224
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005225 // If we are a multi-level pointer, it's possible that our issue is simply
5226 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5227 // the eventual target type is the same and the pointers have the same
5228 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005229 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005230 do {
John McCall86c05f32011-02-01 00:10:29 +00005231 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5232 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005233 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005234
John McCall86c05f32011-02-01 00:10:29 +00005235 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005236 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005237 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005238
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005239 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005240 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005241 }
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005242 if (!S.getLangOptions().CPlusPlus &&
5243 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5244 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005245 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005246}
5247
John McCalle4be87e2011-01-31 23:13:11 +00005248/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005249/// block pointer types are compatible or whether a block and normal pointer
5250/// are compatible. It is more restrict than comparing two function pointer
5251// types.
John McCalle4be87e2011-01-31 23:13:11 +00005252static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005253checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5254 QualType RHSType) {
5255 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5256 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005257
Steve Naroff1c7d0672008-09-04 15:10:53 +00005258 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005259
Steve Naroff1c7d0672008-09-04 15:10:53 +00005260 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005261 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5262 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005263
John McCalle4be87e2011-01-31 23:13:11 +00005264 // In C++, the types have to match exactly.
5265 if (S.getLangOptions().CPlusPlus)
5266 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005267
John McCalle4be87e2011-01-31 23:13:11 +00005268 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005269
Steve Naroff1c7d0672008-09-04 15:10:53 +00005270 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005271 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5272 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005273
Richard Trieu1da27a12011-09-06 20:21:22 +00005274 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005275 return Sema::IncompatibleBlockPointer;
5276
Steve Naroff1c7d0672008-09-04 15:10:53 +00005277 return ConvTy;
5278}
5279
John McCalle4be87e2011-01-31 23:13:11 +00005280/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005281/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005282static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005283checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5284 QualType RHSType) {
5285 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5286 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005287
Richard Trieu1da27a12011-09-06 20:21:22 +00005288 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005289 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005290 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5291 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005292 return Sema::IncompatiblePointer;
5293 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005294 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005295 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005296 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5297 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005298 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005299 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005300 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005301 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5302 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005303
John McCalle4be87e2011-01-31 23:13:11 +00005304 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5305 return Sema::CompatiblePointerDiscardsQualifiers;
5306
Richard Trieu1da27a12011-09-06 20:21:22 +00005307 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005308 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005309 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005310 return Sema::IncompatibleObjCQualifiedId;
5311 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005312}
5313
John McCall1c23e912010-11-16 02:32:08 +00005314Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005315Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005316 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005317 // Fake up an opaque expression. We don't actually care about what
5318 // cast operations are required, so if CheckAssignmentConstraints
5319 // adds casts to this they'll be wasted, but fortunately that doesn't
5320 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005321 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5322 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005323 CastKind K = CK_Invalid;
5324
Richard Trieu1da27a12011-09-06 20:21:22 +00005325 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005326}
5327
Mike Stumpeed9cac2009-02-19 03:04:26 +00005328/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5329/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005330/// pointers. Here are some objectionable examples that GCC considers warnings:
5331///
5332/// int a, *pint;
5333/// short *pshort;
5334/// struct foo *pfoo;
5335///
5336/// pint = pshort; // warning: assignment from incompatible pointer type
5337/// a = pint; // warning: assignment makes integer from pointer without a cast
5338/// pint = a; // warning: assignment makes pointer from integer without a cast
5339/// pint = pfoo; // warning: assignment from incompatible pointer type
5340///
5341/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005342/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005343///
John McCalldaa8e4e2010-11-15 09:13:47 +00005344/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005345Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005346Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005347 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005348 QualType RHSType = RHS.get()->getType();
5349 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005350
Chris Lattnerfc144e22008-01-04 23:18:45 +00005351 // Get canonical types. We're not formatting these types, just comparing
5352 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005353 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5354 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005355
Eli Friedmanb001de72011-10-06 23:00:33 +00005356 // We can't do assignment from/to atomics yet.
5357 if (LHSType->isAtomicType())
5358 return Incompatible;
5359
John McCallb6cfa242011-01-31 22:28:28 +00005360 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005361 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005363 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005364 }
5365
Douglas Gregor9d293df2008-10-28 00:22:11 +00005366 // If the left-hand side is a reference type, then we are in a
5367 // (rare!) case where we've allowed the use of references in C,
5368 // e.g., as a parameter type in a built-in function. In this case,
5369 // just make sure that the type referenced is compatible with the
5370 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005371 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005372 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005373 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5374 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005375 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005376 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005377 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005378 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005379 }
John McCallb6cfa242011-01-31 22:28:28 +00005380
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005381 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5382 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005383 if (LHSType->isExtVectorType()) {
5384 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005385 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005386 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005387 // CK_VectorSplat does T -> vector T, so first cast to the
5388 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005389 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5390 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005391 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005392 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005393 }
5394 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005395 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005396 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398
John McCallb6cfa242011-01-31 22:28:28 +00005399 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005400 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5401 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005402 // Allow assignments of an AltiVec vector type to an equivalent GCC
5403 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005404 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005405 Kind = CK_BitCast;
5406 return Compatible;
5407 }
5408
Douglas Gregor255210e2010-08-06 10:14:59 +00005409 // If we are allowing lax vector conversions, and LHS and RHS are both
5410 // vectors, the total size only needs to be the same. This is a bitcast;
5411 // no bits are changed but the result type is different.
5412 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005413 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005414 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005415 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005416 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005417 }
5418 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005419 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005420
John McCallb6cfa242011-01-31 22:28:28 +00005421 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005422 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5423 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005424 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005425 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005426 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005427
John McCallb6cfa242011-01-31 22:28:28 +00005428 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005429 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005430 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005431 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005432 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005433 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005434 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005435
John McCallb6cfa242011-01-31 22:28:28 +00005436 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005437 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005438 Kind = CK_IntegralToPointer; // FIXME: null?
5439 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005440 }
John McCallb6cfa242011-01-31 22:28:28 +00005441
5442 // C pointers are not compatible with ObjC object pointers,
5443 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005444 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005445 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005446 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005447 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005448 return Compatible;
5449 }
5450
5451 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005452 if (RHSType->isObjCClassType() &&
5453 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005454 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005455 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005456 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005457 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005458
John McCallb6cfa242011-01-31 22:28:28 +00005459 Kind = CK_BitCast;
5460 return IncompatiblePointer;
5461 }
5462
5463 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005464 if (RHSType->getAs<BlockPointerType>()) {
5465 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005466 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005467 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005468 }
Steve Naroffb4406862008-09-29 18:10:17 +00005469 }
John McCallb6cfa242011-01-31 22:28:28 +00005470
Steve Naroff1c7d0672008-09-04 15:10:53 +00005471 return Incompatible;
5472 }
5473
John McCallb6cfa242011-01-31 22:28:28 +00005474 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005475 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005476 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005477 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005478 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005479 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005480 }
5481
5482 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005483 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005484 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005485 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005486 }
5487
John McCallb6cfa242011-01-31 22:28:28 +00005488 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005489 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005490 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005491 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005492 }
Steve Naroffb4406862008-09-29 18:10:17 +00005493
John McCallb6cfa242011-01-31 22:28:28 +00005494 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005495 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005496 if (RHSPT->getPointeeType()->isVoidType()) {
5497 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005498 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005499 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005500
Chris Lattnerfc144e22008-01-04 23:18:45 +00005501 return Incompatible;
5502 }
5503
John McCallb6cfa242011-01-31 22:28:28 +00005504 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005505 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005506 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005507 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005508 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005509 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005510 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005511 if (getLangOptions().ObjCAutoRefCount &&
5512 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005513 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005514 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005515 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005516 }
5517
5518 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005519 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005520 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005521 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005522 }
5523
John McCallb6cfa242011-01-31 22:28:28 +00005524 // In general, C pointers are not compatible with ObjC object pointers,
5525 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005526 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005527 Kind = CK_CPointerToObjCPointerCast;
5528
John McCallb6cfa242011-01-31 22:28:28 +00005529 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005530 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005531 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005532 }
5533
5534 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005535 if (LHSType->isObjCClassType() &&
5536 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005537 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005538 return Compatible;
5539 }
5540
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005541 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005542 }
John McCallb6cfa242011-01-31 22:28:28 +00005543
5544 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005545 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005546 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005547 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005548 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005549 }
5550
Steve Naroff14108da2009-07-10 23:34:53 +00005551 return Incompatible;
5552 }
John McCallb6cfa242011-01-31 22:28:28 +00005553
5554 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005555 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005556 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005557 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005558 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005559 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005560 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005561
John McCallb6cfa242011-01-31 22:28:28 +00005562 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005563 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005564 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005565 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005566 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005567
Chris Lattnerfc144e22008-01-04 23:18:45 +00005568 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005569 }
John McCallb6cfa242011-01-31 22:28:28 +00005570
5571 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005572 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005573 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005574 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005575 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005576 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005577 }
Steve Naroff14108da2009-07-10 23:34:53 +00005578
John McCallb6cfa242011-01-31 22:28:28 +00005579 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005580 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005581 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005582 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005583 }
5584
Steve Naroff14108da2009-07-10 23:34:53 +00005585 return Incompatible;
5586 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005587
John McCallb6cfa242011-01-31 22:28:28 +00005588 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005589 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5590 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005591 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005592 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005594 }
John McCallb6cfa242011-01-31 22:28:28 +00005595
Reid Spencer5f016e22007-07-11 17:01:13 +00005596 return Incompatible;
5597}
5598
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005599/// \brief Constructs a transparent union from an expression that is
5600/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005601static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5602 ExprResult &EResult, QualType UnionType,
5603 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005604 // Build an initializer list that designates the appropriate member
5605 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005606 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005607 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005608 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005609 SourceLocation());
5610 Initializer->setType(UnionType);
5611 Initializer->setInitializedFieldInUnion(Field);
5612
5613 // Build a compound literal constructing a value of the transparent
5614 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005615 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005616 EResult = S.Owned(
5617 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5618 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005619}
5620
5621Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005622Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005623 ExprResult &RHS) {
5624 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005625
Mike Stump1eb44332009-09-09 15:08:12 +00005626 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005627 // transparent_union GCC extension.
5628 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005629 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005630 return Incompatible;
5631
5632 // The field to initialize within the transparent union.
5633 RecordDecl *UD = UT->getDecl();
5634 FieldDecl *InitField = 0;
5635 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005636 for (RecordDecl::field_iterator it = UD->field_begin(),
5637 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005638 it != itend; ++it) {
5639 if (it->getType()->isPointerType()) {
5640 // If the transparent union contains a pointer type, we allow:
5641 // 1) void pointer
5642 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005643 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005644 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005645 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005646 InitField = *it;
5647 break;
5648 }
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Richard Trieuf7720da2011-09-06 20:40:12 +00005650 if (RHS.get()->isNullPointerConstant(Context,
5651 Expr::NPC_ValueDependentIsNull)) {
5652 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5653 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005654 InitField = *it;
5655 break;
5656 }
5657 }
5658
John McCalldaa8e4e2010-11-15 09:13:47 +00005659 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005660 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005661 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005662 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005663 InitField = *it;
5664 break;
5665 }
5666 }
5667
5668 if (!InitField)
5669 return Incompatible;
5670
Richard Trieuf7720da2011-09-06 20:40:12 +00005671 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005672 return Compatible;
5673}
5674
Chris Lattner5cf216b2008-01-04 18:04:52 +00005675Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005676Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5677 bool Diagnose) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005678 if (getLangOptions().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005679 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005680 // C++ 5.17p3: If the left operand is not of class type, the
5681 // expression is implicitly converted (C++ 4) to the
5682 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005683 ExprResult Res;
5684 if (Diagnose) {
5685 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5686 AA_Assigning);
5687 } else {
5688 ImplicitConversionSequence ICS =
5689 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5690 /*SuppressUserConversions=*/false,
5691 /*AllowExplicit=*/false,
5692 /*InOverloadResolution=*/false,
5693 /*CStyle=*/false,
5694 /*AllowObjCWritebackConversion=*/false);
5695 if (ICS.isFailure())
5696 return Incompatible;
5697 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5698 ICS, AA_Assigning);
5699 }
John Wiegley429bb272011-04-08 18:41:53 +00005700 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005701 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005702 Sema::AssignConvertType result = Compatible;
5703 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005704 !CheckObjCARCUnavailableWeakConversion(LHSType,
5705 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005706 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005707 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005708 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005709 }
5710
5711 // FIXME: Currently, we fall through and treat C++ classes like C
5712 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005713 // FIXME: We also fall through for atomics; not sure what should
5714 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005715 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005716
Steve Naroff529a4ad2007-11-27 17:58:44 +00005717 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5718 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005719 if ((LHSType->isPointerType() ||
5720 LHSType->isObjCObjectPointerType() ||
5721 LHSType->isBlockPointerType())
5722 && RHS.get()->isNullPointerConstant(Context,
5723 Expr::NPC_ValueDependentIsNull)) {
5724 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005725 return Compatible;
5726 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005727
Chris Lattner943140e2007-10-16 02:55:40 +00005728 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005729 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005730 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005731 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005732 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005733 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005734 if (!LHSType->isReferenceType()) {
5735 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5736 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005737 return Incompatible;
5738 }
Steve Narofff1120de2007-08-24 22:33:52 +00005739
John McCalldaa8e4e2010-11-15 09:13:47 +00005740 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005741 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005742 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005743
Steve Narofff1120de2007-08-24 22:33:52 +00005744 // C99 6.5.16.1p2: The value of the right operand is converted to the
5745 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005746 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5747 // so that we can use references in built-in functions even in C.
5748 // The getNonReferenceType() call makes sure that the resulting expression
5749 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005750 if (result != Incompatible && RHS.get()->getType() != LHSType)
5751 RHS = ImpCastExprToType(RHS.take(),
5752 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005753 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005754}
5755
Richard Trieuf7720da2011-09-06 20:40:12 +00005756QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5757 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005758 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005759 << LHS.get()->getType() << RHS.get()->getType()
5760 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005761 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005762}
5763
Richard Trieu08062aa2011-09-06 21:01:04 +00005764QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005765 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005766 if (!IsCompAssign) {
5767 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5768 if (LHS.isInvalid())
5769 return QualType();
5770 }
5771 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5772 if (RHS.isInvalid())
5773 return QualType();
5774
Mike Stumpeed9cac2009-02-19 03:04:26 +00005775 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005776 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005777 QualType LHSType =
5778 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5779 QualType RHSType =
5780 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005781
Nate Begemanbe2341d2008-07-14 18:02:46 +00005782 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005783 if (LHSType == RHSType)
5784 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005785
Douglas Gregor255210e2010-08-06 10:14:59 +00005786 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005787 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5788 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5789 if (LHSType->isExtVectorType()) {
5790 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5791 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005792 }
5793
Richard Trieuccd891a2011-09-09 01:45:06 +00005794 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005795 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5796 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005797 }
5798
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005799 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005800 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005801 // If we are allowing lax vector conversions, and LHS and RHS are both
5802 // vectors, the total size only needs to be the same. This is a
5803 // bitcast; no bits are changed but the result type is different.
5804 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005805 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5806 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005807 }
5808
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005809 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5810 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5811 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005812 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005813 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005814 std::swap(RHS, LHS);
5815 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005816 }
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Nate Begemandde25982009-06-28 19:12:57 +00005818 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005819 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005820 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005821 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5822 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005823 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005824 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005825 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005826 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5827 if (swapped) std::swap(RHS, LHS);
5828 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005829 }
5830 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005831 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5832 RHSType->isRealFloatingType()) {
5833 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005834 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005835 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005836 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005837 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5838 if (swapped) std::swap(RHS, LHS);
5839 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005840 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005841 }
5842 }
Mike Stump1eb44332009-09-09 15:08:12 +00005843
Nate Begemandde25982009-06-28 19:12:57 +00005844 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005845 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005846 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005847 << LHS.get()->getType() << RHS.get()->getType()
5848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005849 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005850}
5851
Richard Trieu481037f2011-09-16 00:53:10 +00005852// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5853// expression. These are mainly cases where the null pointer is used as an
5854// integer instead of a pointer.
5855static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5856 SourceLocation Loc, bool IsCompare) {
5857 // The canonical way to check for a GNU null is with isNullPointerConstant,
5858 // but we use a bit of a hack here for speed; this is a relatively
5859 // hot path, and isNullPointerConstant is slow.
5860 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5861 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5862
5863 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5864
5865 // Avoid analyzing cases where the result will either be invalid (and
5866 // diagnosed as such) or entirely valid and not something to warn about.
5867 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5868 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5869 return;
5870
5871 // Comparison operations would not make sense with a null pointer no matter
5872 // what the other expression is.
5873 if (!IsCompare) {
5874 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5875 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5876 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5877 return;
5878 }
5879
5880 // The rest of the operations only make sense with a null pointer
5881 // if the other expression is a pointer.
5882 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5883 NonNullType->canDecayToPointerType())
5884 return;
5885
5886 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5887 << LHSNull /* LHS is NULL */ << NonNullType
5888 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5889}
5890
Richard Trieu08062aa2011-09-06 21:01:04 +00005891QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005892 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005893 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00005894 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5895
Richard Trieu08062aa2011-09-06 21:01:04 +00005896 if (LHS.get()->getType()->isVectorType() ||
5897 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005898 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005899
Richard Trieuccd891a2011-09-09 01:45:06 +00005900 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005901 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005902 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005903
Richard Trieu08062aa2011-09-06 21:01:04 +00005904 if (!LHS.get()->getType()->isArithmeticType() ||
5905 !RHS.get()->getType()->isArithmeticType())
5906 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005907
Chris Lattner7ef655a2010-01-12 21:23:57 +00005908 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005909 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005910 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005911 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005912 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5913 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005914
Chris Lattner7ef655a2010-01-12 21:23:57 +00005915 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005916}
5917
Chris Lattner7ef655a2010-01-12 21:23:57 +00005918QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005919 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00005920 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5921
Richard Trieu08062aa2011-09-06 21:01:04 +00005922 if (LHS.get()->getType()->isVectorType() ||
5923 RHS.get()->getType()->isVectorType()) {
5924 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5925 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005926 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005927 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005928 }
Steve Naroff90045e82007-07-13 23:32:42 +00005929
Richard Trieuccd891a2011-09-09 01:45:06 +00005930 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005931 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005932 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005933
Richard Trieu08062aa2011-09-06 21:01:04 +00005934 if (!LHS.get()->getType()->isIntegerType() ||
5935 !RHS.get()->getType()->isIntegerType())
5936 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005937
Chris Lattner7ef655a2010-01-12 21:23:57 +00005938 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005939 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005940 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005941 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5942 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005943
Chris Lattner7ef655a2010-01-12 21:23:57 +00005944 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005945}
5946
Chandler Carruth13b21be2011-06-27 08:02:19 +00005947/// \brief Diagnose invalid arithmetic on two void pointers.
5948static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005949 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005950 S.Diag(Loc, S.getLangOptions().CPlusPlus
5951 ? diag::err_typecheck_pointer_arith_void_type
5952 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005953 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5954 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005955}
5956
5957/// \brief Diagnose invalid arithmetic on a void pointer.
5958static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5959 Expr *Pointer) {
5960 S.Diag(Loc, S.getLangOptions().CPlusPlus
5961 ? diag::err_typecheck_pointer_arith_void_type
5962 : diag::ext_gnu_void_ptr)
5963 << 0 /* one pointer */ << Pointer->getSourceRange();
5964}
5965
5966/// \brief Diagnose invalid arithmetic on two function pointers.
5967static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5968 Expr *LHS, Expr *RHS) {
5969 assert(LHS->getType()->isAnyPointerType());
5970 assert(RHS->getType()->isAnyPointerType());
5971 S.Diag(Loc, S.getLangOptions().CPlusPlus
5972 ? diag::err_typecheck_pointer_arith_function_type
5973 : diag::ext_gnu_ptr_func_arith)
5974 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5975 // We only show the second type if it differs from the first.
5976 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5977 RHS->getType())
5978 << RHS->getType()->getPointeeType()
5979 << LHS->getSourceRange() << RHS->getSourceRange();
5980}
5981
5982/// \brief Diagnose invalid arithmetic on a function pointer.
5983static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5984 Expr *Pointer) {
5985 assert(Pointer->getType()->isAnyPointerType());
5986 S.Diag(Loc, S.getLangOptions().CPlusPlus
5987 ? diag::err_typecheck_pointer_arith_function_type
5988 : diag::ext_gnu_ptr_func_arith)
5989 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5990 << 0 /* one pointer, so only one type */
5991 << Pointer->getSourceRange();
5992}
5993
Richard Trieud9f19342011-09-12 18:08:02 +00005994/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00005995///
5996/// \returns True if pointer has incomplete type
5997static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5998 Expr *Operand) {
5999 if ((Operand->getType()->isPointerType() &&
6000 !Operand->getType()->isDependentType()) ||
6001 Operand->getType()->isObjCObjectPointerType()) {
6002 QualType PointeeTy = Operand->getType()->getPointeeType();
6003 if (S.RequireCompleteType(
6004 Loc, PointeeTy,
6005 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6006 << PointeeTy << Operand->getSourceRange()))
6007 return true;
6008 }
6009 return false;
6010}
6011
Chandler Carruth13b21be2011-06-27 08:02:19 +00006012/// \brief Check the validity of an arithmetic pointer operand.
6013///
6014/// If the operand has pointer type, this code will check for pointer types
6015/// which are invalid in arithmetic operations. These will be diagnosed
6016/// appropriately, including whether or not the use is supported as an
6017/// extension.
6018///
6019/// \returns True when the operand is valid to use (even if as an extension).
6020static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6021 Expr *Operand) {
6022 if (!Operand->getType()->isAnyPointerType()) return true;
6023
6024 QualType PointeeTy = Operand->getType()->getPointeeType();
6025 if (PointeeTy->isVoidType()) {
6026 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6027 return !S.getLangOptions().CPlusPlus;
6028 }
6029 if (PointeeTy->isFunctionType()) {
6030 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6031 return !S.getLangOptions().CPlusPlus;
6032 }
6033
Richard Trieu097ecd22011-09-02 02:15:37 +00006034 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006035
6036 return true;
6037}
6038
6039/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6040/// operands.
6041///
6042/// This routine will diagnose any invalid arithmetic on pointer operands much
6043/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6044/// for emitting a single diagnostic even for operations where both LHS and RHS
6045/// are (potentially problematic) pointers.
6046///
6047/// \returns True when the operand is valid to use (even if as an extension).
6048static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006049 Expr *LHSExpr, Expr *RHSExpr) {
6050 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6051 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006052 if (!isLHSPointer && !isRHSPointer) return true;
6053
6054 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006055 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6056 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006057
6058 // Check for arithmetic on pointers to incomplete types.
6059 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6060 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6061 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006062 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6063 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6064 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006065
6066 return !S.getLangOptions().CPlusPlus;
6067 }
6068
6069 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6070 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6071 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006072 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6073 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6074 RHSExpr);
6075 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006076
6077 return !S.getLangOptions().CPlusPlus;
6078 }
6079
Richard Trieudef75842011-09-06 21:13:51 +00006080 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6081 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006082
Chandler Carruth13b21be2011-06-27 08:02:19 +00006083 return true;
6084}
6085
Richard Trieudb44a6b2011-09-01 22:53:23 +00006086/// \brief Check bad cases where we step over interface counts.
6087static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6088 SourceLocation OpLoc,
6089 Expr *Op) {
6090 assert(Op->getType()->isAnyPointerType());
6091 QualType PointeeTy = Op->getType()->getPointeeType();
6092 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6093 return true;
6094
6095 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6096 << PointeeTy << Op->getSourceRange();
6097 return false;
6098}
6099
Richard Trieud9f19342011-09-12 18:08:02 +00006100/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006101static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006102 Expr *LHSExpr, Expr *RHSExpr) {
6103 assert(LHSExpr->getType()->isAnyPointerType());
6104 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006105 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006106 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6107 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006108}
6109
Chris Lattner7ef655a2010-01-12 21:23:57 +00006110QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006111 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006112 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6113
Richard Trieudef75842011-09-06 21:13:51 +00006114 if (LHS.get()->getType()->isVectorType() ||
6115 RHS.get()->getType()->isVectorType()) {
6116 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006117 if (CompLHSTy) *CompLHSTy = compType;
6118 return compType;
6119 }
Steve Naroff49b45262007-07-13 16:58:59 +00006120
Richard Trieudef75842011-09-06 21:13:51 +00006121 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6122 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006123 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006124
Reid Spencer5f016e22007-07-11 17:01:13 +00006125 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006126 if (LHS.get()->getType()->isArithmeticType() &&
6127 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006128 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006129 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006130 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006131
Eli Friedmand72d16e2008-05-18 18:08:51 +00006132 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006133 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006134 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006135 std::swap(PExp, IExp);
6136
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006137 if (!PExp->getType()->isAnyPointerType())
6138 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006139
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006140 if (!IExp->getType()->isIntegerType())
6141 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006142
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006143 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6144 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006145
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006146 // Diagnose bad cases where we step over interface counts.
6147 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6148 return QualType();
6149
6150 // Check array bounds for pointer arithemtic
6151 CheckArrayAccess(PExp, IExp);
6152
6153 if (CompLHSTy) {
6154 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6155 if (LHSTy.isNull()) {
6156 LHSTy = LHS.get()->getType();
6157 if (LHSTy->isPromotableIntegerType())
6158 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006159 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006160 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006161 }
6162
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006163 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006164}
6165
Chris Lattnereca7be62008-04-07 05:30:13 +00006166// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006167QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006168 SourceLocation Loc,
6169 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006170 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6171
Richard Trieudef75842011-09-06 21:13:51 +00006172 if (LHS.get()->getType()->isVectorType() ||
6173 RHS.get()->getType()->isVectorType()) {
6174 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006175 if (CompLHSTy) *CompLHSTy = compType;
6176 return compType;
6177 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006178
Richard Trieudef75842011-09-06 21:13:51 +00006179 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6180 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006181 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006182
Chris Lattner6e4ab612007-12-09 21:53:25 +00006183 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006184
Chris Lattner6e4ab612007-12-09 21:53:25 +00006185 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006186 if (LHS.get()->getType()->isArithmeticType() &&
6187 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006188 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006189 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006190 }
Mike Stump1eb44332009-09-09 15:08:12 +00006191
Chris Lattner6e4ab612007-12-09 21:53:25 +00006192 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006193 if (LHS.get()->getType()->isAnyPointerType()) {
6194 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006195
Chris Lattnerb5f15622009-04-24 23:50:08 +00006196 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006197 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006198 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006199
Chris Lattner6e4ab612007-12-09 21:53:25 +00006200 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006201 if (RHS.get()->getType()->isIntegerType()) {
6202 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006203 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006204
Richard Trieudef75842011-09-06 21:13:51 +00006205 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006206 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6207 OK_Ordinary, IExpr->getExprLoc());
6208 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006209 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006210
Richard Trieudef75842011-09-06 21:13:51 +00006211 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6212 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006213 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006214
Chris Lattner6e4ab612007-12-09 21:53:25 +00006215 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006216 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006217 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006218 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006219
Eli Friedman88d936b2009-05-16 13:54:38 +00006220 if (getLangOptions().CPlusPlus) {
6221 // Pointee types must be the same: C++ [expr.add]
6222 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006223 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006224 }
6225 } else {
6226 // Pointee types must be compatible C99 6.5.6p3
6227 if (!Context.typesAreCompatible(
6228 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6229 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006230 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006231 return QualType();
6232 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006233 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006234
Chandler Carruth13b21be2011-06-27 08:02:19 +00006235 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006236 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006237 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006238
Richard Trieudef75842011-09-06 21:13:51 +00006239 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006240 return Context.getPointerDiffType();
6241 }
6242 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006243
Richard Trieudef75842011-09-06 21:13:51 +00006244 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006245}
6246
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006247static bool isScopedEnumerationType(QualType T) {
6248 if (const EnumType *ET = dyn_cast<EnumType>(T))
6249 return ET->getDecl()->isScoped();
6250 return false;
6251}
6252
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006253static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006254 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006255 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006256 llvm::APSInt Right;
6257 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006258 if (RHS.get()->isValueDependent() ||
6259 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006260 return;
6261
6262 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006263 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006264 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006265 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006266 return;
6267 }
6268 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006269 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006270 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006271 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006272 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006273 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006274 return;
6275 }
6276 if (Opc != BO_Shl)
6277 return;
6278
6279 // When left shifting an ICE which is signed, we can check for overflow which
6280 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6281 // integers have defined behavior modulo one more than the maximum value
6282 // representable in the result type, so never warn for those.
6283 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006284 if (LHS.get()->isValueDependent() ||
6285 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6286 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006287 return;
6288 llvm::APInt ResultBits =
6289 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6290 if (LeftBits.uge(ResultBits))
6291 return;
6292 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6293 Result = Result.shl(Right);
6294
Ted Kremenekfa821382011-06-15 00:54:52 +00006295 // Print the bit representation of the signed integer as an unsigned
6296 // hexadecimal number.
6297 llvm::SmallString<40> HexResult;
6298 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6299
Chandler Carruth21206d52011-02-23 23:34:11 +00006300 // If we are only missing a sign bit, this is less likely to result in actual
6301 // bugs -- if the result is cast back to an unsigned type, it will have the
6302 // expected value. Thus we place this behind a different warning that can be
6303 // turned off separately if needed.
6304 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006305 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006306 << HexResult.str() << LHSType
6307 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006308 return;
6309 }
6310
6311 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006312 << HexResult.str() << Result.getMinSignedBits() << LHSType
6313 << Left.getBitWidth() << LHS.get()->getSourceRange()
6314 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006315}
6316
Chris Lattnereca7be62008-04-07 05:30:13 +00006317// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006318QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006319 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006320 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006321 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6322
Chris Lattnerca5eede2007-12-12 05:47:28 +00006323 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006324 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6325 !RHS.get()->getType()->hasIntegerRepresentation())
6326 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006327
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006328 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6329 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006330 if (isScopedEnumerationType(LHS.get()->getType()) ||
6331 isScopedEnumerationType(RHS.get()->getType())) {
6332 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006333 }
6334
Nate Begeman2207d792009-10-25 02:26:48 +00006335 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006336 if (LHS.get()->getType()->isVectorType() ||
6337 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006338 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006339
Chris Lattnerca5eede2007-12-12 05:47:28 +00006340 // Shifts don't perform usual arithmetic conversions, they just do integer
6341 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006342
John McCall1bc80af2010-12-16 19:28:59 +00006343 // For the LHS, do usual unary conversions, but then reset them away
6344 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006345 ExprResult OldLHS = LHS;
6346 LHS = UsualUnaryConversions(LHS.take());
6347 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006348 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006349 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006350 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006351
6352 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006353 RHS = UsualUnaryConversions(RHS.take());
6354 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006355 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006356
Ryan Flynnd0439682009-08-07 16:20:20 +00006357 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006358 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006359
Chris Lattnerca5eede2007-12-12 05:47:28 +00006360 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006361 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006362}
6363
Chandler Carruth99919472010-07-10 12:30:03 +00006364static bool IsWithinTemplateSpecialization(Decl *D) {
6365 if (DeclContext *DC = D->getDeclContext()) {
6366 if (isa<ClassTemplateSpecializationDecl>(DC))
6367 return true;
6368 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6369 return FD->isFunctionTemplateSpecialization();
6370 }
6371 return false;
6372}
6373
Richard Trieue648ac32011-09-02 03:48:46 +00006374/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006375static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6376 ExprResult &RHS) {
6377 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6378 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006379
6380 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6381 if (!LHSEnumType)
6382 return;
6383 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6384 if (!RHSEnumType)
6385 return;
6386
6387 // Ignore anonymous enums.
6388 if (!LHSEnumType->getDecl()->getIdentifier())
6389 return;
6390 if (!RHSEnumType->getDecl()->getIdentifier())
6391 return;
6392
6393 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6394 return;
6395
6396 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6397 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006398 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006399}
6400
Richard Trieu7be1be02011-09-02 02:55:45 +00006401/// \brief Diagnose bad pointer comparisons.
6402static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006403 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006404 bool IsError) {
6405 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006406 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006407 << LHS.get()->getType() << RHS.get()->getType()
6408 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006409}
6410
6411/// \brief Returns false if the pointers are converted to a composite type,
6412/// true otherwise.
6413static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006414 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006415 // C++ [expr.rel]p2:
6416 // [...] Pointer conversions (4.10) and qualification
6417 // conversions (4.4) are performed on pointer operands (or on
6418 // a pointer operand and a null pointer constant) to bring
6419 // them to their composite pointer type. [...]
6420 //
6421 // C++ [expr.eq]p1 uses the same notion for (in)equality
6422 // comparisons of pointers.
6423
6424 // C++ [expr.eq]p2:
6425 // In addition, pointers to members can be compared, or a pointer to
6426 // member and a null pointer constant. Pointer to member conversions
6427 // (4.11) and qualification conversions (4.4) are performed to bring
6428 // them to a common type. If one operand is a null pointer constant,
6429 // the common type is the type of the other operand. Otherwise, the
6430 // common type is a pointer to member type similar (4.4) to the type
6431 // of one of the operands, with a cv-qualification signature (4.4)
6432 // that is the union of the cv-qualification signatures of the operand
6433 // types.
6434
Richard Trieuba261492011-09-06 21:27:33 +00006435 QualType LHSType = LHS.get()->getType();
6436 QualType RHSType = RHS.get()->getType();
6437 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6438 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006439
6440 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006441 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006442 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006443 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006444 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006445 return true;
6446 }
6447
6448 if (NonStandardCompositeType)
6449 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006450 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6451 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006452
Richard Trieuba261492011-09-06 21:27:33 +00006453 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6454 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006455 return false;
6456}
6457
6458static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006459 ExprResult &LHS,
6460 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006461 bool IsError) {
6462 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6463 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006464 << LHS.get()->getType() << RHS.get()->getType()
6465 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006466}
6467
Douglas Gregor0c6db942009-05-04 06:07:12 +00006468// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006469QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006470 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006471 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006472 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6473
John McCall2de56d12010-08-25 11:45:40 +00006474 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006475
Chris Lattner02dd4b12009-12-05 05:40:13 +00006476 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006477 if (LHS.get()->getType()->isVectorType() ||
6478 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006479 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006480
Richard Trieuf1775fb2011-09-06 21:43:51 +00006481 QualType LHSType = LHS.get()->getType();
6482 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006483
Richard Trieuf1775fb2011-09-06 21:43:51 +00006484 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6485 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006486
Richard Trieuf1775fb2011-09-06 21:43:51 +00006487 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006488
Richard Trieuf1775fb2011-09-06 21:43:51 +00006489 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006490 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006491 !LHS.get()->getLocStart().isMacroID() &&
6492 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006493 // For non-floating point types, check for self-comparisons of the form
6494 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6495 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006496 //
6497 // NOTE: Don't warn about comparison expressions resulting from macro
6498 // expansion. Also don't warn about comparisons which are only self
6499 // comparisons within a template specialization. The warnings should catch
6500 // obvious cases in the definition of the template anyways. The idea is to
6501 // warn when the typed comparison operator will always evaluate to the same
6502 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006503 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006504 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006505 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006506 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006507 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006508 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006509 << (Opc == BO_EQ
6510 || Opc == BO_LE
6511 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006512 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006513 !DRL->getDecl()->getType()->isReferenceType() &&
6514 !DRR->getDecl()->getType()->isReferenceType()) {
6515 // what is it always going to eval to?
6516 char always_evals_to;
6517 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006518 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006519 always_evals_to = 0; // false
6520 break;
John McCall2de56d12010-08-25 11:45:40 +00006521 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006522 always_evals_to = 1; // true
6523 break;
6524 default:
6525 // best we can say is 'a constant'
6526 always_evals_to = 2; // e.g. array1 <= array2
6527 break;
6528 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006529 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006530 << 1 // array
6531 << always_evals_to);
6532 }
6533 }
Chandler Carruth99919472010-07-10 12:30:03 +00006534 }
Mike Stump1eb44332009-09-09 15:08:12 +00006535
Chris Lattner55660a72009-03-08 19:39:53 +00006536 if (isa<CastExpr>(LHSStripped))
6537 LHSStripped = LHSStripped->IgnoreParenCasts();
6538 if (isa<CastExpr>(RHSStripped))
6539 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006540
Chris Lattner55660a72009-03-08 19:39:53 +00006541 // Warn about comparisons against a string constant (unless the other
6542 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006543 Expr *literalString = 0;
6544 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006545 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006546 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006547 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006548 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006549 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006550 } else if ((isa<StringLiteral>(RHSStripped) ||
6551 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006552 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006553 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006554 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006555 literalStringStripped = RHSStripped;
6556 }
6557
6558 if (literalString) {
6559 std::string resultComparison;
6560 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006561 case BO_LT: resultComparison = ") < 0"; break;
6562 case BO_GT: resultComparison = ") > 0"; break;
6563 case BO_LE: resultComparison = ") <= 0"; break;
6564 case BO_GE: resultComparison = ") >= 0"; break;
6565 case BO_EQ: resultComparison = ") == 0"; break;
6566 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006567 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006568 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006569
Ted Kremenek351ba912011-02-23 01:52:04 +00006570 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006571 PDiag(diag::warn_stringcompare)
6572 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006573 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006574 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006575 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006576
Douglas Gregord64fdd02010-06-08 19:50:34 +00006577 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006578 if (LHS.get()->getType()->isArithmeticType() &&
6579 RHS.get()->getType()->isArithmeticType()) {
6580 UsualArithmeticConversions(LHS, RHS);
6581 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006582 return QualType();
6583 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006584 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006585 LHS = UsualUnaryConversions(LHS.take());
6586 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006587 return QualType();
6588
Richard Trieuf1775fb2011-09-06 21:43:51 +00006589 RHS = UsualUnaryConversions(RHS.take());
6590 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006591 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006592 }
6593
Richard Trieuf1775fb2011-09-06 21:43:51 +00006594 LHSType = LHS.get()->getType();
6595 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006596
Douglas Gregor447b69e2008-11-19 03:25:36 +00006597 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006598 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006599
Richard Trieuccd891a2011-09-09 01:45:06 +00006600 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006601 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006602 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006603 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006604 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006605 if (LHSType->hasFloatingRepresentation())
6606 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006607
Richard Trieuf1775fb2011-09-06 21:43:51 +00006608 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006609 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006610 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006611
Richard Trieuf1775fb2011-09-06 21:43:51 +00006612 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006613 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006614 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006615 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006616
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006617 // All of the following pointer-related warnings are GCC extensions, except
6618 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006619 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006620 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006621 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006622 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006623 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006624
Douglas Gregor0c6db942009-05-04 06:07:12 +00006625 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006626 if (LCanPointeeTy == RCanPointeeTy)
6627 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006628 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006629 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6630 // Valid unless comparison between non-null pointer and function pointer
6631 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006632 // In a SFINAE context, we treat this as a hard error to maintain
6633 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006634 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6635 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006636 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006637 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006638
6639 if (isSFINAEContext())
6640 return QualType();
6641
Richard Trieuf1775fb2011-09-06 21:43:51 +00006642 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006643 return ResultTy;
6644 }
6645 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006646
Richard Trieuf1775fb2011-09-06 21:43:51 +00006647 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006648 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006649 else
6650 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006651 }
Eli Friedman3075e762009-08-23 00:27:47 +00006652 // C99 6.5.9p2 and C99 6.5.8p2
6653 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6654 RCanPointeeTy.getUnqualifiedType())) {
6655 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006656 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006657 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006658 << LHSType << RHSType << LHS.get()->getSourceRange()
6659 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006660 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006661 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006662 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6663 // Valid unless comparison between non-null pointer and function pointer
6664 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006665 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006666 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006667 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006668 } else {
6669 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006670 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006671 }
John McCall34d6f932011-03-11 04:25:25 +00006672 if (LCanPointeeTy != RCanPointeeTy) {
6673 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006674 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006675 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006676 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006677 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006678 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006679 }
Mike Stump1eb44332009-09-09 15:08:12 +00006680
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006681 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006682 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006683 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006684 return ResultTy;
6685
Mike Stump1eb44332009-09-09 15:08:12 +00006686 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006687 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006688 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006689 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006690 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006691 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6692 RHS = ImpCastExprToType(RHS.take(), LHSType,
6693 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006694 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006695 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006696 return ResultTy;
6697 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006698 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006699 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006700 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006701 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6702 LHS = ImpCastExprToType(LHS.take(), RHSType,
6703 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006704 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006705 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006706 return ResultTy;
6707 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006708
6709 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006710 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006711 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6712 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006713 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006714 else
6715 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006716 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006717
6718 // Handle scoped enumeration types specifically, since they don't promote
6719 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006720 if (LHS.get()->getType()->isEnumeralType() &&
6721 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6722 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006723 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006724 }
Mike Stump1eb44332009-09-09 15:08:12 +00006725
Steve Naroff1c7d0672008-09-04 15:10:53 +00006726 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006727 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006728 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006729 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6730 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006731
Steve Naroff1c7d0672008-09-04 15:10:53 +00006732 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006733 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006734 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006735 << LHSType << RHSType << LHS.get()->getSourceRange()
6736 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006737 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006738 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006739 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006740 }
John Wiegley429bb272011-04-08 18:41:53 +00006741
Steve Naroff59f53942008-09-28 01:11:11 +00006742 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006743 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006744 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6745 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006746 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006747 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006748 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006749 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006750 ->getPointeeType()->isVoidType())))
6751 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006752 << LHSType << RHSType << LHS.get()->getSourceRange()
6753 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006754 }
John McCall34d6f932011-03-11 04:25:25 +00006755 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006756 LHS = ImpCastExprToType(LHS.take(), RHSType,
6757 RHSType->isPointerType() ? CK_BitCast
6758 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006759 else
John McCall1d9b3b22011-09-09 05:25:32 +00006760 RHS = ImpCastExprToType(RHS.take(), LHSType,
6761 LHSType->isPointerType() ? CK_BitCast
6762 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006763 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006764 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006765
Richard Trieuf1775fb2011-09-06 21:43:51 +00006766 if (LHSType->isObjCObjectPointerType() ||
6767 RHSType->isObjCObjectPointerType()) {
6768 const PointerType *LPT = LHSType->getAs<PointerType>();
6769 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006770 if (LPT || RPT) {
6771 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6772 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006773
Steve Naroffa8069f12008-11-17 19:49:16 +00006774 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006775 !Context.typesAreCompatible(LHSType, RHSType)) {
6776 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006777 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006778 }
John McCall34d6f932011-03-11 04:25:25 +00006779 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006780 LHS = ImpCastExprToType(LHS.take(), RHSType,
6781 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006782 else
John McCall1d9b3b22011-09-09 05:25:32 +00006783 RHS = ImpCastExprToType(RHS.take(), LHSType,
6784 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006785 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006786 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006787 if (LHSType->isObjCObjectPointerType() &&
6788 RHSType->isObjCObjectPointerType()) {
6789 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6790 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006791 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006792 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006793 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006794 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006795 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006796 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006797 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006798 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006799 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6800 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006801 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006802 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006803 if ((LHSIsNull && LHSType->isIntegerType()) ||
6804 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006805 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006806 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006807 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006808 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006809 else if (getLangOptions().CPlusPlus) {
6810 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6811 isError = true;
6812 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006813 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006814
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006815 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006816 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006817 << LHSType << RHSType << LHS.get()->getSourceRange()
6818 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006819 if (isError)
6820 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006821 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006822
Richard Trieuf1775fb2011-09-06 21:43:51 +00006823 if (LHSType->isIntegerType())
6824 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006825 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006826 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006827 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006828 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006829 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006830 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006831
Steve Naroff39218df2008-09-04 16:56:14 +00006832 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006833 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006834 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6835 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006836 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006837 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006838 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006839 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6840 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006841 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006842 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006843
Richard Trieuf1775fb2011-09-06 21:43:51 +00006844 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006845}
6846
Nate Begemanbe2341d2008-07-14 18:02:46 +00006847/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006848/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006849/// like a scalar comparison, a vector comparison produces a vector of integer
6850/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006851QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006852 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006853 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006854 // Check to make sure we're operating on vectors of the same type and width,
6855 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006856 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006857 if (vType.isNull())
6858 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006859
Richard Trieu9f60dee2011-09-07 01:19:57 +00006860 QualType LHSType = LHS.get()->getType();
6861 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006862
Anton Yartsev7870b132011-03-27 15:36:07 +00006863 // If AltiVec, the comparison results in a numeric type, i.e.
6864 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006865 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006866 return Context.getLogicalOperationType();
6867
Nate Begemanbe2341d2008-07-14 18:02:46 +00006868 // For non-floating point types, check for self-comparisons of the form
6869 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6870 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006871 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00006872 if (DeclRefExpr* DRL
6873 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6874 if (DeclRefExpr* DRR
6875 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006876 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006877 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006878 PDiag(diag::warn_comparison_always)
6879 << 0 // self-
6880 << 2 // "a constant"
6881 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006882 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006883
Nate Begemanbe2341d2008-07-14 18:02:46 +00006884 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006885 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006886 assert (RHSType->hasFloatingRepresentation());
6887 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006888 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006889
Tanya Lattner6ec96432011-10-17 21:00:38 +00006890 // Return a signed type that is of identical size and number of elements.
6891 // For floating point vectors, return an integer type of identical size
6892 // and number of elements.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006893 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006894 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Tanya Lattner6ec96432011-10-17 21:00:38 +00006895 if (TypeSize == Context.getTypeSize(Context.CharTy))
6896 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6897 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6898 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6899 else if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006900 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Tanya Lattner6ec96432011-10-17 21:00:38 +00006901 else if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006902 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006903 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006904 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006905 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6906}
6907
Reid Spencer5f016e22007-07-11 17:01:13 +00006908inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006909 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006910 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6911
Richard Trieu9f60dee2011-09-07 01:19:57 +00006912 if (LHS.get()->getType()->isVectorType() ||
6913 RHS.get()->getType()->isVectorType()) {
6914 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6915 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006916 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006917
Richard Trieu9f60dee2011-09-07 01:19:57 +00006918 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006919 }
Steve Naroff90045e82007-07-13 23:32:42 +00006920
Richard Trieu9f60dee2011-09-07 01:19:57 +00006921 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6922 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006923 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006924 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006925 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006926 LHS = LHSResult.take();
6927 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006928
Richard Trieu9f60dee2011-09-07 01:19:57 +00006929 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6930 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006931 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006932 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006933}
6934
6935inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006936 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006937
6938 // Diagnose cases where the user write a logical and/or but probably meant a
6939 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6940 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006941 if (LHS.get()->getType()->isIntegerType() &&
6942 !LHS.get()->getType()->isBooleanType() &&
6943 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006944 // Don't warn in macros or template instantiations.
6945 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006946 // If the RHS can be constant folded, and if it constant folds to something
6947 // that isn't 0 or 1 (which indicate a potential logical operation that
6948 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006949 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00006950 llvm::APSInt Result;
6951 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieu9f60dee2011-09-07 01:19:57 +00006952 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00006953 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00006954 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006955 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006956 << (Opc == BO_LAnd ? "&&" : "||");
6957 // Suggest replacing the logical operator with the bitwise version
6958 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6959 << (Opc == BO_LAnd ? "&" : "|")
6960 << FixItHint::CreateReplacement(SourceRange(
6961 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6962 getLangOptions())),
6963 Opc == BO_LAnd ? "&" : "|");
6964 if (Opc == BO_LAnd)
6965 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6966 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6967 << FixItHint::CreateRemoval(
6968 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006969 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006970 0, getSourceManager(),
6971 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006972 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006973 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006974 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006975
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006976 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006977 LHS = UsualUnaryConversions(LHS.take());
6978 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006979 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006980
Richard Trieu9f60dee2011-09-07 01:19:57 +00006981 RHS = UsualUnaryConversions(RHS.take());
6982 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006983 return QualType();
6984
Richard Trieu9f60dee2011-09-07 01:19:57 +00006985 if (!LHS.get()->getType()->isScalarType() ||
6986 !RHS.get()->getType()->isScalarType())
6987 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006988
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006989 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006990 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006991
John McCall75f7c0f2010-06-04 00:29:51 +00006992 // The following is safe because we only use this method for
6993 // non-overloadable operands.
6994
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006995 // C++ [expr.log.and]p1
6996 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006997 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006998 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6999 if (LHSRes.isInvalid())
7000 return InvalidOperands(Loc, LHS, RHS);
7001 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007002
Richard Trieu9f60dee2011-09-07 01:19:57 +00007003 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7004 if (RHSRes.isInvalid())
7005 return InvalidOperands(Loc, LHS, RHS);
7006 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007007
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007008 // C++ [expr.log.and]p2
7009 // C++ [expr.log.or]p2
7010 // The result is a bool.
7011 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007012}
7013
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007014/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7015/// is a read-only property; return true if so. A readonly property expression
7016/// depends on various declarations and thus must be treated specially.
7017///
Mike Stump1eb44332009-09-09 15:08:12 +00007018static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007019 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7020 if (!PropExpr) return false;
7021 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007022
John McCall3c3b7f92011-10-25 17:37:35 +00007023 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7024 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007025 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007026 PropExpr->getBase()->getType();
7027
John McCall3c3b7f92011-10-25 17:37:35 +00007028 if (const ObjCObjectPointerType *OPT =
7029 BaseType->getAsObjCInterfacePointerType())
7030 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7031 if (S.isPropertyReadonly(PDecl, IFace))
7032 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007033 return false;
7034}
7035
Fariborz Jahanian14086762011-03-28 23:47:18 +00007036static bool IsConstProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007037 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7038 if (!PropExpr) return false;
7039 if (PropExpr->isImplicitProperty()) return false;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007040
John McCall3c3b7f92011-10-25 17:37:35 +00007041 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7042 QualType T = PDecl->getType().getNonReferenceType();
7043 return T.isConstQualified();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007044}
7045
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007046static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007047 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7048 if (!ME) return false;
7049 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7050 ObjCMessageExpr *Base =
7051 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7052 if (!Base) return false;
7053 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007054}
7055
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007056/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7057/// emit an error and return true. If so, return false.
7058static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007059 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007060 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007061 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007062 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7063 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007064 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7065 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007066 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7067 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007068 if (IsLV == Expr::MLV_Valid)
7069 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007070
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007071 unsigned Diag = 0;
7072 bool NeedType = false;
7073 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007074 case Expr::MLV_ConstQualified:
7075 Diag = diag::err_typecheck_assign_const;
7076
John McCall7acddac2011-06-17 06:42:21 +00007077 // In ARC, use some specialized diagnostics for occasions where we
7078 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00007079 if (S.getLangOptions().ObjCAutoRefCount) {
7080 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7081 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7082 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7083
John McCall7acddac2011-06-17 06:42:21 +00007084 // Use the normal diagnostic if it's pseudo-__strong but the
7085 // user actually wrote 'const'.
7086 if (var->isARCPseudoStrong() &&
7087 (!var->getTypeSourceInfo() ||
7088 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7089 // There are two pseudo-strong cases:
7090 // - self
John McCallf85e1932011-06-15 23:02:42 +00007091 ObjCMethodDecl *method = S.getCurMethodDecl();
7092 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007093 Diag = method->isClassMethod()
7094 ? diag::err_typecheck_arc_assign_self_class_method
7095 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007096
7097 // - fast enumeration variables
7098 else
John McCallf85e1932011-06-15 23:02:42 +00007099 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007100
John McCallf85e1932011-06-15 23:02:42 +00007101 SourceRange Assign;
7102 if (Loc != OrigLoc)
7103 Assign = SourceRange(OrigLoc, OrigLoc);
7104 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7105 // We need to preserve the AST regardless, so migration tool
7106 // can do its job.
7107 return false;
7108 }
7109 }
7110 }
7111
7112 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007113 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007114 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7115 NeedType = true;
7116 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007117 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007118 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7119 NeedType = true;
7120 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007121 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007122 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7123 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007124 case Expr::MLV_Valid:
7125 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007126 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007127 case Expr::MLV_MemberFunction:
7128 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007129 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7130 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007131 case Expr::MLV_IncompleteType:
7132 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007133 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007134 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007135 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007136 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007137 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7138 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007139 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007140 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7141 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007142 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007143 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007144 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007145 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007146 case Expr::MLV_InvalidMessageExpression:
7147 Diag = diag::error_readonly_message_assignment;
7148 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007149 case Expr::MLV_SubObjCPropertySetting:
7150 Diag = diag::error_no_subobject_property_setting;
7151 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007152 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007153
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007154 SourceRange Assign;
7155 if (Loc != OrigLoc)
7156 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007157 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007158 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007159 else
Mike Stump1eb44332009-09-09 15:08:12 +00007160 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007161 return true;
7162}
7163
7164
7165
7166// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007167QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007168 SourceLocation Loc,
7169 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007170 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7171
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007172 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007173 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007174 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007175
Richard Trieu268942b2011-09-07 01:33:52 +00007176 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007177 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7178 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007179 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007180 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007181 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007182 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007183 if (RHS.isInvalid())
7184 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007185 // Special case of NSObject attributes on c-style pointer types.
7186 if (ConvTy == IncompatiblePointer &&
7187 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007188 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007189 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007190 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007191 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007192
John McCallf89e55a2010-11-18 06:31:45 +00007193 if (ConvTy == Compatible &&
7194 getLangOptions().ObjCNonFragileABI &&
7195 LHSType->isObjCObjectType())
7196 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7197 << LHSType;
7198
Chris Lattner2c156472008-08-21 18:04:13 +00007199 // If the RHS is a unary plus or minus, check to see if they = and + are
7200 // right next to each other. If so, the user may have typo'd "x =+ 4"
7201 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007202 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7204 RHSCheck = ICE->getSubExpr();
7205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007206 if ((UO->getOpcode() == UO_Plus ||
7207 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007208 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007209 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007210 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007211 // And there is a space or other character before the subexpr of the
7212 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007213 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007214 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007215 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007216 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007217 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007218 }
Chris Lattner2c156472008-08-21 18:04:13 +00007219 }
John McCallf85e1932011-06-15 23:02:42 +00007220
7221 if (ConvTy == Compatible) {
7222 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007223 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007224 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007225 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007226 }
Chris Lattner2c156472008-08-21 18:04:13 +00007227 } else {
7228 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007229 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007230 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007231
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007232 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007233 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007234 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007235
Richard Trieu268942b2011-09-07 01:33:52 +00007236 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007237
Reid Spencer5f016e22007-07-11 17:01:13 +00007238 // C99 6.5.16p3: The type of an assignment expression is the type of the
7239 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007240 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007241 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7242 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007243 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007244 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007245 return (getLangOptions().CPlusPlus
7246 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007247}
7248
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007249// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007250static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007251 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007252 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007253
John McCallfb8721c2011-04-10 19:13:55 +00007254 LHS = S.CheckPlaceholderExpr(LHS.take());
7255 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007256 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007257 return QualType();
7258
John McCallcf2e5062010-10-12 07:14:40 +00007259 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7260 // operands, but not unary promotions.
7261 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007262
John McCallf6a16482010-12-04 03:47:34 +00007263 // So we treat the LHS as a ignored value, and in C++ we allow the
7264 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007265 LHS = S.IgnoredValueConversions(LHS.take());
7266 if (LHS.isInvalid())
7267 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007268
7269 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007270 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7271 if (RHS.isInvalid())
7272 return QualType();
7273 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007274 S.RequireCompleteType(Loc, RHS.get()->getType(),
7275 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007276 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007277
John Wiegley429bb272011-04-08 18:41:53 +00007278 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007279}
7280
Steve Naroff49b45262007-07-13 16:58:59 +00007281/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7282/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007283static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7284 ExprValueKind &VK,
7285 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007286 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007287 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007288 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007289
Chris Lattner3528d352008-11-21 07:05:48 +00007290 QualType ResType = Op->getType();
7291 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007292
John McCall09431682010-11-18 19:01:18 +00007293 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007294 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007295 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007296 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007297 return QualType();
7298 }
7299 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007300 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007301 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007302 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007303 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007304 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007305 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007306 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007307
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007308 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007309 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007310 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007311 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007312 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007313 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007314 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007315 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007316 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007317 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007318 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007319 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007320 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7321 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007322 } else {
John McCall09431682010-11-18 19:01:18 +00007323 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007324 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007325 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007326 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007327 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007328 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007329 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007330 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007331 // In C++, a prefix increment is the same type as the operand. Otherwise
7332 // (in C or with postfix), the increment is the unqualified type of the
7333 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007334 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007335 VK = VK_LValue;
7336 return ResType;
7337 } else {
7338 VK = VK_RValue;
7339 return ResType.getUnqualifiedType();
7340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007341}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007342
7343
Anders Carlsson369dee42008-02-01 07:15:58 +00007344/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007345/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007346/// where the declaration is needed for type checking. We only need to
7347/// handle cases when the expression references a function designator
7348/// or is an lvalue. Here are some examples:
7349/// - &(x) => x
7350/// - &*****f => f for f a function designator.
7351/// - &s.xx => s
7352/// - &s.zz[1].yy -> s, if zz is an array
7353/// - *(x + 1) -> x, if x is an array
7354/// - &"123"[2] -> 0
7355/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007356static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007357 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007358 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007359 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007360 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007361 // If this is an arrow operator, the address is an offset from
7362 // the base's value, so the object the base refers to is
7363 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007364 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007365 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007366 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007367 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007368 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007369 // FIXME: This code shouldn't be necessary! We should catch the implicit
7370 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007371 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7372 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7373 if (ICE->getSubExpr()->getType()->isArrayType())
7374 return getPrimaryDecl(ICE->getSubExpr());
7375 }
7376 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007377 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007378 case Stmt::UnaryOperatorClass: {
7379 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007380
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007381 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007382 case UO_Real:
7383 case UO_Imag:
7384 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007385 return getPrimaryDecl(UO->getSubExpr());
7386 default:
7387 return 0;
7388 }
7389 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007390 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007391 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007392 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007393 // If the result of an implicit cast is an l-value, we care about
7394 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007395 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007396 default:
7397 return 0;
7398 }
7399}
7400
Richard Trieu5520f232011-09-07 21:46:33 +00007401namespace {
7402 enum {
7403 AO_Bit_Field = 0,
7404 AO_Vector_Element = 1,
7405 AO_Property_Expansion = 2,
7406 AO_Register_Variable = 3,
7407 AO_No_Error = 4
7408 };
7409}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007410/// \brief Diagnose invalid operand for address of operations.
7411///
7412/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007413static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7414 Expr *E, unsigned Type) {
7415 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7416}
7417
Reid Spencer5f016e22007-07-11 17:01:13 +00007418/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007419/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007420/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007421/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007422/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007423/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007424/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007425static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007426 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007427 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7428 if (PTy->getKind() == BuiltinType::Overload) {
7429 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7430 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7431 << OrigOp.get()->getSourceRange();
7432 return QualType();
7433 }
7434
7435 return S.Context.OverloadTy;
7436 }
7437
7438 if (PTy->getKind() == BuiltinType::UnknownAny)
7439 return S.Context.UnknownAnyTy;
7440
7441 if (PTy->getKind() == BuiltinType::BoundMember) {
7442 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7443 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007444 return QualType();
7445 }
John McCall3c3b7f92011-10-25 17:37:35 +00007446
7447 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7448 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007449 }
John McCall9c72c602010-08-27 09:08:28 +00007450
John McCall3c3b7f92011-10-25 17:37:35 +00007451 if (OrigOp.get()->isTypeDependent())
7452 return S.Context.DependentTy;
7453
7454 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007455
John McCall9c72c602010-08-27 09:08:28 +00007456 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007457 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007458
John McCall09431682010-11-18 19:01:18 +00007459 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007460 // Implement C99-only parts of addressof rules.
7461 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007462 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007463 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7464 // (assuming the deref expression is valid).
7465 return uOp->getSubExpr()->getType();
7466 }
7467 // Technically, there should be a check for array subscript
7468 // expressions here, but the result of one is always an lvalue anyway.
7469 }
John McCall5808ce42011-02-03 08:15:49 +00007470 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007471 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007472 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007473
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007474 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007475 bool sfinae = S.isSFINAEContext();
7476 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7477 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007478 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007479 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007480 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007481 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007482 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007483 } else if (lval == Expr::LV_MemberFunction) {
7484 // If it's an instance method, make a member pointer.
7485 // The expression must have exactly the form &A::foo.
7486
7487 // If the underlying expression isn't a decl ref, give up.
7488 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007489 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007490 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007491 return QualType();
7492 }
7493 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7494 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7495
7496 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007497 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007498 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007499 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007500
7501 // The method was named without a qualifier.
7502 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007503 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007504 << op->getSourceRange();
7505 }
7506
John McCall09431682010-11-18 19:01:18 +00007507 return S.Context.getMemberPointerType(op->getType(),
7508 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007509 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007510 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007511 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007512 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007513 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007514 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007515 AddressOfError = AO_Property_Expansion;
7516 } else {
7517 // FIXME: emit more specific diag...
7518 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7519 << op->getSourceRange();
7520 return QualType();
7521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007522 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007523 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007524 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007525 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007526 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007527 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007528 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007529 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007530 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007531 // with the register storage-class specifier.
7532 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007533 // in C++ it is not error to take address of a register
7534 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007535 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007536 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007537 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007538 }
John McCallba135432009-11-21 08:51:07 +00007539 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007540 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007541 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007542 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007543 // Could be a pointer to member, though, if there is an explicit
7544 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007545 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007546 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007547 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007548 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007549 S.Diag(OpLoc,
7550 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007551 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007552 return QualType();
7553 }
Mike Stump1eb44332009-09-09 15:08:12 +00007554
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007555 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7556 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007557 return S.Context.getMemberPointerType(op->getType(),
7558 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007559 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007560 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007561 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007562 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007563 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007564
Richard Trieu5520f232011-09-07 21:46:33 +00007565 if (AddressOfError != AO_No_Error) {
7566 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7567 return QualType();
7568 }
7569
Eli Friedman441cf102009-05-16 23:27:50 +00007570 if (lval == Expr::LV_IncompleteVoidType) {
7571 // Taking the address of a void variable is technically illegal, but we
7572 // allow it in cases which are otherwise valid.
7573 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007574 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007575 }
7576
Reid Spencer5f016e22007-07-11 17:01:13 +00007577 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007578 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007579 return S.Context.getObjCObjectPointerType(op->getType());
7580 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007581}
7582
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007583/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007584static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7585 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007586 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007587 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007588
John Wiegley429bb272011-04-08 18:41:53 +00007589 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7590 if (ConvResult.isInvalid())
7591 return QualType();
7592 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007593 QualType OpTy = Op->getType();
7594 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007595
7596 if (isa<CXXReinterpretCastExpr>(Op)) {
7597 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7598 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7599 Op->getSourceRange());
7600 }
7601
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007602 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7603 // is an incomplete type or void. It would be possible to warn about
7604 // dereferencing a void pointer, but it's completely well-defined, and such a
7605 // warning is unlikely to catch any mistakes.
7606 if (const PointerType *PT = OpTy->getAs<PointerType>())
7607 Result = PT->getPointeeType();
7608 else if (const ObjCObjectPointerType *OPT =
7609 OpTy->getAs<ObjCObjectPointerType>())
7610 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007611 else {
John McCallfb8721c2011-04-10 19:13:55 +00007612 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007613 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007614 if (PR.take() != Op)
7615 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007616 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007617
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007618 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007619 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007620 << OpTy << Op->getSourceRange();
7621 return QualType();
7622 }
John McCall09431682010-11-18 19:01:18 +00007623
7624 // Dereferences are usually l-values...
7625 VK = VK_LValue;
7626
7627 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007628 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007629 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007630
7631 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007632}
7633
John McCall2de56d12010-08-25 11:45:40 +00007634static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007635 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007636 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007637 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007638 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007639 case tok::periodstar: Opc = BO_PtrMemD; break;
7640 case tok::arrowstar: Opc = BO_PtrMemI; break;
7641 case tok::star: Opc = BO_Mul; break;
7642 case tok::slash: Opc = BO_Div; break;
7643 case tok::percent: Opc = BO_Rem; break;
7644 case tok::plus: Opc = BO_Add; break;
7645 case tok::minus: Opc = BO_Sub; break;
7646 case tok::lessless: Opc = BO_Shl; break;
7647 case tok::greatergreater: Opc = BO_Shr; break;
7648 case tok::lessequal: Opc = BO_LE; break;
7649 case tok::less: Opc = BO_LT; break;
7650 case tok::greaterequal: Opc = BO_GE; break;
7651 case tok::greater: Opc = BO_GT; break;
7652 case tok::exclaimequal: Opc = BO_NE; break;
7653 case tok::equalequal: Opc = BO_EQ; break;
7654 case tok::amp: Opc = BO_And; break;
7655 case tok::caret: Opc = BO_Xor; break;
7656 case tok::pipe: Opc = BO_Or; break;
7657 case tok::ampamp: Opc = BO_LAnd; break;
7658 case tok::pipepipe: Opc = BO_LOr; break;
7659 case tok::equal: Opc = BO_Assign; break;
7660 case tok::starequal: Opc = BO_MulAssign; break;
7661 case tok::slashequal: Opc = BO_DivAssign; break;
7662 case tok::percentequal: Opc = BO_RemAssign; break;
7663 case tok::plusequal: Opc = BO_AddAssign; break;
7664 case tok::minusequal: Opc = BO_SubAssign; break;
7665 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7666 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7667 case tok::ampequal: Opc = BO_AndAssign; break;
7668 case tok::caretequal: Opc = BO_XorAssign; break;
7669 case tok::pipeequal: Opc = BO_OrAssign; break;
7670 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007671 }
7672 return Opc;
7673}
7674
John McCall2de56d12010-08-25 11:45:40 +00007675static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007676 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007677 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007678 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007679 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007680 case tok::plusplus: Opc = UO_PreInc; break;
7681 case tok::minusminus: Opc = UO_PreDec; break;
7682 case tok::amp: Opc = UO_AddrOf; break;
7683 case tok::star: Opc = UO_Deref; break;
7684 case tok::plus: Opc = UO_Plus; break;
7685 case tok::minus: Opc = UO_Minus; break;
7686 case tok::tilde: Opc = UO_Not; break;
7687 case tok::exclaim: Opc = UO_LNot; break;
7688 case tok::kw___real: Opc = UO_Real; break;
7689 case tok::kw___imag: Opc = UO_Imag; break;
7690 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007691 }
7692 return Opc;
7693}
7694
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007695/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7696/// This warning is only emitted for builtin assignment operations. It is also
7697/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007698static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007699 SourceLocation OpLoc) {
7700 if (!S.ActiveTemplateInstantiations.empty())
7701 return;
7702 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7703 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007704 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7705 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7706 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7707 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7708 if (!LHSDeclRef || !RHSDeclRef ||
7709 LHSDeclRef->getLocation().isMacroID() ||
7710 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007711 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007712 const ValueDecl *LHSDecl =
7713 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7714 const ValueDecl *RHSDecl =
7715 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7716 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007717 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007718 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007719 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007720 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007721 if (RefTy->getPointeeType().isVolatileQualified())
7722 return;
7723
7724 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007725 << LHSDeclRef->getType()
7726 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007727}
7728
Douglas Gregoreaebc752008-11-06 23:29:22 +00007729/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7730/// operator @p Opc at location @c TokLoc. This routine only supports
7731/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007732ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007733 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007734 Expr *LHSExpr, Expr *RHSExpr) {
7735 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007736 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007737 // The following two variables are used for compound assignment operators
7738 QualType CompLHSTy; // Type of LHS after promotions for computation
7739 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007740 ExprValueKind VK = VK_RValue;
7741 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007742
7743 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007744 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007745 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007746 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007747 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7748 VK = LHS.get()->getValueKind();
7749 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007750 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007751 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007752 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007753 break;
John McCall2de56d12010-08-25 11:45:40 +00007754 case BO_PtrMemD:
7755 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007756 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007757 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007758 break;
John McCall2de56d12010-08-25 11:45:40 +00007759 case BO_Mul:
7760 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007761 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007762 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007763 break;
John McCall2de56d12010-08-25 11:45:40 +00007764 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007765 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007766 break;
John McCall2de56d12010-08-25 11:45:40 +00007767 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007768 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007769 break;
John McCall2de56d12010-08-25 11:45:40 +00007770 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007771 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007772 break;
John McCall2de56d12010-08-25 11:45:40 +00007773 case BO_Shl:
7774 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007775 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007776 break;
John McCall2de56d12010-08-25 11:45:40 +00007777 case BO_LE:
7778 case BO_LT:
7779 case BO_GE:
7780 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007781 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007782 break;
John McCall2de56d12010-08-25 11:45:40 +00007783 case BO_EQ:
7784 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007785 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007786 break;
John McCall2de56d12010-08-25 11:45:40 +00007787 case BO_And:
7788 case BO_Xor:
7789 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007790 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007791 break;
John McCall2de56d12010-08-25 11:45:40 +00007792 case BO_LAnd:
7793 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007794 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007795 break;
John McCall2de56d12010-08-25 11:45:40 +00007796 case BO_MulAssign:
7797 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007798 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007799 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007800 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007801 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7802 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007803 break;
John McCall2de56d12010-08-25 11:45:40 +00007804 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007805 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007806 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007807 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7808 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007809 break;
John McCall2de56d12010-08-25 11:45:40 +00007810 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007811 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7812 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7813 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007814 break;
John McCall2de56d12010-08-25 11:45:40 +00007815 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007816 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7817 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7818 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007819 break;
John McCall2de56d12010-08-25 11:45:40 +00007820 case BO_ShlAssign:
7821 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007822 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007823 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007824 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7825 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007826 break;
John McCall2de56d12010-08-25 11:45:40 +00007827 case BO_AndAssign:
7828 case BO_XorAssign:
7829 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007830 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007831 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007832 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7833 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007834 break;
John McCall2de56d12010-08-25 11:45:40 +00007835 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007836 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7837 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7838 VK = RHS.get()->getValueKind();
7839 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007840 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007841 break;
7842 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007843 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007844 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007845
7846 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007847 CheckArrayAccess(LHS.get());
7848 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007849
Eli Friedmanab3a8522009-03-28 01:22:36 +00007850 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007851 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007852 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007853 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007854 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007855 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007856 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007857 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007858 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007859 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007860 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007861}
7862
Sebastian Redlaee3c932009-10-27 12:10:02 +00007863/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7864/// operators are mixed in a way that suggests that the programmer forgot that
7865/// comparison operators have higher precedence. The most typical example of
7866/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007867static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007868 SourceLocation OpLoc, Expr *LHSExpr,
7869 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007870 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007871 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7872 RHSopc = static_cast<BinOp::Opcode>(-1);
7873 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7874 LHSopc = BO->getOpcode();
7875 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7876 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007877
7878 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007879 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007880 return;
7881
7882 // Bitwise operations are sometimes used as eager logical ops.
7883 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007884 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7885 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007886 return;
7887
Richard Trieu78ea78b2011-09-07 01:49:20 +00007888 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7889 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007890 if (!isLeftComp && !isRightComp) return;
7891
Richard Trieu78ea78b2011-09-07 01:49:20 +00007892 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7893 OpLoc)
7894 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7895 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7896 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007897 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00007898 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7899 RHSExpr->getLocEnd())
7900 : SourceRange(LHSExpr->getLocStart(),
7901 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00007902
7903 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7904 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7905 SuggestParentheses(Self, OpLoc,
7906 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007907 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00007908 SuggestParentheses(Self, OpLoc,
7909 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7910 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007911}
7912
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007913/// \brief It accepts a '&' expr that is inside a '|' one.
7914/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7915/// in parentheses.
7916static void
7917EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7918 BinaryOperator *Bop) {
7919 assert(Bop->getOpcode() == BO_And);
7920 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7921 << Bop->getSourceRange() << OpLoc;
7922 SuggestParentheses(Self, Bop->getOperatorLoc(),
7923 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7924 Bop->getSourceRange());
7925}
7926
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007927/// \brief It accepts a '&&' expr that is inside a '||' one.
7928/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7929/// in parentheses.
7930static void
7931EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007932 BinaryOperator *Bop) {
7933 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007934 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7935 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007936 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007937 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007938 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007939}
7940
7941/// \brief Returns true if the given expression can be evaluated as a constant
7942/// 'true'.
7943static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7944 bool Res;
7945 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7946}
7947
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007948/// \brief Returns true if the given expression can be evaluated as a constant
7949/// 'false'.
7950static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7951 bool Res;
7952 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7953}
7954
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007955/// \brief Look for '&&' in the left hand of a '||' expr.
7956static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007957 Expr *LHSExpr, Expr *RHSExpr) {
7958 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007959 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007960 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007961 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007962 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007963 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7964 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7965 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7966 } else if (Bop->getOpcode() == BO_LOr) {
7967 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7968 // If it's "a || b && 1 || c" we didn't warn earlier for
7969 // "a || b && 1", but warn now.
7970 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7971 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7972 }
7973 }
7974 }
7975}
7976
7977/// \brief Look for '&&' in the right hand of a '||' expr.
7978static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007979 Expr *LHSExpr, Expr *RHSExpr) {
7980 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007981 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007982 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007983 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007984 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007985 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7986 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7987 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007988 }
7989 }
7990}
7991
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007992/// \brief Look for '&' in the left or right hand of a '|' expr.
7993static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7994 Expr *OrArg) {
7995 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7996 if (Bop->getOpcode() == BO_And)
7997 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7998 }
7999}
8000
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008001/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008002/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008003static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008004 SourceLocation OpLoc, Expr *LHSExpr,
8005 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008006 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008007 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008008 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008009
8010 // Diagnose "arg1 & arg2 | arg3"
8011 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008012 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8013 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008014 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008015
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008016 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8017 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008018 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008019 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8020 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008021 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008022}
8023
Reid Spencer5f016e22007-07-11 17:01:13 +00008024// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008025ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008026 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008027 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008028 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008029 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8030 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008031
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008032 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008033 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008034
Richard Trieubefece12011-09-07 02:02:10 +00008035 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008036}
8037
John McCall3c3b7f92011-10-25 17:37:35 +00008038/// Build an overloaded binary operator expression in the given scope.
8039static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8040 BinaryOperatorKind Opc,
8041 Expr *LHS, Expr *RHS) {
8042 // Find all of the overloaded operators visible from this
8043 // point. We perform both an operator-name lookup from the local
8044 // scope and an argument-dependent lookup based on the types of
8045 // the arguments.
8046 UnresolvedSet<16> Functions;
8047 OverloadedOperatorKind OverOp
8048 = BinaryOperator::getOverloadedOperator(Opc);
8049 if (Sc && OverOp != OO_None)
8050 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8051 RHS->getType(), Functions);
8052
8053 // Build the (potentially-overloaded, potentially-dependent)
8054 // binary operation.
8055 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8056}
8057
John McCall60d7b3a2010-08-24 06:29:42 +00008058ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008059 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008060 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008061 // We want to end up calling one of checkPseudoObjectAssignment
8062 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8063 // both expressions are overloadable or either is type-dependent),
8064 // or CreateBuiltinBinOp (in any other case). We also want to get
8065 // any placeholder types out of the way.
8066
John McCall3c3b7f92011-10-25 17:37:35 +00008067 // Handle pseudo-objects in the LHS.
8068 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8069 // Assignments with a pseudo-object l-value need special analysis.
8070 if (pty->getKind() == BuiltinType::PseudoObject &&
8071 BinaryOperator::isAssignmentOp(Opc))
8072 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8073
8074 // Don't resolve overloads if the other type is overloadable.
8075 if (pty->getKind() == BuiltinType::Overload) {
8076 // We can't actually test that if we still have a placeholder,
8077 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008078 // code below are valid when the LHS is an overload set. Note
8079 // that an overload set can be dependently-typed, but it never
8080 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008081 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8082 if (resolvedRHS.isInvalid()) return ExprError();
8083 RHSExpr = resolvedRHS.take();
8084
John McCallac516502011-10-28 01:04:34 +00008085 if (RHSExpr->isTypeDependent() ||
8086 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008087 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8088 }
8089
8090 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8091 if (LHS.isInvalid()) return ExprError();
8092 LHSExpr = LHS.take();
8093 }
8094
8095 // Handle pseudo-objects in the RHS.
8096 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8097 // An overload in the RHS can potentially be resolved by the type
8098 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008099 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8100 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8101 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8102
John McCall3c3b7f92011-10-25 17:37:35 +00008103 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008104 }
John McCall3c3b7f92011-10-25 17:37:35 +00008105
8106 // Don't resolve overloads if the other type is overloadable.
8107 if (pty->getKind() == BuiltinType::Overload &&
8108 LHSExpr->getType()->isOverloadableType())
8109 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8110
8111 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8112 if (!resolvedRHS.isUsable()) return ExprError();
8113 RHSExpr = resolvedRHS.take();
8114 }
8115
John McCall01b2e4e2010-12-06 05:26:58 +00008116 if (getLangOptions().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008117 // If either expression is type-dependent, always build an
8118 // overloaded op.
8119 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8120 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008121
John McCallac516502011-10-28 01:04:34 +00008122 // Otherwise, build an overloaded op if either expression has an
8123 // overloadable type.
8124 if (LHSExpr->getType()->isOverloadableType() ||
8125 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008126 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008127 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008128
Douglas Gregoreaebc752008-11-06 23:29:22 +00008129 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008130 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008131}
8132
John McCall60d7b3a2010-08-24 06:29:42 +00008133ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008134 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008135 Expr *InputExpr) {
8136 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008137 ExprValueKind VK = VK_RValue;
8138 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008139 QualType resultType;
8140 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008141 case UO_PreInc:
8142 case UO_PreDec:
8143 case UO_PostInc:
8144 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008145 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008146 Opc == UO_PreInc ||
8147 Opc == UO_PostInc,
8148 Opc == UO_PreInc ||
8149 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008150 break;
John McCall2de56d12010-08-25 11:45:40 +00008151 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008152 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008153 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008154 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008155 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8156 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008157 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008158 }
John McCall2de56d12010-08-25 11:45:40 +00008159 case UO_Plus:
8160 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008161 Input = UsualUnaryConversions(Input.take());
8162 if (Input.isInvalid()) return ExprError();
8163 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008164 if (resultType->isDependentType())
8165 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008166 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8167 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008168 break;
8169 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8170 resultType->isEnumeralType())
8171 break;
8172 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008173 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008174 resultType->isPointerType())
8175 break;
8176
Sebastian Redl0eb23302009-01-19 00:08:26 +00008177 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008178 << resultType << Input.get()->getSourceRange());
8179
John McCall2de56d12010-08-25 11:45:40 +00008180 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008181 Input = UsualUnaryConversions(Input.take());
8182 if (Input.isInvalid()) return ExprError();
8183 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008184 if (resultType->isDependentType())
8185 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008186 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8187 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8188 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008189 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008190 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008191 else if (resultType->hasIntegerRepresentation())
8192 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008193 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008194 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008195 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008196 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008197 break;
John Wiegley429bb272011-04-08 18:41:53 +00008198
John McCall2de56d12010-08-25 11:45:40 +00008199 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008200 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008201 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8202 if (Input.isInvalid()) return ExprError();
8203 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008204
8205 // Though we still have to promote half FP to float...
8206 if (resultType->isHalfType()) {
8207 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8208 resultType = Context.FloatTy;
8209 }
8210
Sebastian Redl28507842009-02-26 14:39:58 +00008211 if (resultType->isDependentType())
8212 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008213 if (resultType->isScalarType()) {
8214 // C99 6.5.3.3p1: ok, fallthrough;
8215 if (Context.getLangOptions().CPlusPlus) {
8216 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8217 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008218 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8219 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008220 }
John McCall2cd11fe2010-10-12 02:09:17 +00008221 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008222 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008223 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008224 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008225
Reid Spencer5f016e22007-07-11 17:01:13 +00008226 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008227 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008228 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008229 break;
John McCall2de56d12010-08-25 11:45:40 +00008230 case UO_Real:
8231 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008232 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008233 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008234 if (Input.isInvalid()) return ExprError();
8235 if (Input.get()->getValueKind() != VK_RValue &&
8236 Input.get()->getObjectKind() == OK_Ordinary)
8237 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008238 break;
John McCall2de56d12010-08-25 11:45:40 +00008239 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008240 resultType = Input.get()->getType();
8241 VK = Input.get()->getValueKind();
8242 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008243 break;
8244 }
John Wiegley429bb272011-04-08 18:41:53 +00008245 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008246 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008247
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008248 // Check for array bounds violations in the operand of the UnaryOperator,
8249 // except for the '*' and '&' operators that have to be handled specially
8250 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8251 // that are explicitly defined as valid by the standard).
8252 if (Opc != UO_AddrOf && Opc != UO_Deref)
8253 CheckArrayAccess(Input.get());
8254
John Wiegley429bb272011-04-08 18:41:53 +00008255 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008256 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008257}
8258
John McCall60d7b3a2010-08-24 06:29:42 +00008259ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008260 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008261 // First things first: handle placeholders so that the
8262 // overloaded-operator check considers the right type.
8263 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8264 // Increment and decrement of pseudo-object references.
8265 if (pty->getKind() == BuiltinType::PseudoObject &&
8266 UnaryOperator::isIncrementDecrementOp(Opc))
8267 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8268
8269 // extension is always a builtin operator.
8270 if (Opc == UO_Extension)
8271 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8272
8273 // & gets special logic for several kinds of placeholder.
8274 // The builtin code knows what to do.
8275 if (Opc == UO_AddrOf &&
8276 (pty->getKind() == BuiltinType::Overload ||
8277 pty->getKind() == BuiltinType::UnknownAny ||
8278 pty->getKind() == BuiltinType::BoundMember))
8279 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8280
8281 // Anything else needs to be handled now.
8282 ExprResult Result = CheckPlaceholderExpr(Input);
8283 if (Result.isInvalid()) return ExprError();
8284 Input = Result.take();
8285 }
8286
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008287 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008288 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008289 // Find all of the overloaded operators visible from this
8290 // point. We perform both an operator-name lookup from the local
8291 // scope and an argument-dependent lookup based on the types of
8292 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008293 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008294 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008295 if (S && OverOp != OO_None)
8296 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8297 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008298
John McCall9ae2f072010-08-23 23:25:46 +00008299 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008300 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008301
John McCall9ae2f072010-08-23 23:25:46 +00008302 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008303}
8304
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008305// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008306ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008307 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008308 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008309}
8310
Steve Naroff1b273c42007-09-16 14:56:35 +00008311/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008312ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008313 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008314 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008315 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008316 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008317 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008318}
8319
John McCallf85e1932011-06-15 23:02:42 +00008320/// Given the last statement in a statement-expression, check whether
8321/// the result is a producing expression (like a call to an
8322/// ns_returns_retained function) and, if so, rebuild it to hoist the
8323/// release out of the full-expression. Otherwise, return null.
8324/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008325static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008326 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008327 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008328 if (!cleanups) return 0;
8329
8330 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008331 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008332 return 0;
8333
8334 // Splice out the cast. This shouldn't modify any interesting
8335 // features of the statement.
8336 Expr *producer = cast->getSubExpr();
8337 assert(producer->getType() == cast->getType());
8338 assert(producer->getValueKind() == cast->getValueKind());
8339 cleanups->setSubExpr(producer);
8340 return cleanups;
8341}
8342
John McCall60d7b3a2010-08-24 06:29:42 +00008343ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008344Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008345 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008346 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8347 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8348
Douglas Gregordd8f5692010-03-10 04:54:39 +00008349 bool isFileScope
8350 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008351 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008352 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008353
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008354 // FIXME: there are a variety of strange constraints to enforce here, for
8355 // example, it is not possible to goto into a stmt expression apparently.
8356 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008357
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008358 // If there are sub stmts in the compound stmt, take the type of the last one
8359 // as the type of the stmtexpr.
8360 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008361 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008362 if (!Compound->body_empty()) {
8363 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008364 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008365 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008366 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8367 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008368 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008369 }
John McCallf85e1932011-06-15 23:02:42 +00008370
John Wiegley429bb272011-04-08 18:41:53 +00008371 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008372 // Do function/array conversion on the last expression, but not
8373 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008374 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8375 if (LastExpr.isInvalid())
8376 return ExprError();
8377 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008378
John Wiegley429bb272011-04-08 18:41:53 +00008379 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008380 // In ARC, if the final expression ends in a consume, splice
8381 // the consume out and bind it later. In the alternate case
8382 // (when dealing with a retainable type), the result
8383 // initialization will create a produce. In both cases the
8384 // result will be +1, and we'll need to balance that out with
8385 // a bind.
8386 if (Expr *rebuiltLastStmt
8387 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8388 LastExpr = rebuiltLastStmt;
8389 } else {
8390 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008391 InitializedEntity::InitializeResult(LPLoc,
8392 Ty,
8393 false),
8394 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008395 LastExpr);
8396 }
8397
John Wiegley429bb272011-04-08 18:41:53 +00008398 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008399 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008400 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008401 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008402 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008403 else
John Wiegley429bb272011-04-08 18:41:53 +00008404 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008405 StmtExprMayBindToTemp = true;
8406 }
8407 }
8408 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008409 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008410
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008411 // FIXME: Check that expression type is complete/non-abstract; statement
8412 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008413 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8414 if (StmtExprMayBindToTemp)
8415 return MaybeBindToTemporary(ResStmtExpr);
8416 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008417}
Steve Naroffd34e9152007-08-01 22:05:33 +00008418
John McCall60d7b3a2010-08-24 06:29:42 +00008419ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008420 TypeSourceInfo *TInfo,
8421 OffsetOfComponent *CompPtr,
8422 unsigned NumComponents,
8423 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008424 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008425 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008426 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008427
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008428 // We must have at least one component that refers to the type, and the first
8429 // one is known to be a field designator. Verify that the ArgTy represents
8430 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008431 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008432 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8433 << ArgTy << TypeRange);
8434
8435 // Type must be complete per C99 7.17p3 because a declaring a variable
8436 // with an incomplete type would be ill-formed.
8437 if (!Dependent
8438 && RequireCompleteType(BuiltinLoc, ArgTy,
8439 PDiag(diag::err_offsetof_incomplete_type)
8440 << TypeRange))
8441 return ExprError();
8442
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008443 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8444 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008445 // FIXME: This diagnostic isn't actually visible because the location is in
8446 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008447 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008448 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8449 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008450
8451 bool DidWarnAboutNonPOD = false;
8452 QualType CurrentType = ArgTy;
8453 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008454 SmallVector<OffsetOfNode, 4> Comps;
8455 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008456 for (unsigned i = 0; i != NumComponents; ++i) {
8457 const OffsetOfComponent &OC = CompPtr[i];
8458 if (OC.isBrackets) {
8459 // Offset of an array sub-field. TODO: Should we allow vector elements?
8460 if (!CurrentType->isDependentType()) {
8461 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8462 if(!AT)
8463 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8464 << CurrentType);
8465 CurrentType = AT->getElementType();
8466 } else
8467 CurrentType = Context.DependentTy;
8468
Richard Smithea011432011-10-17 23:29:39 +00008469 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8470 if (IdxRval.isInvalid())
8471 return ExprError();
8472 Expr *Idx = IdxRval.take();
8473
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008474 // The expression must be an integral expression.
8475 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008476 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8477 !Idx->getType()->isIntegerType())
8478 return ExprError(Diag(Idx->getLocStart(),
8479 diag::err_typecheck_subscript_not_integer)
8480 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00008481
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008482 // Record this array index.
8483 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00008484 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008485 continue;
8486 }
8487
8488 // Offset of a field.
8489 if (CurrentType->isDependentType()) {
8490 // We have the offset of a field, but we can't look into the dependent
8491 // type. Just record the identifier of the field.
8492 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8493 CurrentType = Context.DependentTy;
8494 continue;
8495 }
8496
8497 // We need to have a complete type to look into.
8498 if (RequireCompleteType(OC.LocStart, CurrentType,
8499 diag::err_offsetof_incomplete_type))
8500 return ExprError();
8501
8502 // Look for the designated field.
8503 const RecordType *RC = CurrentType->getAs<RecordType>();
8504 if (!RC)
8505 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8506 << CurrentType);
8507 RecordDecl *RD = RC->getDecl();
8508
8509 // C++ [lib.support.types]p5:
8510 // The macro offsetof accepts a restricted set of type arguments in this
8511 // International Standard. type shall be a POD structure or a POD union
8512 // (clause 9).
8513 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8514 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008515 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008516 PDiag(diag::warn_offsetof_non_pod_type)
8517 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8518 << CurrentType))
8519 DidWarnAboutNonPOD = true;
8520 }
8521
8522 // Look for the field.
8523 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8524 LookupQualifiedName(R, RD);
8525 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008526 IndirectFieldDecl *IndirectMemberDecl = 0;
8527 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008528 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008529 MemberDecl = IndirectMemberDecl->getAnonField();
8530 }
8531
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008532 if (!MemberDecl)
8533 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8534 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8535 OC.LocEnd));
8536
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008537 // C99 7.17p3:
8538 // (If the specified member is a bit-field, the behavior is undefined.)
8539 //
8540 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008541 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008542 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8543 << MemberDecl->getDeclName()
8544 << SourceRange(BuiltinLoc, RParenLoc);
8545 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8546 return ExprError();
8547 }
Eli Friedman19410a72010-08-05 10:11:36 +00008548
8549 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008550 if (IndirectMemberDecl)
8551 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008552
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008553 // If the member was found in a base class, introduce OffsetOfNodes for
8554 // the base class indirections.
8555 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8556 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008557 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008558 CXXBasePath &Path = Paths.front();
8559 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8560 B != BEnd; ++B)
8561 Comps.push_back(OffsetOfNode(B->Base));
8562 }
Eli Friedman19410a72010-08-05 10:11:36 +00008563
Francois Pichet87c2e122010-11-21 06:08:52 +00008564 if (IndirectMemberDecl) {
8565 for (IndirectFieldDecl::chain_iterator FI =
8566 IndirectMemberDecl->chain_begin(),
8567 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8568 assert(isa<FieldDecl>(*FI));
8569 Comps.push_back(OffsetOfNode(OC.LocStart,
8570 cast<FieldDecl>(*FI), OC.LocEnd));
8571 }
8572 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008573 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008574
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008575 CurrentType = MemberDecl->getType().getNonReferenceType();
8576 }
8577
8578 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8579 TInfo, Comps.data(), Comps.size(),
8580 Exprs.data(), Exprs.size(), RParenLoc));
8581}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008582
John McCall60d7b3a2010-08-24 06:29:42 +00008583ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008584 SourceLocation BuiltinLoc,
8585 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008586 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008587 OffsetOfComponent *CompPtr,
8588 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008589 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008590
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008591 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008592 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008593 if (ArgTy.isNull())
8594 return ExprError();
8595
Eli Friedman5a15dc12010-08-05 10:15:45 +00008596 if (!ArgTInfo)
8597 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8598
8599 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008600 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008601}
8602
8603
John McCall60d7b3a2010-08-24 06:29:42 +00008604ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008605 Expr *CondExpr,
8606 Expr *LHSExpr, Expr *RHSExpr,
8607 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008608 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8609
John McCallf89e55a2010-11-18 06:31:45 +00008610 ExprValueKind VK = VK_RValue;
8611 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008612 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008613 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008614 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008615 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008616 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008617 } else {
8618 // The conditional expression is required to be a constant expression.
8619 llvm::APSInt condEval(32);
8620 SourceLocation ExpLoc;
8621 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008622 return ExprError(Diag(ExpLoc,
8623 diag::err_typecheck_choose_expr_requires_constant)
8624 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008625
Sebastian Redl28507842009-02-26 14:39:58 +00008626 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008627 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8628
8629 resType = ActiveExpr->getType();
8630 ValueDependent = ActiveExpr->isValueDependent();
8631 VK = ActiveExpr->getValueKind();
8632 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008633 }
8634
Sebastian Redlf53597f2009-03-15 17:47:39 +00008635 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008636 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008637 resType->isDependentType(),
8638 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008639}
8640
Steve Naroff4eb206b2008-09-03 18:15:37 +00008641//===----------------------------------------------------------------------===//
8642// Clang Extensions.
8643//===----------------------------------------------------------------------===//
8644
8645/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008646void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008647 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008648 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008649 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008650 if (CurScope)
8651 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008652 else
8653 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00008654
8655 // Enter a new evaluation context to insulate the block from any
8656 // cleanups from the enclosing full-expression.
8657 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00008658}
8659
Mike Stump98eb8a72009-02-04 22:31:32 +00008660void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008661 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008662 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008663 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008664
John McCallbf1a0282010-06-04 23:28:52 +00008665 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008666 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008667
John McCall711c52b2011-01-05 12:14:39 +00008668 // GetTypeForDeclarator always produces a function type for a block
8669 // literal signature. Furthermore, it is always a FunctionProtoType
8670 // unless the function was written with a typedef.
8671 assert(T->isFunctionType() &&
8672 "GetTypeForDeclarator made a non-function block signature");
8673
8674 // Look for an explicit signature in that function type.
8675 FunctionProtoTypeLoc ExplicitSignature;
8676
8677 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8678 if (isa<FunctionProtoTypeLoc>(tmp)) {
8679 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8680
8681 // Check whether that explicit signature was synthesized by
8682 // GetTypeForDeclarator. If so, don't save that as part of the
8683 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008684 if (ExplicitSignature.getLocalRangeBegin() ==
8685 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008686 // This would be much cheaper if we stored TypeLocs instead of
8687 // TypeSourceInfos.
8688 TypeLoc Result = ExplicitSignature.getResultLoc();
8689 unsigned Size = Result.getFullDataSize();
8690 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8691 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8692
8693 ExplicitSignature = FunctionProtoTypeLoc();
8694 }
John McCall82dc0092010-06-04 11:21:44 +00008695 }
Mike Stump1eb44332009-09-09 15:08:12 +00008696
John McCall711c52b2011-01-05 12:14:39 +00008697 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8698 CurBlock->FunctionType = T;
8699
8700 const FunctionType *Fn = T->getAs<FunctionType>();
8701 QualType RetTy = Fn->getResultType();
8702 bool isVariadic =
8703 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8704
John McCallc71a4912010-06-04 19:02:56 +00008705 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008706
John McCall82dc0092010-06-04 11:21:44 +00008707 // Don't allow returning a objc interface by value.
8708 if (RetTy->isObjCObjectType()) {
8709 Diag(ParamInfo.getSourceRange().getBegin(),
8710 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8711 return;
8712 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008713
John McCall82dc0092010-06-04 11:21:44 +00008714 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008715 // return type. TODO: what should we do with declarators like:
8716 // ^ * { ... }
8717 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00008718 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00008719 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00008720 CurBlock->TheDecl->setBlockMissingReturnType(false);
8721 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008722
John McCall82dc0092010-06-04 11:21:44 +00008723 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008724 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008725 if (ExplicitSignature) {
8726 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8727 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008728 if (Param->getIdentifier() == 0 &&
8729 !Param->isImplicit() &&
8730 !Param->isInvalidDecl() &&
8731 !getLangOptions().CPlusPlus)
8732 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008733 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008734 }
John McCall82dc0092010-06-04 11:21:44 +00008735
8736 // Fake up parameter variables if we have a typedef, like
8737 // ^ fntype { ... }
8738 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8739 for (FunctionProtoType::arg_type_iterator
8740 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8741 ParmVarDecl *Param =
8742 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8743 ParamInfo.getSourceRange().getBegin(),
8744 *I);
John McCallc71a4912010-06-04 19:02:56 +00008745 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008746 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008747 }
John McCall82dc0092010-06-04 11:21:44 +00008748
John McCallc71a4912010-06-04 19:02:56 +00008749 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008750 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00008751 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00008752 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8753 CurBlock->TheDecl->param_end(),
8754 /*CheckParameterNames=*/false);
8755 }
8756
John McCall82dc0092010-06-04 11:21:44 +00008757 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008758 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008759
John McCallc71a4912010-06-04 19:02:56 +00008760 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008761 Diag(ParamInfo.getAttributes()->getLoc(),
8762 diag::warn_attribute_sentinel_not_variadic) << 1;
8763 // FIXME: remove the attribute.
8764 }
8765
8766 // Put the parameter variables in scope. We can bail out immediately
8767 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008768 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008769 return;
8770
Steve Naroff090276f2008-10-10 01:28:17 +00008771 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008772 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8773 (*AI)->setOwningFunction(CurBlock->TheDecl);
8774
Steve Naroff090276f2008-10-10 01:28:17 +00008775 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008776 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008777 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008778
Steve Naroff090276f2008-10-10 01:28:17 +00008779 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008780 }
John McCall7a9813c2010-01-22 00:28:27 +00008781 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008782}
8783
8784/// ActOnBlockError - If there is an error parsing a block, this callback
8785/// is invoked to pop the information about the block from the action impl.
8786void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00008787 // Leave the expression-evaluation context.
8788 DiscardCleanupsInEvaluationContext();
8789 PopExpressionEvaluationContext();
8790
Steve Naroff4eb206b2008-09-03 18:15:37 +00008791 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008792 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008793 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008794}
8795
8796/// ActOnBlockStmtExpr - This is called when the body of a block statement
8797/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008798ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008799 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008800 // If blocks are disabled, emit an error.
8801 if (!LangOpts.Blocks)
8802 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008803
John McCall538773c2011-11-11 03:19:12 +00008804 // Leave the expression-evaluation context.
8805 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8806 PopExpressionEvaluationContext();
8807
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008808 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008809
Steve Naroff090276f2008-10-10 01:28:17 +00008810 PopDeclContext();
8811
Steve Naroff4eb206b2008-09-03 18:15:37 +00008812 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008813 if (!BSI->ReturnType.isNull())
8814 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008815
Mike Stump56925862009-07-28 22:04:01 +00008816 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008817 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008818
John McCall469a1eb2011-02-02 13:00:07 +00008819 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008820 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8821 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008822
John McCallc71a4912010-06-04 19:02:56 +00008823 // If the user wrote a function type in some form, try to use that.
8824 if (!BSI->FunctionType.isNull()) {
8825 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8826
8827 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8828 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8829
8830 // Turn protoless block types into nullary block types.
8831 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008832 FunctionProtoType::ExtProtoInfo EPI;
8833 EPI.ExtInfo = Ext;
8834 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008835
8836 // Otherwise, if we don't need to change anything about the function type,
8837 // preserve its sugar structure.
8838 } else if (FTy->getResultType() == RetTy &&
8839 (!NoReturn || FTy->getNoReturnAttr())) {
8840 BlockTy = BSI->FunctionType;
8841
8842 // Otherwise, make the minimal modifications to the function type.
8843 } else {
8844 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008845 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8846 EPI.TypeQuals = 0; // FIXME: silently?
8847 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008848 BlockTy = Context.getFunctionType(RetTy,
8849 FPT->arg_type_begin(),
8850 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008851 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008852 }
8853
8854 // If we don't have a function type, just build one from nothing.
8855 } else {
John McCalle23cf432010-12-14 08:05:40 +00008856 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008857 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008858 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008859 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008860
John McCallc71a4912010-06-04 19:02:56 +00008861 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8862 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008863 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008864
Chris Lattner17a78302009-04-19 05:28:12 +00008865 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008866 if (getCurFunction()->NeedsScopeChecking() &&
8867 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008868 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008869
Chris Lattnere476bdc2011-02-17 23:58:47 +00008870 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008871
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008872 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8873 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8874 const VarDecl *variable = ci->getVariable();
8875 QualType T = variable->getType();
8876 QualType::DestructionKind destructKind = T.isDestructedType();
8877 if (destructKind != QualType::DK_none)
8878 getCurFunction()->setHasBranchProtectedScope();
8879 }
8880
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008881 computeNRVO(Body, getCurBlock());
8882
Benjamin Kramerd2486192011-07-12 14:11:05 +00008883 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8884 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8885 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8886
John McCall80ee6e82011-11-10 05:35:25 +00008887 // If the block isn't obviously global, i.e. it captures anything at
8888 // all, mark this full-expression as needing a cleanup.
8889 if (Result->getBlockDecl()->hasCaptures()) {
8890 ExprCleanupObjects.push_back(Result->getBlockDecl());
8891 ExprNeedsCleanups = true;
8892 }
8893
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008894 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008895}
8896
John McCall60d7b3a2010-08-24 06:29:42 +00008897ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008898 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008899 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008900 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008901 GetTypeFromParser(Ty, &TInfo);
8902 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008903}
8904
John McCall60d7b3a2010-08-24 06:29:42 +00008905ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008906 Expr *E, TypeSourceInfo *TInfo,
8907 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008908 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008909
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008910 // Get the va_list type
8911 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008912 if (VaListType->isArrayType()) {
8913 // Deal with implicit array decay; for example, on x86-64,
8914 // va_list is an array, but it's supposed to decay to
8915 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008916 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008917 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008918 ExprResult Result = UsualUnaryConversions(E);
8919 if (Result.isInvalid())
8920 return ExprError();
8921 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008922 } else {
8923 // Otherwise, the va_list argument must be an l-value because
8924 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008925 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008926 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008927 return ExprError();
8928 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008929
Douglas Gregordd027302009-05-19 23:10:31 +00008930 if (!E->isTypeDependent() &&
8931 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008932 return ExprError(Diag(E->getLocStart(),
8933 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008934 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008935 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008936
David Majnemer0adde122011-06-14 05:17:32 +00008937 if (!TInfo->getType()->isDependentType()) {
8938 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8939 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8940 << TInfo->getTypeLoc().getSourceRange()))
8941 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008942
David Majnemer0adde122011-06-14 05:17:32 +00008943 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8944 TInfo->getType(),
8945 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8946 << TInfo->getTypeLoc().getSourceRange()))
8947 return ExprError();
8948
Douglas Gregor4eb75222011-07-30 06:45:27 +00008949 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008950 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008951 TInfo->getType()->isObjCLifetimeType()
8952 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8953 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008954 << TInfo->getType()
8955 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008956 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008957
8958 // Check for va_arg where arguments of the given type will be promoted
8959 // (i.e. this va_arg is guaranteed to have undefined behavior).
8960 QualType PromoteType;
8961 if (TInfo->getType()->isPromotableIntegerType()) {
8962 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8963 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8964 PromoteType = QualType();
8965 }
8966 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8967 PromoteType = Context.DoubleTy;
8968 if (!PromoteType.isNull())
8969 Diag(TInfo->getTypeLoc().getBeginLoc(),
8970 diag::warn_second_parameter_to_va_arg_never_compatible)
8971 << TInfo->getType()
8972 << PromoteType
8973 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008974 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008975
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008976 QualType T = TInfo->getType().getNonLValueExprType(Context);
8977 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008978}
8979
John McCall60d7b3a2010-08-24 06:29:42 +00008980ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008981 // The type of __null will be int or long, depending on the size of
8982 // pointers on the target.
8983 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008984 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8985 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008986 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008987 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008988 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008989 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008990 Ty = Context.LongLongTy;
8991 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00008992 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008993 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008994
Sebastian Redlf53597f2009-03-15 17:47:39 +00008995 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008996}
8997
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008998static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008999 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009000 if (!SemaRef.getLangOptions().ObjC1)
9001 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009002
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009003 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9004 if (!PT)
9005 return;
9006
9007 // Check if the destination is of type 'id'.
9008 if (!PT->isObjCIdType()) {
9009 // Check if the destination is the 'NSString' interface.
9010 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9011 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9012 return;
9013 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009014
John McCall4b9c2d22011-11-06 09:01:30 +00009015 // Ignore any parens, implicit casts (should only be
9016 // array-to-pointer decays), and not-so-opaque values. The last is
9017 // important for making this trigger for property assignments.
9018 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9019 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9020 if (OV->getSourceExpr())
9021 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9022
9023 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009024 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009025 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009026
Douglas Gregor849b2432010-03-31 17:46:05 +00009027 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009028}
9029
Chris Lattner5cf216b2008-01-04 18:04:52 +00009030bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9031 SourceLocation Loc,
9032 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009033 Expr *SrcExpr, AssignmentAction Action,
9034 bool *Complained) {
9035 if (Complained)
9036 *Complained = false;
9037
Chris Lattner5cf216b2008-01-04 18:04:52 +00009038 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009039 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009040 bool isInvalid = false;
9041 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009042 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009043 ConversionFixItGenerator ConvHints;
9044 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009045 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009046
Chris Lattner5cf216b2008-01-04 18:04:52 +00009047 switch (ConvTy) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009048 default: llvm_unreachable("Unknown conversion type");
Chris Lattner5cf216b2008-01-04 18:04:52 +00009049 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009050 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009051 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009052 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9053 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009054 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009055 case IntToPointer:
9056 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009057 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9058 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009059 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009060 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009061 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009062 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009063 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9064 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009065 if (Hint.isNull() && !CheckInferredResultType) {
9066 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9067 }
9068 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009069 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009070 case IncompatiblePointerSign:
9071 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9072 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009073 case FunctionVoidPointer:
9074 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9075 break;
John McCall86c05f32011-02-01 00:10:29 +00009076 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009077 // Perform array-to-pointer decay if necessary.
9078 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9079
John McCall86c05f32011-02-01 00:10:29 +00009080 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9081 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9082 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9083 DiagKind = diag::err_typecheck_incompatible_address_space;
9084 break;
John McCallf85e1932011-06-15 23:02:42 +00009085
9086
9087 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009088 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009089 break;
John McCall86c05f32011-02-01 00:10:29 +00009090 }
9091
9092 llvm_unreachable("unknown error case for discarding qualifiers!");
9093 // fallthrough
9094 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009095 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009096 // If the qualifiers lost were because we were applying the
9097 // (deprecated) C++ conversion from a string literal to a char*
9098 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9099 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009100 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009101 // bit of refactoring (so that the second argument is an
9102 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009103 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009104 // C++ semantics.
9105 if (getLangOptions().CPlusPlus &&
9106 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9107 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009108 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9109 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009110 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009111 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009112 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009113 case IntToBlockPointer:
9114 DiagKind = diag::err_int_to_block_pointer;
9115 break;
9116 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009117 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009118 break;
Steve Naroff39579072008-10-14 22:18:38 +00009119 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009120 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009121 // it can give a more specific diagnostic.
9122 DiagKind = diag::warn_incompatible_qualified_id;
9123 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009124 case IncompatibleVectors:
9125 DiagKind = diag::warn_incompatible_vectors;
9126 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009127 case IncompatibleObjCWeakRef:
9128 DiagKind = diag::err_arc_weak_unavailable_assign;
9129 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009130 case Incompatible:
9131 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009132 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9133 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009134 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009135 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009136 break;
9137 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009138
Douglas Gregord4eea832010-04-09 00:35:39 +00009139 QualType FirstType, SecondType;
9140 switch (Action) {
9141 case AA_Assigning:
9142 case AA_Initializing:
9143 // The destination type comes first.
9144 FirstType = DstType;
9145 SecondType = SrcType;
9146 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009147
Douglas Gregord4eea832010-04-09 00:35:39 +00009148 case AA_Returning:
9149 case AA_Passing:
9150 case AA_Converting:
9151 case AA_Sending:
9152 case AA_Casting:
9153 // The source type comes first.
9154 FirstType = SrcType;
9155 SecondType = DstType;
9156 break;
9157 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009158
Anna Zaks67221552011-07-28 19:51:27 +00009159 PartialDiagnostic FDiag = PDiag(DiagKind);
9160 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9161
9162 // If we can fix the conversion, suggest the FixIts.
9163 assert(ConvHints.isNull() || Hint.isNull());
9164 if (!ConvHints.isNull()) {
9165 for (llvm::SmallVector<FixItHint, 1>::iterator
9166 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9167 HI != HE; ++HI)
9168 FDiag << *HI;
9169 } else {
9170 FDiag << Hint;
9171 }
9172 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9173
Richard Trieu6efd4c52011-11-23 22:32:32 +00009174 if (MayHaveFunctionDiff)
9175 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9176
Anna Zaks67221552011-07-28 19:51:27 +00009177 Diag(Loc, FDiag);
9178
Richard Trieu6efd4c52011-11-23 22:32:32 +00009179 if (SecondType == Context.OverloadTy)
9180 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9181 FirstType);
9182
Douglas Gregor926df6c2011-06-11 01:09:30 +00009183 if (CheckInferredResultType)
9184 EmitRelatedResultTypeNote(SrcExpr);
9185
Douglas Gregora41a8c52010-04-22 00:20:18 +00009186 if (Complained)
9187 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009188 return isInvalid;
9189}
Anders Carlssone21555e2008-11-30 19:50:32 +00009190
Chris Lattner3bf68932009-04-25 21:59:05 +00009191bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009192 llvm::APSInt ICEResult;
9193 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9194 if (Result)
9195 *Result = ICEResult;
9196 return false;
9197 }
9198
Anders Carlssone21555e2008-11-30 19:50:32 +00009199 Expr::EvalResult EvalResult;
9200
Richard Smith51f47082011-10-29 00:50:52 +00009201 if (!E->EvaluateAsRValue(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009202 EvalResult.HasSideEffects) {
9203 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9204
9205 if (EvalResult.Diag) {
9206 // We only show the note if it's not the usual "invalid subexpression"
9207 // or if it's actually in a subexpression.
9208 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9209 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9210 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9211 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009212
Anders Carlssone21555e2008-11-30 19:50:32 +00009213 return true;
9214 }
9215
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009216 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9217 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009218
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009219 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009220 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikied6471f72011-09-25 23:23:43 +00009221 != DiagnosticsEngine::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009222 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009223
Anders Carlssone21555e2008-11-30 19:50:32 +00009224 if (Result)
9225 *Result = EvalResult.Val.getInt();
9226 return false;
9227}
Douglas Gregore0762c92009-06-19 23:52:42 +00009228
Douglas Gregor2afce722009-11-26 00:44:06 +00009229void
Mike Stump1eb44332009-09-09 15:08:12 +00009230Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009231 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009232 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +00009233 ExprCleanupObjects.size(),
John McCallf85e1932011-06-15 23:02:42 +00009234 ExprNeedsCleanups));
9235 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009236}
9237
Richard Trieu67e29332011-08-02 04:35:43 +00009238void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009239 // Pop the current expression evaluation context off the stack.
9240 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9241 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009242
Douglas Gregor06d33692009-12-12 07:57:52 +00009243 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9244 if (Rec.PotentiallyReferenced) {
9245 // Mark any remaining declarations in the current position of the stack
9246 // as "referenced". If they were not meant to be referenced, semantic
9247 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009248 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009249 I = Rec.PotentiallyReferenced->begin(),
9250 IEnd = Rec.PotentiallyReferenced->end();
9251 I != IEnd; ++I)
9252 MarkDeclarationReferenced(I->first, I->second);
9253 }
9254
9255 if (Rec.PotentiallyDiagnosed) {
9256 // Emit any pending diagnostics.
9257 for (PotentiallyEmittedDiagnostics::iterator
9258 I = Rec.PotentiallyDiagnosed->begin(),
9259 IEnd = Rec.PotentiallyDiagnosed->end();
9260 I != IEnd; ++I)
9261 Diag(I->first, I->second);
9262 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009263 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009264
9265 // When are coming out of an unevaluated context, clear out any
9266 // temporaries that we may have created as part of the evaluation of
9267 // the expression in that context: they aren't relevant because they
9268 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009269 if (Rec.Context == Unevaluated) {
John McCall80ee6e82011-11-10 05:35:25 +00009270 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9271 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +00009272 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9273
9274 // Otherwise, merge the contexts together.
9275 } else {
9276 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9277 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009278
9279 // Destroy the popped expression evaluation record.
9280 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009281}
Douglas Gregore0762c92009-06-19 23:52:42 +00009282
John McCallf85e1932011-06-15 23:02:42 +00009283void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +00009284 ExprCleanupObjects.erase(
9285 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9286 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +00009287 ExprNeedsCleanups = false;
9288}
9289
Douglas Gregore0762c92009-06-19 23:52:42 +00009290/// \brief Note that the given declaration was referenced in the source code.
9291///
9292/// This routine should be invoke whenever a given declaration is referenced
9293/// in the source code, and where that reference occurred. If this declaration
9294/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9295/// C99 6.9p3), then the declaration will be marked as used.
9296///
9297/// \param Loc the location where the declaration was referenced.
9298///
9299/// \param D the declaration that has been referenced by the source code.
9300void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9301 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009302
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009303 D->setReferenced();
9304
Douglas Gregorc070cc62010-06-17 23:14:26 +00009305 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009306 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009307
Richard Trieu67e29332011-08-02 04:35:43 +00009308 // Mark a parameter or variable declaration "used", regardless of whether
9309 // we're in a template or not. The reason for this is that unevaluated
9310 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9311 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009312 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009313 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009314 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009315 return;
9316 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009317
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009318 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9319 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009320
Douglas Gregore0762c92009-06-19 23:52:42 +00009321 // Do not mark anything as "used" within a dependent context; wait for
9322 // an instantiation.
9323 if (CurContext->isDependentContext())
9324 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009325
Douglas Gregor2afce722009-11-26 00:44:06 +00009326 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009327 case Unevaluated:
9328 // We are in an expression that is not potentially evaluated; do nothing.
9329 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009330
Douglas Gregorac7610d2009-06-22 20:57:11 +00009331 case PotentiallyEvaluated:
9332 // We are in a potentially-evaluated expression, so this declaration is
9333 // "used"; handle this below.
9334 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009335
Douglas Gregorac7610d2009-06-22 20:57:11 +00009336 case PotentiallyPotentiallyEvaluated:
9337 // We are in an expression that may be potentially evaluated; queue this
9338 // declaration reference until we know whether the expression is
9339 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009340 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009341 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009342
9343 case PotentiallyEvaluatedIfUsed:
9344 // Referenced declarations will only be used if the construct in the
9345 // containing expression is used.
9346 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009347 }
Mike Stump1eb44332009-09-09 15:08:12 +00009348
Douglas Gregore0762c92009-06-19 23:52:42 +00009349 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009350 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 if (Constructor->isDefaulted()) {
9352 if (Constructor->isDefaultConstructor()) {
9353 if (Constructor->isTrivial())
9354 return;
9355 if (!Constructor->isUsed(false))
9356 DefineImplicitDefaultConstructor(Loc, Constructor);
9357 } else if (Constructor->isCopyConstructor()) {
9358 if (!Constructor->isUsed(false))
9359 DefineImplicitCopyConstructor(Loc, Constructor);
9360 } else if (Constructor->isMoveConstructor()) {
9361 if (!Constructor->isUsed(false))
9362 DefineImplicitMoveConstructor(Loc, Constructor);
9363 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009364 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009365
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009366 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009367 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009368 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009369 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009370 if (Destructor->isVirtual())
9371 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009372 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009373 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009374 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009375 if (!MethodDecl->isUsed(false)) {
9376 if (MethodDecl->isCopyAssignmentOperator())
9377 DefineImplicitCopyAssignment(Loc, MethodDecl);
9378 else
9379 DefineImplicitMoveAssignment(Loc, MethodDecl);
9380 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009381 } else if (MethodDecl->isVirtual())
9382 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009383 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009384 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009385 // Recursive functions should be marked when used from another function.
9386 if (CurContext == Function) return;
9387
Mike Stump1eb44332009-09-09 15:08:12 +00009388 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009389 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009390 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009391 bool AlreadyInstantiated = false;
9392 if (FunctionTemplateSpecializationInfo *SpecInfo
9393 = Function->getTemplateSpecializationInfo()) {
9394 if (SpecInfo->getPointOfInstantiation().isInvalid())
9395 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009396 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009397 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009398 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009399 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009400 = Function->getMemberSpecializationInfo()) {
9401 if (MSInfo->getPointOfInstantiation().isInvalid())
9402 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009403 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009404 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009405 AlreadyInstantiated = true;
9406 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009407
Douglas Gregor60406be2010-01-16 22:29:39 +00009408 if (!AlreadyInstantiated) {
9409 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9410 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9411 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9412 Loc));
9413 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009414 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009415 }
John McCall15e310a2011-02-19 02:53:41 +00009416 } else {
9417 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009418 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9419 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009420 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009421 MarkDeclarationReferenced(Loc, *i);
9422 }
John McCall15e310a2011-02-19 02:53:41 +00009423 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009424
John McCall15e310a2011-02-19 02:53:41 +00009425 // Keep track of used but undefined functions.
9426 if (!Function->isPure() && !Function->hasBody() &&
9427 Function->getLinkage() != ExternalLinkage) {
9428 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9429 if (old.isInvalid()) old = Loc;
9430 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009431
John McCall15e310a2011-02-19 02:53:41 +00009432 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009433 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009434 }
Mike Stump1eb44332009-09-09 15:08:12 +00009435
Douglas Gregore0762c92009-06-19 23:52:42 +00009436 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009437 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009438 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009439 Var->getInstantiatedFromStaticDataMember()) {
9440 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9441 assert(MSInfo && "Missing member specialization information?");
9442 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9443 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9444 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009445 // This is a modification of an existing AST node. Notify listeners.
9446 if (ASTMutationListener *L = getASTMutationListener())
9447 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009448 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009449 }
9450 }
Mike Stump1eb44332009-09-09 15:08:12 +00009451
John McCall77efc682011-02-21 19:25:48 +00009452 // Keep track of used but undefined variables. We make a hole in
9453 // the warning for static const data members with in-line
9454 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009455 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009456 && Var->getLinkage() != ExternalLinkage
9457 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009458 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9459 if (old.isInvalid()) old = Loc;
9460 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009461
Douglas Gregore0762c92009-06-19 23:52:42 +00009462 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009463 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009464 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009465}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009466
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009467namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009468 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009469 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009470 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009471 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9472 Sema &S;
9473 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009474
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009475 public:
9476 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009477
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009478 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009479
9480 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9481 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009482 };
9483}
9484
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009485bool MarkReferencedDecls::TraverseTemplateArgument(
9486 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009487 if (Arg.getKind() == TemplateArgument::Declaration) {
9488 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9489 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009490
9491 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009492}
9493
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009494bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009495 if (ClassTemplateSpecializationDecl *Spec
9496 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9497 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009498 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009499 }
9500
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009501 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009502}
9503
9504void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9505 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009506 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009507}
9508
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009509namespace {
9510 /// \brief Helper class that marks all of the declarations referenced by
9511 /// potentially-evaluated subexpressions as "referenced".
9512 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9513 Sema &S;
9514
9515 public:
9516 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9517
9518 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9519
9520 void VisitDeclRefExpr(DeclRefExpr *E) {
9521 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9522 }
9523
9524 void VisitMemberExpr(MemberExpr *E) {
9525 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009526 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009527 }
9528
John McCall80ee6e82011-11-10 05:35:25 +00009529 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9530 S.MarkDeclarationReferenced(E->getLocStart(),
9531 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
9532 Visit(E->getSubExpr());
9533 }
9534
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009535 void VisitCXXNewExpr(CXXNewExpr *E) {
9536 if (E->getConstructor())
9537 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9538 if (E->getOperatorNew())
9539 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9540 if (E->getOperatorDelete())
9541 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009542 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009543 }
9544
9545 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9546 if (E->getOperatorDelete())
9547 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009548 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9549 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9550 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9551 S.MarkDeclarationReferenced(E->getLocStart(),
9552 S.LookupDestructor(Record));
9553 }
9554
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009555 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009556 }
9557
9558 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9559 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009560 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009561 }
9562
9563 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9564 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9565 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009566
9567 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9568 Visit(E->getExpr());
9569 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009570 };
9571}
9572
9573/// \brief Mark any declarations that appear within this expression or any
9574/// potentially-evaluated subexpressions as "referenced".
9575void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9576 EvaluatedExprMarker(*this).Visit(E);
9577}
9578
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009579/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9580/// of the program being compiled.
9581///
9582/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009583/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009584/// possibility that the code will actually be executable. Code in sizeof()
9585/// expressions, code used only during overload resolution, etc., are not
9586/// potentially evaluated. This routine will suppress such diagnostics or,
9587/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009588/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009589/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009590///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009591/// This routine should be used for all diagnostics that describe the run-time
9592/// behavior of a program, such as passing a non-POD value through an ellipsis.
9593/// Failure to do so will likely result in spurious diagnostics or failures
9594/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009595bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009596 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009597 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009598 case Unevaluated:
9599 // The argument will never be evaluated, so don't complain.
9600 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009601
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009602 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009603 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009604 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009605 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009606 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009607 }
9608 else
9609 Diag(Loc, PD);
9610
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009611 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009612
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009613 case PotentiallyPotentiallyEvaluated:
9614 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9615 break;
9616 }
9617
9618 return false;
9619}
9620
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009621bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9622 CallExpr *CE, FunctionDecl *FD) {
9623 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9624 return false;
9625
9626 PartialDiagnostic Note =
9627 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9628 << FD->getDeclName() : PDiag();
9629 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009630
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009631 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009632 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009633 PDiag(diag::err_call_function_incomplete_return)
9634 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009635 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009636 << CE->getSourceRange(),
9637 std::make_pair(NoteLoc, Note)))
9638 return true;
9639
9640 return false;
9641}
9642
Douglas Gregor92c3a042011-01-19 16:50:08 +00009643// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009644// will prevent this condition from triggering, which is what we want.
9645void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9646 SourceLocation Loc;
9647
John McCalla52ef082009-11-11 02:41:58 +00009648 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009649 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009650
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009651 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009652 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009653 return;
9654
Douglas Gregor92c3a042011-01-19 16:50:08 +00009655 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9656
John McCallc8d8ac52009-11-12 00:06:05 +00009657 // Greylist some idioms by putting them into a warning subcategory.
9658 if (ObjCMessageExpr *ME
9659 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9660 Selector Sel = ME->getSelector();
9661
John McCallc8d8ac52009-11-12 00:06:05 +00009662 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +00009663 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009664 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9665
9666 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009667 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009668 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9669 }
John McCalla52ef082009-11-11 02:41:58 +00009670
John McCall5a881bb2009-10-12 21:59:07 +00009671 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009672 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009673 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009674 return;
9675
Douglas Gregor92c3a042011-01-19 16:50:08 +00009676 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009677 Loc = Op->getOperatorLoc();
9678 } else {
9679 // Not an assignment.
9680 return;
9681 }
9682
Douglas Gregor55b38842010-04-14 16:09:52 +00009683 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009684
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009685 SourceLocation Open = E->getSourceRange().getBegin();
9686 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9687 Diag(Loc, diag::note_condition_assign_silence)
9688 << FixItHint::CreateInsertion(Open, "(")
9689 << FixItHint::CreateInsertion(Close, ")");
9690
Douglas Gregor92c3a042011-01-19 16:50:08 +00009691 if (IsOrAssign)
9692 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9693 << FixItHint::CreateReplacement(Loc, "!=");
9694 else
9695 Diag(Loc, diag::note_condition_assign_to_comparison)
9696 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009697}
9698
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009699/// \brief Redundant parentheses over an equality comparison can indicate
9700/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009701void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009702 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009703 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009704 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9705 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009706 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009707 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009708 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009709
Richard Trieuccd891a2011-09-09 01:45:06 +00009710 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009711
9712 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009713 if (opE->getOpcode() == BO_EQ &&
9714 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9715 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009716 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009717
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009718 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009719 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009720 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9721 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009722 Diag(Loc, diag::note_equality_comparison_to_assign)
9723 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009724 }
9725}
9726
John Wiegley429bb272011-04-08 18:41:53 +00009727ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009728 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009729 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9730 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009731
John McCall864c0412011-04-26 20:42:42 +00009732 ExprResult result = CheckPlaceholderExpr(E);
9733 if (result.isInvalid()) return ExprError();
9734 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009735
John McCall864c0412011-04-26 20:42:42 +00009736 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009737 if (getLangOptions().CPlusPlus)
9738 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9739
John Wiegley429bb272011-04-08 18:41:53 +00009740 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9741 if (ERes.isInvalid())
9742 return ExprError();
9743 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009744
9745 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009746 if (!T->isScalarType()) { // C99 6.8.4.1p1
9747 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9748 << T << E->getSourceRange();
9749 return ExprError();
9750 }
John McCall5a881bb2009-10-12 21:59:07 +00009751 }
9752
John Wiegley429bb272011-04-08 18:41:53 +00009753 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009754}
Douglas Gregor586596f2010-05-06 17:25:47 +00009755
John McCall60d7b3a2010-08-24 06:29:42 +00009756ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009757 Expr *SubExpr) {
9758 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009759 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009760
Richard Trieuccd891a2011-09-09 01:45:06 +00009761 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009762}
John McCall2a984ca2010-10-12 00:20:44 +00009763
John McCall1de4d4e2011-04-07 08:22:57 +00009764namespace {
John McCall755d8492011-04-12 00:42:48 +00009765 /// A visitor for rebuilding a call to an __unknown_any expression
9766 /// to have an appropriate type.
9767 struct RebuildUnknownAnyFunction
9768 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9769
9770 Sema &S;
9771
9772 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9773
9774 ExprResult VisitStmt(Stmt *S) {
9775 llvm_unreachable("unexpected statement!");
9776 return ExprError();
9777 }
9778
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009779 ExprResult VisitExpr(Expr *E) {
9780 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9781 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009782 return ExprError();
9783 }
9784
9785 /// Rebuild an expression which simply semantically wraps another
9786 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009787 template <class T> ExprResult rebuildSugarExpr(T *E) {
9788 ExprResult SubResult = Visit(E->getSubExpr());
9789 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009790
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009791 Expr *SubExpr = SubResult.take();
9792 E->setSubExpr(SubExpr);
9793 E->setType(SubExpr->getType());
9794 E->setValueKind(SubExpr->getValueKind());
9795 assert(E->getObjectKind() == OK_Ordinary);
9796 return E;
John McCall755d8492011-04-12 00:42:48 +00009797 }
9798
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009799 ExprResult VisitParenExpr(ParenExpr *E) {
9800 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009801 }
9802
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009803 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9804 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009805 }
9806
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009807 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9808 ExprResult SubResult = Visit(E->getSubExpr());
9809 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009810
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009811 Expr *SubExpr = SubResult.take();
9812 E->setSubExpr(SubExpr);
9813 E->setType(S.Context.getPointerType(SubExpr->getType()));
9814 assert(E->getValueKind() == VK_RValue);
9815 assert(E->getObjectKind() == OK_Ordinary);
9816 return E;
John McCall755d8492011-04-12 00:42:48 +00009817 }
9818
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009819 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9820 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009821
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009822 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009823
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009824 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009825 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009826 !(isa<CXXMethodDecl>(VD) &&
9827 cast<CXXMethodDecl>(VD)->isInstance()))
9828 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009829
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009830 return E;
John McCall755d8492011-04-12 00:42:48 +00009831 }
9832
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009833 ExprResult VisitMemberExpr(MemberExpr *E) {
9834 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009835 }
9836
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009837 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9838 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009839 }
9840 };
9841}
9842
9843/// Given a function expression of unknown-any type, try to rebuild it
9844/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009845static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9846 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9847 if (Result.isInvalid()) return ExprError();
9848 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009849}
9850
9851namespace {
John McCall379b5152011-04-11 07:02:50 +00009852 /// A visitor for rebuilding an expression of type __unknown_anytype
9853 /// into one which resolves the type directly on the referring
9854 /// expression. Strict preservation of the original source
9855 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009856 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009857 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009858
9859 Sema &S;
9860
9861 /// The current destination type.
9862 QualType DestType;
9863
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009864 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9865 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009866
John McCalla5fc4722011-04-09 22:50:59 +00009867 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009868 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009869 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009870 }
9871
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009872 ExprResult VisitExpr(Expr *E) {
9873 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9874 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009875 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009876 }
9877
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009878 ExprResult VisitCallExpr(CallExpr *E);
9879 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009880
John McCalla5fc4722011-04-09 22:50:59 +00009881 /// Rebuild an expression which simply semantically wraps another
9882 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009883 template <class T> ExprResult rebuildSugarExpr(T *E) {
9884 ExprResult SubResult = Visit(E->getSubExpr());
9885 if (SubResult.isInvalid()) return ExprError();
9886 Expr *SubExpr = SubResult.take();
9887 E->setSubExpr(SubExpr);
9888 E->setType(SubExpr->getType());
9889 E->setValueKind(SubExpr->getValueKind());
9890 assert(E->getObjectKind() == OK_Ordinary);
9891 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009892 }
John McCall1de4d4e2011-04-07 08:22:57 +00009893
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009894 ExprResult VisitParenExpr(ParenExpr *E) {
9895 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009896 }
9897
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009898 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9899 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009900 }
9901
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009902 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9903 const PointerType *Ptr = DestType->getAs<PointerType>();
9904 if (!Ptr) {
9905 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9906 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009907 return ExprError();
9908 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009909 assert(E->getValueKind() == VK_RValue);
9910 assert(E->getObjectKind() == OK_Ordinary);
9911 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009912
9913 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009914 DestType = Ptr->getPointeeType();
9915 ExprResult SubResult = Visit(E->getSubExpr());
9916 if (SubResult.isInvalid()) return ExprError();
9917 E->setSubExpr(SubResult.take());
9918 return E;
John McCall755d8492011-04-12 00:42:48 +00009919 }
9920
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009921 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009922
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009923 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009924
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009925 ExprResult VisitMemberExpr(MemberExpr *E) {
9926 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009927 }
John McCalla5fc4722011-04-09 22:50:59 +00009928
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009929 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9930 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009931 }
9932 };
9933}
9934
John McCall379b5152011-04-11 07:02:50 +00009935/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009936ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9937 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009938
9939 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009940 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009941 FK_FunctionPointer,
9942 FK_BlockPointer
9943 };
9944
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009945 FnKind Kind;
9946 QualType CalleeType = CalleeExpr->getType();
9947 if (CalleeType == S.Context.BoundMemberTy) {
9948 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9949 Kind = FK_MemberFunction;
9950 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9951 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9952 CalleeType = Ptr->getPointeeType();
9953 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009954 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009955 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9956 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009957 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009958 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009959
9960 // Verify that this is a legal result type of a function.
9961 if (DestType->isArrayType() || DestType->isFunctionType()) {
9962 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009963 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009964 diagID = diag::err_block_returning_array_function;
9965
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009966 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009967 << DestType->isFunctionType() << DestType;
9968 return ExprError();
9969 }
9970
9971 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009972 E->setType(DestType.getNonLValueExprType(S.Context));
9973 E->setValueKind(Expr::getValueKindForType(DestType));
9974 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009975
9976 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009977 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009978 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009979 Proto->arg_type_begin(),
9980 Proto->getNumArgs(),
9981 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009982 else
9983 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009984 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009985
9986 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009987 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009988 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009989 // Nothing to do.
9990 break;
9991
9992 case FK_FunctionPointer:
9993 DestType = S.Context.getPointerType(DestType);
9994 break;
9995
9996 case FK_BlockPointer:
9997 DestType = S.Context.getBlockPointerType(DestType);
9998 break;
9999 }
10000
10001 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010002 ExprResult CalleeResult = Visit(CalleeExpr);
10003 if (!CalleeResult.isUsable()) return ExprError();
10004 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000010005
10006 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010007 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010008}
10009
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010010ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010011 // Verify that this is a legal result type of a call.
10012 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010013 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000010014 << DestType->isFunctionType() << DestType;
10015 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010016 }
10017
John McCall48218c62011-07-13 17:56:40 +000010018 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010019 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10020 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10021 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000010022 }
John McCall755d8492011-04-12 00:42:48 +000010023
John McCall379b5152011-04-11 07:02:50 +000010024 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010025 E->setType(DestType.getNonReferenceType());
10026 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010027
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010028 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010029}
10030
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010031ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010032 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010033 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10034 assert(E->getValueKind() == VK_RValue);
10035 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000010036
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010037 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000010038
John McCall379b5152011-04-11 07:02:50 +000010039 // Rebuild the sub-expression as the pointee (function) type.
10040 DestType = DestType->castAs<PointerType>()->getPointeeType();
10041
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010042 ExprResult Result = Visit(E->getSubExpr());
10043 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010044
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010045 E->setSubExpr(Result.take());
10046 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010047}
10048
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010049ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10050 ExprValueKind ValueKind = VK_LValue;
10051 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000010052
10053 // We know how to make this work for certain kinds of decls:
10054
10055 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010056 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10057 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10058 DestType = Ptr->getPointeeType();
10059 ExprResult Result = resolveDecl(E, VD);
10060 if (Result.isInvalid()) return ExprError();
10061 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000010062 CK_FunctionToPointerDecay, VK_RValue);
10063 }
10064
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010065 if (!Type->isFunctionType()) {
10066 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10067 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000010068 return ExprError();
10069 }
John McCall379b5152011-04-11 07:02:50 +000010070
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010071 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10072 if (MD->isInstance()) {
10073 ValueKind = VK_RValue;
10074 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000010075 }
10076
John McCall379b5152011-04-11 07:02:50 +000010077 // Function references aren't l-values in C.
10078 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010079 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000010080
10081 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010082 } else if (isa<VarDecl>(VD)) {
10083 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10084 Type = RefTy->getPointeeType();
10085 } else if (Type->isFunctionType()) {
10086 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10087 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000010088 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010089 }
10090
10091 // - nothing else
10092 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010093 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10094 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010095 return ExprError();
10096 }
10097
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010098 VD->setType(DestType);
10099 E->setType(Type);
10100 E->setValueKind(ValueKind);
10101 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010102}
10103
John McCall1de4d4e2011-04-07 08:22:57 +000010104/// Check a cast of an unknown-any type. We intentionally only
10105/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000010106ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10107 Expr *CastExpr, CastKind &CastKind,
10108 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010109 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010110 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010111 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010112
Richard Trieuccd891a2011-09-09 01:45:06 +000010113 CastExpr = result.take();
10114 VK = CastExpr->getValueKind();
10115 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010116
Richard Trieuccd891a2011-09-09 01:45:06 +000010117 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010118}
10119
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000010120ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
10121 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
10122}
10123
Richard Trieuccd891a2011-09-09 01:45:06 +000010124static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10125 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010126 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010127 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010128 E = E->IgnoreParenImpCasts();
10129 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10130 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010131 diagID = diag::err_uncasted_call_of_unknown_any;
10132 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010133 break;
John McCall379b5152011-04-11 07:02:50 +000010134 }
John McCall1de4d4e2011-04-07 08:22:57 +000010135 }
10136
John McCall379b5152011-04-11 07:02:50 +000010137 SourceLocation loc;
10138 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010139 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010140 loc = ref->getLocation();
10141 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010142 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010143 loc = mem->getMemberLoc();
10144 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010145 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010146 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000010147 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000010148 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010149 if (!d) {
10150 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10151 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10152 << orig->getSourceRange();
10153 return ExprError();
10154 }
John McCall379b5152011-04-11 07:02:50 +000010155 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010156 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10157 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010158 return ExprError();
10159 }
10160
10161 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010162
10163 // Never recoverable.
10164 return ExprError();
10165}
10166
John McCall2a984ca2010-10-12 00:20:44 +000010167/// Check for operands with placeholder types and complain if found.
10168/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010169ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000010170 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
10171 if (!placeholderType) return Owned(E);
10172
10173 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000010174
John McCall1de4d4e2011-04-07 08:22:57 +000010175 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000010176 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000010177 // Try to resolve a single function template specialization.
10178 // This is obligatory.
10179 ExprResult result = Owned(E);
10180 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10181 return result;
10182
10183 // If that failed, try to recover with a call.
10184 } else {
10185 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10186 /*complain*/ true);
10187 return result;
10188 }
10189 }
John McCall1de4d4e2011-04-07 08:22:57 +000010190
John McCall864c0412011-04-26 20:42:42 +000010191 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000010192 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000010193 ExprResult result = Owned(E);
10194 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10195 /*complain*/ true);
10196 return result;
John McCall5acb0c92011-10-17 18:40:02 +000010197 }
10198
10199 // ARC unbridged casts.
10200 case BuiltinType::ARCUnbridgedCast: {
10201 Expr *realCast = stripARCUnbridgedCast(E);
10202 diagnoseARCUnbridgedCast(realCast);
10203 return Owned(realCast);
10204 }
John McCall864c0412011-04-26 20:42:42 +000010205
John McCall1de4d4e2011-04-07 08:22:57 +000010206 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000010207 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000010208 return diagnoseUnknownAnyExpr(*this, E);
10209
John McCall3c3b7f92011-10-25 17:37:35 +000010210 // Pseudo-objects.
10211 case BuiltinType::PseudoObject:
10212 return checkPseudoObjectRValue(E);
10213
John McCalle0a22d02011-10-18 21:02:43 +000010214 // Everything else should be impossible.
10215#define BUILTIN_TYPE(Id, SingletonId) \
10216 case BuiltinType::Id:
10217#define PLACEHOLDER_TYPE(Id, SingletonId)
10218#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000010219 break;
10220 }
10221
10222 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000010223}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010224
Richard Trieuccd891a2011-09-09 01:45:06 +000010225bool Sema::CheckCaseExpression(Expr *E) {
10226 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010227 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010228 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10229 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010230 return false;
10231}