blob: e6e6e5f5e1ec45afdab379a8d290cb7b12bd5c48 [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);
71 switch (Result) {
72 case AR_Available:
73 case AR_NotYetIntroduced:
74 break;
75
76 case AR_Deprecated:
77 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
78 break;
79
80 case AR_Unavailable:
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000081 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 if (Message.empty()) {
83 if (!UnknownObjCClass)
84 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
85 else
86 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
87 << D->getDeclName();
88 }
89 else
90 S.Diag(Loc, diag::err_unavailable_message)
91 << D->getDeclName() << Message;
92 S.Diag(D->getLocation(), diag::note_unavailable_here)
93 << isa<FunctionDecl>(D) << false;
94 }
95 break;
96 }
97 return Result;
98}
99
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000100/// \brief Determine whether the use of this declaration is valid, and
101/// emit any corresponding diagnostics.
102///
103/// This routine diagnoses various problems with referencing
104/// declarations that can occur when using a declaration. For example,
105/// it might warn if a deprecated or unavailable declaration is being
106/// used, or produce an error (and return true) if a C++0x deleted
107/// function is being used.
108///
109/// \returns true if there was an error (this declaration cannot be
110/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000111///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000112bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000114 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
115 // If there were any diagnostics suppressed by template argument deduction,
116 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000117 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000118 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
119 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000121 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
122 Diag(Suppressed[I].first, Suppressed[I].second);
123
124 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000125 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000126 // entry from the table, because we want to avoid ever emitting these
127 // diagnostics again.
128 Suppressed.clear();
129 }
130 }
131
Richard Smith34b41d92011-02-20 03:19:35 +0000132 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000133 if (ParsingInitForAutoVars.count(D)) {
134 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
135 << D->getDeclName();
136 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000137 }
138
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000139 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000141 if (FD->isDeleted()) {
142 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +0000143 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000144 return true;
145 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000146 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000147 AvailabilityResult Result =
148 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000149
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000150 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000151 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000152 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000153 // For available enumerator, it will become unavailable/deprecated
154 // if its enum declaration is as such.
155 if (Result == AR_Available)
156 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
157 const DeclContext *DC = ECD->getDeclContext();
158 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000159 DiagnoseAvailabilityOfDecl(*this,
160 const_cast< EnumDecl *>(TheEnumDecl),
161 Loc, UnknownObjCClass);
Fariborz Jahanian97db7262011-09-29 18:40:01 +0000162 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000163 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000164}
165
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000166/// \brief Retrieve the message suffix that should be added to a
167/// diagnostic complaining about the given function being deleted or
168/// unavailable.
169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170 // FIXME: C++0x implicitly-deleted special member functions could be
171 // detected here so that we could improve diagnostics to say, e.g.,
172 // "base class 'A' had a deleted copy constructor".
173 if (FD->isDeleted())
174 return std::string();
175
176 std::string Message;
177 if (FD->getAvailability(&Message))
178 return ": " + Message;
179
180 return std::string();
181}
182
John McCall3323fad2011-09-09 07:56:05 +0000183/// DiagnoseSentinelCalls - This routine checks whether a call or
184/// message-send is to a declaration with the sentinel attribute, and
185/// if so, it checks that the requirements of the sentinel are
186/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000188 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000189 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000190 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000191 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000192
John McCall3323fad2011-09-09 07:56:05 +0000193 // The number of formal parameters of the declaration.
194 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
John McCall3323fad2011-09-09 07:56:05 +0000196 // The kind of declaration. This is also an index into a %select in
197 // the diagnostic.
198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000201 numFormalParams = MD->param_size();
202 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000204 numFormalParams = FD->param_size();
205 calleeType = CT_Function;
206 } else if (isa<VarDecl>(D)) {
207 QualType type = cast<ValueDecl>(D)->getType();
208 const FunctionType *fn = 0;
209 if (const PointerType *ptr = type->getAs<PointerType>()) {
210 fn = ptr->getPointeeType()->getAs<FunctionType>();
211 if (!fn) return;
212 calleeType = CT_Function;
213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214 fn = ptr->getPointeeType()->castAs<FunctionType>();
215 calleeType = CT_Block;
216 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000217 return;
John McCall3323fad2011-09-09 07:56:05 +0000218 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000219
John McCall3323fad2011-09-09 07:56:05 +0000220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221 numFormalParams = proto->getNumArgs();
222 } else {
223 numFormalParams = 0;
224 }
225 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000226 return;
227 }
John McCall3323fad2011-09-09 07:56:05 +0000228
229 // "nullPos" is the number of formal parameters at the end which
230 // effectively count as part of the variadic arguments. This is
231 // useful if you would prefer to not have *any* formal parameters,
232 // but the language forces you to have at least one.
233 unsigned nullPos = attr->getNullPos();
234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236
237 // The number of arguments which should follow the sentinel.
238 unsigned numArgsAfterSentinel = attr->getSentinel();
239
240 // If there aren't enough arguments for all the formal parameters,
241 // the sentinel, and the args after the sentinel, complain.
242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000245 return;
246 }
John McCall3323fad2011-09-09 07:56:05 +0000247
248 // Otherwise, find the sentinel expression.
249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000250 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000251 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000252
253 // nullptr_t is always treated as null.
254 if (sentinelExpr->getType()->isNullPtrType()) return;
255
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000256 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000257 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
258 Expr::NPC_ValueDependentIsNull))
259 return;
260
261 // Unfortunately, __null has type 'int'.
262 if (isa<GNUNullExpr>(sentinelExpr)) return;
263
John McCall3323fad2011-09-09 07:56:05 +0000264 // Pick a reasonable string to insert. Optimistically use 'nil' or
265 // 'NULL' if those are actually defined in the context. Only use
266 // 'nil' for ObjC methods, where it's much more likely that the
267 // variadic arguments form a list of object pointers.
268 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000269 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
270 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000271 if (calleeType == CT_Method &&
272 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000273 NullValue = "nil";
274 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
275 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000276 else
John McCall3323fad2011-09-09 07:56:05 +0000277 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000278
279 if (MissingNilLoc.isInvalid())
280 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
281 else
282 Diag(MissingNilLoc, diag::warn_missing_sentinel)
283 << calleeType
284 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000285 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000286}
287
Richard Trieuccd891a2011-09-09 01:45:06 +0000288SourceRange Sema::getExprRange(Expr *E) const {
289 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000290}
291
Chris Lattnere7a2e912008-07-25 21:10:04 +0000292//===----------------------------------------------------------------------===//
293// Standard Promotions and Conversions
294//===----------------------------------------------------------------------===//
295
Chris Lattnere7a2e912008-07-25 21:10:04 +0000296/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000297ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000298 // Handle any placeholder expressions which made it here.
299 if (E->getType()->isPlaceholderType()) {
300 ExprResult result = CheckPlaceholderExpr(E);
301 if (result.isInvalid()) return ExprError();
302 E = result.take();
303 }
304
Chris Lattnere7a2e912008-07-25 21:10:04 +0000305 QualType Ty = E->getType();
306 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
307
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000309 E = ImpCastExprToType(E, Context.getPointerType(Ty),
310 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000311 else if (Ty->isArrayType()) {
312 // In C90 mode, arrays only promote to pointers if the array expression is
313 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
314 // type 'array of type' is converted to an expression that has type 'pointer
315 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
316 // that has type 'array of type' ...". The relevant change is "an lvalue"
317 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000318 //
319 // C++ 4.2p1:
320 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
321 // T" can be converted to an rvalue of type "pointer to T".
322 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000323 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000324 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
325 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000326 }
John Wiegley429bb272011-04-08 18:41:53 +0000327 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000328}
329
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000330static void CheckForNullPointerDereference(Sema &S, Expr *E) {
331 // Check to see if we are dereferencing a null pointer. If so,
332 // and if not volatile-qualified, this is undefined behavior that the
333 // optimizer will delete, so warn about it. People sometimes try to use this
334 // to get a deterministic trap and are surprised by clang's behavior. This
335 // only handles the pattern "*null", which is a very syntactic check.
336 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
337 if (UO->getOpcode() == UO_Deref &&
338 UO->getSubExpr()->IgnoreParenCasts()->
339 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
340 !UO->getType().isVolatileQualified()) {
341 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
342 S.PDiag(diag::warn_indirection_through_null)
343 << UO->getSubExpr()->getSourceRange());
344 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
345 S.PDiag(diag::note_indirection_through_null));
346 }
347}
348
John Wiegley429bb272011-04-08 18:41:53 +0000349ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000350 // Handle any placeholder expressions which made it here.
351 if (E->getType()->isPlaceholderType()) {
352 ExprResult result = CheckPlaceholderExpr(E);
353 if (result.isInvalid()) return ExprError();
354 E = result.take();
355 }
356
John McCall0ae287a2010-12-01 04:43:34 +0000357 // C++ [conv.lval]p1:
358 // A glvalue of a non-function, non-array type T can be
359 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000360 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000361
John McCall409fa9a2010-12-06 20:48:59 +0000362 QualType T = E->getType();
363 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000364
Eli Friedmanb001de72011-10-06 23:00:33 +0000365 // We can't do lvalue-to-rvalue on atomics yet.
John McCall3c3b7f92011-10-25 17:37:35 +0000366 if (T->isAtomicType())
Eli Friedmanb001de72011-10-06 23:00:33 +0000367 return Owned(E);
368
John McCall409fa9a2010-12-06 20:48:59 +0000369 // We don't want to throw lvalue-to-rvalue casts on top of
370 // expressions of certain types in C++.
371 if (getLangOptions().CPlusPlus &&
372 (E->getType() == Context.OverloadTy ||
373 T->isDependentType() ||
374 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000375 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000376
377 // The C standard is actually really unclear on this point, and
378 // DR106 tells us what the result should be but not why. It's
379 // generally best to say that void types just doesn't undergo
380 // lvalue-to-rvalue at all. Note that expressions of unqualified
381 // 'void' type are never l-values, but qualified void can be.
382 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000383 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000384
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000385 CheckForNullPointerDereference(*this, E);
386
John McCall409fa9a2010-12-06 20:48:59 +0000387 // C++ [conv.lval]p1:
388 // [...] If T is a non-class type, the type of the prvalue is the
389 // cv-unqualified version of T. Otherwise, the type of the
390 // rvalue is T.
391 //
392 // C99 6.3.2.1p2:
393 // If the lvalue has qualified type, the value has the unqualified
394 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000395 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000396 if (T.hasQualifiers())
397 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000398
399 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
400 E, 0, VK_RValue));
401
402 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000403}
404
John Wiegley429bb272011-04-08 18:41:53 +0000405ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
406 ExprResult Res = DefaultFunctionArrayConversion(E);
407 if (Res.isInvalid())
408 return ExprError();
409 Res = DefaultLvalueConversion(Res.take());
410 if (Res.isInvalid())
411 return ExprError();
412 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000413}
414
415
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000417/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000418/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000419/// apply if the array is an argument to the sizeof or address (&) operators.
420/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000421ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000422 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000423 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
424 if (Res.isInvalid())
425 return Owned(E);
426 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000427
John McCall0ae287a2010-12-01 04:43:34 +0000428 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000429 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000430
431 // Half FP is a bit different: it's a storage-only type, meaning that any
432 // "use" of it should be promoted to float.
433 if (Ty->isHalfType())
434 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
435
John McCall0ae287a2010-12-01 04:43:34 +0000436 // Try to perform integral promotions if the object has a theoretically
437 // promotable type.
438 if (Ty->isIntegralOrUnscopedEnumerationType()) {
439 // C99 6.3.1.1p2:
440 //
441 // The following may be used in an expression wherever an int or
442 // unsigned int may be used:
443 // - an object or expression with an integer type whose integer
444 // conversion rank is less than or equal to the rank of int
445 // and unsigned int.
446 // - A bit-field of type _Bool, int, signed int, or unsigned int.
447 //
448 // If an int can represent all values of the original type, the
449 // value is converted to an int; otherwise, it is converted to an
450 // unsigned int. These are called the integer promotions. All
451 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000452
John McCall0ae287a2010-12-01 04:43:34 +0000453 QualType PTy = Context.isPromotableBitField(E);
454 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000455 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
456 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000457 }
458 if (Ty->isPromotableIntegerType()) {
459 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000460 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
461 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000462 }
Eli Friedman04e83572009-08-20 04:21:42 +0000463 }
John Wiegley429bb272011-04-08 18:41:53 +0000464 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000465}
466
Chris Lattner05faf172008-07-25 22:25:12 +0000467/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000468/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000469/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000470ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
471 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000472 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000473
John Wiegley429bb272011-04-08 18:41:53 +0000474 ExprResult Res = UsualUnaryConversions(E);
475 if (Res.isInvalid())
476 return Owned(E);
477 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000478
Chris Lattner05faf172008-07-25 22:25:12 +0000479 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000480 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000481 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
482
John McCall96a914a2011-08-27 22:06:17 +0000483 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000484 // promotion, even on class types, but note:
485 // C++11 [conv.lval]p2:
486 // When an lvalue-to-rvalue conversion occurs in an unevaluated
487 // operand or a subexpression thereof the value contained in the
488 // referenced object is not accessed. Otherwise, if the glvalue
489 // has a class type, the conversion copy-initializes a temporary
490 // of type T from the glvalue and the result of the conversion
491 // is a prvalue for the temporary.
492 // FIXME: add some way to gate this entire thing for correctness in
493 // potentially potentially evaluated contexts.
John McCall96a914a2011-08-27 22:06:17 +0000494 if (getLangOptions().CPlusPlus && E->isGLValue() &&
495 ExprEvalContexts.back().Context != Unevaluated) {
John McCall5f8d6042011-08-27 01:09:30 +0000496 ExprResult Temp = PerformCopyInitialization(
497 InitializedEntity::InitializeTemporary(E->getType()),
498 E->getExprLoc(),
499 Owned(E));
500 if (Temp.isInvalid())
501 return ExprError();
502 E = Temp.get();
503 }
504
John Wiegley429bb272011-04-08 18:41:53 +0000505 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000506}
507
Chris Lattner312531a2009-04-12 08:11:20 +0000508/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
509/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000510/// interfaces passed by value.
511ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000512 FunctionDecl *FDecl) {
John McCall5acb0c92011-10-17 18:40:02 +0000513 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
514 // Strip the unbridged-cast placeholder expression off, if applicable.
515 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
516 (CT == VariadicMethod ||
517 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
518 E = stripARCUnbridgedCast(E);
519
520 // Otherwise, do normal placeholder checking.
521 } else {
522 ExprResult ExprRes = CheckPlaceholderExpr(E);
523 if (ExprRes.isInvalid())
524 return ExprError();
525 E = ExprRes.take();
526 }
527 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000528
John McCall5acb0c92011-10-17 18:40:02 +0000529 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000530 if (ExprRes.isInvalid())
531 return ExprError();
532 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000534 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000535 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000536 DiagRuntimeBehavior(E->getLocStart(), 0,
537 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
538 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000539 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000540
Douglas Gregorb8e778d2011-10-14 20:34:19 +0000541 // Complain about passing non-POD types through varargs. However, don't
542 // perform this check for incomplete types, which we can get here when we're
543 // in an unevaluated context.
544 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000545 // C++0x [expr.call]p7:
546 // Passing a potentially-evaluated argument of class type (Clause 9)
547 // having a non-trivial copy constructor, a non-trivial move constructor,
548 // or a non-trivial destructor, with no corresponding parameter,
549 // is conditionally-supported with implementation-defined semantics.
550 bool TrivialEnough = false;
551 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
552 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
553 if (Record->hasTrivialCopyConstructor() &&
554 Record->hasTrivialMoveConstructor() &&
Richard Smithebaf0e62011-10-18 20:49:44 +0000555 Record->hasTrivialDestructor()) {
556 DiagRuntimeBehavior(E->getLocStart(), 0,
557 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
558 << E->getType() << CT);
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000559 TrivialEnough = true;
Richard Smithebaf0e62011-10-18 20:49:44 +0000560 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000561 }
562 }
John McCallf85e1932011-06-15 23:02:42 +0000563
564 if (!TrivialEnough &&
565 getLangOptions().ObjCAutoRefCount &&
566 E->getType()->isObjCLifetimeType())
567 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000568
569 if (TrivialEnough) {
570 // Nothing to diagnose. This is okay.
571 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000572 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000573 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000574 << CT)) {
575 // Turn this into a trap.
576 CXXScopeSpec SS;
577 UnqualifiedId Name;
578 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
579 E->getLocStart());
580 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
581 if (TrapFn.isInvalid())
582 return ExprError();
583
584 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
585 MultiExprArg(), E->getLocEnd());
586 if (Call.isInvalid())
587 return ExprError();
588
589 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
590 Call.get(), E);
591 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000592 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000593 E = Comma.get();
594 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000595 }
596
John Wiegley429bb272011-04-08 18:41:53 +0000597 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000598}
599
Richard Trieu8289f492011-09-02 20:58:51 +0000600/// \brief Converts an integer to complex float type. Helper function of
601/// UsualArithmeticConversions()
602///
603/// \return false if the integer expression is an integer type and is
604/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000605static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
606 ExprResult &ComplexExpr,
607 QualType IntTy,
608 QualType ComplexTy,
609 bool SkipCast) {
610 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
611 if (SkipCast) return false;
612 if (IntTy->isIntegerType()) {
613 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
614 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
615 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000616 CK_FloatingRealToComplex);
617 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000618 assert(IntTy->isComplexIntegerType());
619 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000620 CK_IntegralComplexToFloatingComplex);
621 }
622 return false;
623}
624
625/// \brief Takes two complex float types and converts them to the same type.
626/// Helper function of UsualArithmeticConversions()
627static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000628handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
629 ExprResult &RHS, QualType LHSType,
630 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000631 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000632 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000633
634 if (order < 0) {
635 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000636 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000637 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
638 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000639 }
640 if (order > 0)
641 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000642 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
643 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000644}
645
646/// \brief Converts otherExpr to complex float and promotes complexExpr if
647/// necessary. Helper function of UsualArithmeticConversions()
648static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000649 ExprResult &ComplexExpr,
650 ExprResult &OtherExpr,
651 QualType ComplexTy,
652 QualType OtherTy,
653 bool ConvertComplexExpr,
654 bool ConvertOtherExpr) {
655 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000656
657 // If just the complexExpr is complex, the otherExpr needs to be converted,
658 // and the complexExpr might need to be promoted.
659 if (order > 0) { // complexExpr is wider
660 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000661 if (ConvertOtherExpr) {
662 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
663 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
664 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000665 CK_FloatingRealToComplex);
666 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000667 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000668 }
669
670 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000671 QualType result = (order == 0 ? ComplexTy :
672 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000673
674 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000675 if (ConvertOtherExpr)
676 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000677 CK_FloatingRealToComplex);
678
679 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000680 if (ConvertComplexExpr && order < 0)
681 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000682 CK_FloatingComplexCast);
683
684 return result;
685}
686
687/// \brief Handle arithmetic conversion with complex types. Helper function of
688/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000689static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
690 ExprResult &RHS, QualType LHSType,
691 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000692 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000693 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000694 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000695 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000696 return LHSType;
697 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000698 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000699 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000700
701 // This handles complex/complex, complex/float, or float/complex.
702 // When both operands are complex, the shorter operand is converted to the
703 // type of the longer, and that is the type of the result. This corresponds
704 // to what is done when combining two real floating-point operands.
705 // The fun begins when size promotion occur across type domains.
706 // From H&S 6.3.4: When one operand is complex and the other is a real
707 // floating-point type, the less precise type is converted, within it's
708 // real or complex domain, to the precision of the other type. For example,
709 // when combining a "long double" with a "double _Complex", the
710 // "double _Complex" is promoted to "long double _Complex".
711
Richard Trieucafd30b2011-09-06 18:25:09 +0000712 bool LHSComplexFloat = LHSType->isComplexType();
713 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000714
715 // If both are complex, just cast to the more precise type.
716 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000717 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
718 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000719 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000720
721 // If only one operand is complex, promote it if necessary and convert the
722 // other operand to complex.
723 if (LHSComplexFloat)
724 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000725 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000726 /*convertOtherExpr*/ true);
727
728 assert(RHSComplexFloat);
729 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000730 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000731 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000732}
733
734/// \brief Hande arithmetic conversion from integer to float. Helper function
735/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000736static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
737 ExprResult &IntExpr,
738 QualType FloatTy, QualType IntTy,
739 bool ConvertFloat, bool ConvertInt) {
740 if (IntTy->isIntegerType()) {
741 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000742 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000743 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000744 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000745 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000746 }
747
748 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000749 assert(IntTy->isComplexIntegerType());
750 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000751
752 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000753 if (ConvertInt)
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000755 CK_IntegralComplexToFloatingComplex);
756
757 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000758 if (ConvertFloat)
759 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000760 CK_FloatingRealToComplex);
761
762 return result;
763}
764
765/// \brief Handle arithmethic conversion with floating point types. Helper
766/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000767static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
768 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000769 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000770 bool LHSFloat = LHSType->isRealFloatingType();
771 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000772
773 // If we have two real floating types, convert the smaller operand
774 // to the bigger result.
775 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000776 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000777 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000778 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
779 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000780 }
781
782 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000783 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000784 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
785 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000786 }
787
788 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000789 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000790 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000791 /*convertInt=*/ true);
792 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000793 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000794 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000795 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000796}
797
798/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000799/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000800// FIXME: if the operands are (int, _Complex long), we currently
801// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000802static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
803 ExprResult &RHS, QualType LHSType,
804 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000805 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000806 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
807 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000808
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000809 if (LHSComplexInt && RHSComplexInt) {
810 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
811 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000812 assert(order && "inequal types with equal element ordering");
813 if (order > 0) {
814 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000815 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
816 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000817 }
818
Richard Trieuccd891a2011-09-09 01:45:06 +0000819 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000820 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
821 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000822 }
823
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000824 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000825 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000826 // FIXME: This needs to take integer ranks into account
827 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
828 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000829 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
830 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000831 }
832
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000833 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000834 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000835 // FIXME: This needs to take integer ranks into account
836 if (!IsCompAssign) {
837 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
838 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000839 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000840 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000841 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000842}
843
844/// \brief Handle integer arithmetic conversions. Helper function of
845/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000846static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
847 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000848 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000849 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000850 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
851 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
852 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
853 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000854 // Same signedness; use the higher-ranked type
855 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000856 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
857 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000858 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000859 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
860 return RHSType;
861 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000862 // The unsigned type has greater than or equal rank to the
863 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000864 if (RHSSigned) {
865 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
866 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000868 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
869 return RHSType;
870 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000871 // The two types are different widths; if we are here, that
872 // means the signed type is larger than the unsigned type, so
873 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000874 if (LHSSigned) {
875 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
876 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000877 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
879 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000880 } else {
881 // The signed type is higher-ranked than the unsigned type,
882 // but isn't actually any bigger (like unsigned int and long
883 // on most 32-bit systems). Use the unsigned type corresponding
884 // to the signed type.
885 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000886 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
887 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000889 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +0000890 return result;
891 }
892}
893
Chris Lattnere7a2e912008-07-25 21:10:04 +0000894/// UsualArithmeticConversions - Performs various conversions that are common to
895/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000896/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000897/// responsible for emitting appropriate error diagnostics.
898/// FIXME: verify the conversion rules for "complex int" are consistent with
899/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000900QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 bool IsCompAssign) {
902 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000903 LHS = UsualUnaryConversions(LHS.take());
904 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000905 return QualType();
906 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000907
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000908 RHS = UsualUnaryConversions(RHS.take());
909 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000910 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000911
Mike Stump1eb44332009-09-09 15:08:12 +0000912 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000913 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000914 QualType LHSType =
915 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
916 QualType RHSType =
917 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000918
919 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000920 if (LHSType == RHSType)
921 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000922
923 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
924 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000925 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
926 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000927
John McCallcf33b242010-11-13 08:17:45 +0000928 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000929 QualType LHSUnpromotedType = LHSType;
930 if (LHSType->isPromotableIntegerType())
931 LHSType = Context.getPromotedIntegerType(LHSType);
932 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000933 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000934 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +0000935 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000936 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000937
John McCallcf33b242010-11-13 08:17:45 +0000938 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000939 if (LHSType == RHSType)
940 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +0000941
942 // At this point, we have two different arithmetic types.
943
944 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000945 if (LHSType->isComplexType() || RHSType->isComplexType())
946 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000947 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000948
949 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000950 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
951 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000952 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000953
954 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000955 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000956 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000957 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +0000958
959 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000960 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000961 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000962}
963
Chris Lattnere7a2e912008-07-25 21:10:04 +0000964//===----------------------------------------------------------------------===//
965// Semantic Analysis for various Expression Types
966//===----------------------------------------------------------------------===//
967
968
Peter Collingbournef111d932011-04-15 00:35:48 +0000969ExprResult
970Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
971 SourceLocation DefaultLoc,
972 SourceLocation RParenLoc,
973 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +0000974 MultiTypeArg ArgTypes,
975 MultiExprArg ArgExprs) {
976 unsigned NumAssocs = ArgTypes.size();
977 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +0000978
Richard Trieuccd891a2011-09-09 01:45:06 +0000979 ParsedType *ParsedTypes = ArgTypes.release();
980 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +0000981
982 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
983 for (unsigned i = 0; i < NumAssocs; ++i) {
984 if (ParsedTypes[i])
985 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
986 else
987 Types[i] = 0;
988 }
989
990 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
991 ControllingExpr, Types, Exprs,
992 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000993 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000994 return ER;
995}
996
997ExprResult
998Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
999 SourceLocation DefaultLoc,
1000 SourceLocation RParenLoc,
1001 Expr *ControllingExpr,
1002 TypeSourceInfo **Types,
1003 Expr **Exprs,
1004 unsigned NumAssocs) {
1005 bool TypeErrorFound = false,
1006 IsResultDependent = ControllingExpr->isTypeDependent(),
1007 ContainsUnexpandedParameterPack
1008 = ControllingExpr->containsUnexpandedParameterPack();
1009
1010 for (unsigned i = 0; i < NumAssocs; ++i) {
1011 if (Exprs[i]->containsUnexpandedParameterPack())
1012 ContainsUnexpandedParameterPack = true;
1013
1014 if (Types[i]) {
1015 if (Types[i]->getType()->containsUnexpandedParameterPack())
1016 ContainsUnexpandedParameterPack = true;
1017
1018 if (Types[i]->getType()->isDependentType()) {
1019 IsResultDependent = true;
1020 } else {
1021 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1022 // complete object type other than a variably modified type."
1023 unsigned D = 0;
1024 if (Types[i]->getType()->isIncompleteType())
1025 D = diag::err_assoc_type_incomplete;
1026 else if (!Types[i]->getType()->isObjectType())
1027 D = diag::err_assoc_type_nonobject;
1028 else if (Types[i]->getType()->isVariablyModifiedType())
1029 D = diag::err_assoc_type_variably_modified;
1030
1031 if (D != 0) {
1032 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1033 << Types[i]->getTypeLoc().getSourceRange()
1034 << Types[i]->getType();
1035 TypeErrorFound = true;
1036 }
1037
1038 // C1X 6.5.1.1p2 "No two generic associations in the same generic
1039 // selection shall specify compatible types."
1040 for (unsigned j = i+1; j < NumAssocs; ++j)
1041 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1042 Context.typesAreCompatible(Types[i]->getType(),
1043 Types[j]->getType())) {
1044 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1045 diag::err_assoc_compatible_types)
1046 << Types[j]->getTypeLoc().getSourceRange()
1047 << Types[j]->getType()
1048 << Types[i]->getType();
1049 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1050 diag::note_compat_assoc)
1051 << Types[i]->getTypeLoc().getSourceRange()
1052 << Types[i]->getType();
1053 TypeErrorFound = true;
1054 }
1055 }
1056 }
1057 }
1058 if (TypeErrorFound)
1059 return ExprError();
1060
1061 // If we determined that the generic selection is result-dependent, don't
1062 // try to compute the result expression.
1063 if (IsResultDependent)
1064 return Owned(new (Context) GenericSelectionExpr(
1065 Context, KeyLoc, ControllingExpr,
1066 Types, Exprs, NumAssocs, DefaultLoc,
1067 RParenLoc, ContainsUnexpandedParameterPack));
1068
Chris Lattner5f9e2722011-07-23 10:55:15 +00001069 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001070 unsigned DefaultIndex = -1U;
1071 for (unsigned i = 0; i < NumAssocs; ++i) {
1072 if (!Types[i])
1073 DefaultIndex = i;
1074 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1075 Types[i]->getType()))
1076 CompatIndices.push_back(i);
1077 }
1078
1079 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1080 // type compatible with at most one of the types named in its generic
1081 // association list."
1082 if (CompatIndices.size() > 1) {
1083 // We strip parens here because the controlling expression is typically
1084 // parenthesized in macro definitions.
1085 ControllingExpr = ControllingExpr->IgnoreParens();
1086 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1087 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1088 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001089 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001090 E = CompatIndices.end(); I != E; ++I) {
1091 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1092 diag::note_compat_assoc)
1093 << Types[*I]->getTypeLoc().getSourceRange()
1094 << Types[*I]->getType();
1095 }
1096 return ExprError();
1097 }
1098
1099 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1100 // its controlling expression shall have type compatible with exactly one of
1101 // the types named in its generic association list."
1102 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1103 // We strip parens here because the controlling expression is typically
1104 // parenthesized in macro definitions.
1105 ControllingExpr = ControllingExpr->IgnoreParens();
1106 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1107 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1108 return ExprError();
1109 }
1110
1111 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1112 // type name that is compatible with the type of the controlling expression,
1113 // then the result expression of the generic selection is the expression
1114 // in that generic association. Otherwise, the result expression of the
1115 // generic selection is the expression in the default generic association."
1116 unsigned ResultIndex =
1117 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1118
1119 return Owned(new (Context) GenericSelectionExpr(
1120 Context, KeyLoc, ControllingExpr,
1121 Types, Exprs, NumAssocs, DefaultLoc,
1122 RParenLoc, ContainsUnexpandedParameterPack,
1123 ResultIndex));
1124}
1125
Steve Narofff69936d2007-09-16 03:34:24 +00001126/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001127/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1128/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1129/// multiple tokens. However, the common case is that StringToks points to one
1130/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001131///
John McCall60d7b3a2010-08-24 06:29:42 +00001132ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001133Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 assert(NumStringToks && "Must have at least one string!");
1135
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001136 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001138 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001139
Chris Lattner5f9e2722011-07-23 10:55:15 +00001140 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 for (unsigned i = 0; i != NumStringToks; ++i)
1142 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001143
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001144 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001145 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001146 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001147 else if (Literal.isUTF16())
1148 StrTy = Context.Char16Ty;
1149 else if (Literal.isUTF32())
1150 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001151 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001152 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001153
Douglas Gregor5cee1192011-07-27 05:40:30 +00001154 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1155 if (Literal.isWide())
1156 Kind = StringLiteral::Wide;
1157 else if (Literal.isUTF8())
1158 Kind = StringLiteral::UTF8;
1159 else if (Literal.isUTF16())
1160 Kind = StringLiteral::UTF16;
1161 else if (Literal.isUTF32())
1162 Kind = StringLiteral::UTF32;
1163
Douglas Gregor77a52232008-09-12 00:47:35 +00001164 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001165 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001166 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001167
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001168 // Get an array type for the string, according to C99 6.4.5. This includes
1169 // the nul terminator character as well as the string length for pascal
1170 // strings.
1171 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001172 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001173 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001176 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001177 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001178 &StringTokLocs[0],
1179 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001180}
1181
John McCall469a1eb2011-02-02 13:00:07 +00001182enum CaptureResult {
1183 /// No capture is required.
1184 CR_NoCapture,
1185
1186 /// A capture is required.
1187 CR_Capture,
1188
John McCall6b5a61b2011-02-07 10:33:21 +00001189 /// A by-ref capture is required.
1190 CR_CaptureByRef,
1191
John McCall469a1eb2011-02-02 13:00:07 +00001192 /// An error occurred when trying to capture the given variable.
1193 CR_Error
1194};
1195
1196/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001197///
John McCall469a1eb2011-02-02 13:00:07 +00001198/// \param var - the variable referenced
1199/// \param DC - the context which we couldn't capture through
1200static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001201diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001202 VarDecl *var, DeclContext *DC) {
1203 switch (S.ExprEvalContexts.back().Context) {
1204 case Sema::Unevaluated:
1205 // The argument will never be evaluated, so don't complain.
1206 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
John McCall469a1eb2011-02-02 13:00:07 +00001208 case Sema::PotentiallyEvaluated:
1209 case Sema::PotentiallyEvaluatedIfUsed:
1210 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001211
John McCall469a1eb2011-02-02 13:00:07 +00001212 case Sema::PotentiallyPotentiallyEvaluated:
1213 // FIXME: delay these!
1214 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
John McCall469a1eb2011-02-02 13:00:07 +00001217 // Don't diagnose about capture if we're not actually in code right
1218 // now; in general, there are more appropriate places that will
1219 // diagnose this.
1220 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1221
John McCall4f38f412011-03-22 23:15:50 +00001222 // Certain madnesses can happen with parameter declarations, which
1223 // we want to ignore.
1224 if (isa<ParmVarDecl>(var)) {
1225 // - If the parameter still belongs to the translation unit, then
1226 // we're actually just using one parameter in the declaration of
1227 // the next. This is useful in e.g. VLAs.
1228 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1229 return CR_NoCapture;
1230
1231 // - This particular madness can happen in ill-formed default
1232 // arguments; claim it's okay and let downstream code handle it.
1233 if (S.CurContext == var->getDeclContext()->getParent())
1234 return CR_NoCapture;
1235 }
John McCall469a1eb2011-02-02 13:00:07 +00001236
1237 DeclarationName functionName;
1238 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1239 functionName = fn->getDeclName();
1240 // FIXME: variable from enclosing block that we couldn't capture from!
1241
1242 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1243 << var->getIdentifier() << functionName;
1244 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1245 << var->getIdentifier();
1246
1247 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001248}
1249
John McCall6b5a61b2011-02-07 10:33:21 +00001250/// There is a well-formed capture at a particular scope level;
1251/// propagate it through all the nested blocks.
Richard Trieuccd891a2011-09-09 01:45:06 +00001252static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1253 const BlockDecl::Capture &Capture) {
1254 VarDecl *var = Capture.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001255
1256 // Update all the inner blocks with the capture information.
Richard Trieuccd891a2011-09-09 01:45:06 +00001257 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall6b5a61b2011-02-07 10:33:21 +00001258 i != e; ++i) {
1259 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1260 innerBlock->Captures.push_back(
Richard Trieuccd891a2011-09-09 01:45:06 +00001261 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1262 /*nested*/ true, Capture.getCopyExpr()));
John McCall6b5a61b2011-02-07 10:33:21 +00001263 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1264 }
1265
Richard Trieuccd891a2011-09-09 01:45:06 +00001266 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall6b5a61b2011-02-07 10:33:21 +00001267}
1268
1269/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001270/// given value in the current context requires a variable capture.
1271///
1272/// This also keeps the captures set in the BlockScopeInfo records
1273/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001274static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00001275 ValueDecl *Value) {
John McCall469a1eb2011-02-02 13:00:07 +00001276 // Only variables ever require capture.
Richard Trieuccd891a2011-09-09 01:45:06 +00001277 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCall76a40212011-02-09 01:13:10 +00001278 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001279
1280 // Fast path: variables from the current context never require capture.
1281 DeclContext *DC = S.CurContext;
1282 if (var->getDeclContext() == DC) return CR_NoCapture;
1283
1284 // Only variables with local storage require capture.
1285 // FIXME: What about 'const' variables in C++?
1286 if (!var->hasLocalStorage()) return CR_NoCapture;
1287
1288 // Otherwise, we need to capture.
1289
1290 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001291 do {
1292 // Only blocks (and eventually C++0x closures) can capture; other
1293 // scopes don't work.
1294 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001295 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001296
1297 BlockScopeInfo *blockScope =
1298 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1299 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1300
John McCall6b5a61b2011-02-07 10:33:21 +00001301 // Check whether we've already captured it in this block. If so,
1302 // we're done.
1303 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1304 return propagateCapture(S, functionScopesIndex,
1305 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001306
1307 functionScopesIndex--;
1308 DC = cast<BlockDecl>(DC)->getDeclContext();
1309 } while (var->getDeclContext() != DC);
1310
John McCall6b5a61b2011-02-07 10:33:21 +00001311 // Okay, we descended all the way to the block that defines the variable.
1312 // Actually try to capture it.
1313 QualType type = var->getType();
Fariborz Jahanian05053212011-11-01 18:57:34 +00001314
John McCall6b5a61b2011-02-07 10:33:21 +00001315 // Prohibit variably-modified types.
1316 if (type->isVariablyModifiedType()) {
1317 S.Diag(loc, diag::err_ref_vm_type);
1318 S.Diag(var->getLocation(), diag::note_declared_at);
1319 return CR_Error;
1320 }
1321
1322 // Prohibit arrays, even in __block variables, but not references to
1323 // them.
1324 if (type->isArrayType()) {
1325 S.Diag(loc, diag::err_ref_array_type);
1326 S.Diag(var->getLocation(), diag::note_declared_at);
1327 return CR_Error;
1328 }
1329
1330 S.MarkDeclarationReferenced(loc, var);
1331
1332 // The BlocksAttr indicates the variable is bound by-reference.
1333 bool byRef = var->hasAttr<BlocksAttr>();
1334
1335 // Build a copy expression.
1336 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001337 const RecordType *rtype;
1338 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1339 (rtype = type->getAs<RecordType>())) {
1340
1341 // The capture logic needs the destructor, so make sure we mark it.
1342 // Usually this is unnecessary because most local variables have
1343 // their destructors marked at declaration time, but parameters are
1344 // an exception because it's technically only the call site that
1345 // actually requires the destructor.
1346 if (isa<ParmVarDecl>(var))
1347 S.FinalizeVarWithDestructor(var, rtype);
1348
John McCall6b5a61b2011-02-07 10:33:21 +00001349 // According to the blocks spec, the capture of a variable from
1350 // the stack requires a const copy constructor. This is not true
1351 // of the copy/move done to move a __block variable to the heap.
1352 type.addConst();
1353
1354 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1355 ExprResult result =
1356 S.PerformCopyInitialization(
1357 InitializedEntity::InitializeBlock(var->getLocation(),
1358 type, false),
1359 loc, S.Owned(declRef));
1360
1361 // Build a full-expression copy expression if initialization
1362 // succeeded and used a non-trivial constructor. Recover from
1363 // errors by pretending that the copy isn't necessary.
1364 if (!result.isInvalid() &&
1365 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1366 result = S.MaybeCreateExprWithCleanups(result);
1367 copyExpr = result.take();
1368 }
1369 }
1370
1371 // We're currently at the declarer; go back to the closure.
1372 functionScopesIndex++;
1373 BlockScopeInfo *blockScope =
1374 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1375
1376 // Build a valid capture in this scope.
1377 blockScope->Captures.push_back(
1378 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1379 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1380
1381 // Propagate that to inner captures if necessary.
1382 return propagateCapture(S, functionScopesIndex,
1383 blockScope->Captures.back());
1384}
1385
Richard Trieuccd891a2011-09-09 01:45:06 +00001386static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall6b5a61b2011-02-07 10:33:21 +00001387 const DeclarationNameInfo &NameInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00001388 bool ByRef) {
1389 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall6b5a61b2011-02-07 10:33:21 +00001390
Richard Trieuccd891a2011-09-09 01:45:06 +00001391 VarDecl *var = cast<VarDecl>(VD);
John McCall6b5a61b2011-02-07 10:33:21 +00001392 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuccd891a2011-09-09 01:45:06 +00001393 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall6b5a61b2011-02-07 10:33:21 +00001394
1395 QualType exprType = var->getType().getNonReferenceType();
1396
1397 BlockDeclRefExpr *BDRE;
Richard Trieuccd891a2011-09-09 01:45:06 +00001398 if (!ByRef) {
John McCall6b5a61b2011-02-07 10:33:21 +00001399 // The variable will be bound by copy; make it const within the
1400 // closure, but record that this was done in the expression.
1401 bool constAdded = !exprType.isConstQualified();
1402 exprType.addConst();
1403
1404 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1405 NameInfo.getLoc(), false,
1406 constAdded);
1407 } else {
1408 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1409 NameInfo.getLoc(), true);
1410 }
1411
1412 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001413}
Chris Lattner639e2d32008-10-20 05:16:36 +00001414
John McCall60d7b3a2010-08-24 06:29:42 +00001415ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001416Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001417 SourceLocation Loc,
1418 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001419 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001420 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001421}
1422
John McCall76a40212011-02-09 01:13:10 +00001423/// BuildDeclRefExpr - Build an expression that references a
1424/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001425ExprResult
John McCall76a40212011-02-09 01:13:10 +00001426Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001427 const DeclarationNameInfo &NameInfo,
1428 const CXXScopeSpec *SS) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001429 if (getLangOptions().CUDA)
1430 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1431 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1432 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1433 CalleeTarget = IdentifyCUDATarget(Callee);
1434 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1435 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1436 << CalleeTarget << D->getIdentifier() << CallerTarget;
1437 Diag(D->getLocation(), diag::note_previous_decl)
1438 << D->getIdentifier();
1439 return ExprError();
1440 }
1441 }
1442
Abramo Bagnara25777432010-08-11 22:01:17 +00001443 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
John McCall7eb0a9e2010-11-24 05:12:34 +00001445 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001446 SS? SS->getWithLocInContext(Context)
1447 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001448 D, NameInfo, Ty, VK);
1449
1450 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001451 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1452 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001453 E->setObjectKind(OK_BitField);
1454
1455 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001456}
1457
Abramo Bagnara25777432010-08-11 22:01:17 +00001458/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001459/// possibly a list of template arguments.
1460///
1461/// If this produces template arguments, it is permitted to call
1462/// DecomposeTemplateName.
1463///
1464/// This actually loses a lot of source location information for
1465/// non-standard name kinds; we should consider preserving that in
1466/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001467void
1468Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1469 TemplateArgumentListInfo &Buffer,
1470 DeclarationNameInfo &NameInfo,
1471 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001472 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1473 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1474 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1475
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001477 Id.TemplateId->getTemplateArgs(),
1478 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001479 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001480 TemplateArgsPtr.release();
1481
John McCall2b5289b2010-08-23 07:28:44 +00001482 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001483 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001484 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001485 TemplateArgs = &Buffer;
1486 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001487 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001488 TemplateArgs = 0;
1489 }
1490}
1491
John McCall578b69b2009-12-16 08:11:27 +00001492/// Diagnose an empty lookup.
1493///
1494/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001495bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001496 CorrectTypoContext CTC,
1497 TemplateArgumentListInfo *ExplicitTemplateArgs,
1498 Expr **Args, unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001499 DeclarationName Name = R.getLookupName();
1500
John McCall578b69b2009-12-16 08:11:27 +00001501 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001502 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001503 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1504 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001505 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001506 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001507 diagnostic_suggest = diag::err_undeclared_use_suggest;
1508 }
John McCall578b69b2009-12-16 08:11:27 +00001509
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001510 // If the original lookup was an unqualified lookup, fake an
1511 // unqualified lookup. This is useful when (for example) the
1512 // original lookup would not have found something because it was a
1513 // dependent name.
Francois Pichetc8ff9152011-11-25 01:10:54 +00001514 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1515 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001516 if (isa<CXXRecordDecl>(DC)) {
1517 LookupQualifiedName(R, DC);
1518
1519 if (!R.empty()) {
1520 // Don't give errors about ambiguities in this lookup.
1521 R.suppressDiagnostics();
1522
Francois Pichete6226ae2011-11-17 03:44:24 +00001523 // During a default argument instantiation the CurContext points
1524 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1525 // function parameter list, hence add an explicit check.
1526 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1527 ActiveTemplateInstantiations.back().Kind ==
1528 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001529 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1530 bool isInstance = CurMethod &&
1531 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001532 DC == CurMethod->getParent() && !isDefaultArgument;
1533
John McCall578b69b2009-12-16 08:11:27 +00001534
1535 // Give a code modification hint to insert 'this->'.
1536 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1537 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001538 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001539 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1540 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001541 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001542 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001543 if (DepMethod) {
Francois Pichete614d6c2011-11-15 23:33:34 +00001544 if (getLangOptions().MicrosoftMode)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001545 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001546 Diag(R.getNameLoc(), diagnostic) << Name
1547 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1548 QualType DepThisType = DepMethod->getThisType(Context);
1549 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550 R.getNameLoc(), DepThisType, false);
1551 TemplateArgumentListInfo TList;
1552 if (ULE->hasExplicitTemplateArgs())
1553 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001554
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001555 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001556 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001557 CXXDependentScopeMemberExpr *DepExpr =
1558 CXXDependentScopeMemberExpr::Create(
1559 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001560 SS.getWithLocInContext(Context), NULL,
Francois Pichetf7400122011-09-04 23:00:48 +00001561 R.getLookupNameInfo(),
1562 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001563 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001564 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001565 // FIXME: we should be able to handle this case too. It is correct
1566 // to add this-> here. This is a workaround for PR7947.
1567 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001568 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001569 } else {
Francois Pichete614d6c2011-11-15 23:33:34 +00001570 if (getLangOptions().MicrosoftMode)
1571 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCall578b69b2009-12-16 08:11:27 +00001572 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001573 }
John McCall578b69b2009-12-16 08:11:27 +00001574
1575 // Do we really want to note all of these?
1576 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1577 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1578
Francois Pichete6226ae2011-11-17 03:44:24 +00001579 // Return true if we are inside a default argument instantiation
1580 // and the found name refers to an instance member function, otherwise
1581 // the function calling DiagnoseEmptyLookup will try to create an
1582 // implicit member call and this is wrong for default argument.
1583 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1584 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1585 return true;
1586 }
1587
John McCall578b69b2009-12-16 08:11:27 +00001588 // Tell the callee to try to recover.
1589 return false;
1590 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001591
1592 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001593 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001594
1595 // In Microsoft mode, if we are performing lookup from within a friend
1596 // function definition declared at class scope then we must set
1597 // DC to the lexical parent to be able to search into the parent
1598 // class.
1599 if (getLangOptions().MicrosoftMode && DC->isFunctionOrMethod() &&
1600 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1601 DC->getLexicalParent()->isRecord())
1602 DC = DC->getLexicalParent();
1603 else
1604 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001605 }
1606
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001607 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001608 TypoCorrection Corrected;
1609 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1610 S, &SS, NULL, false, CTC))) {
1611 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1612 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1613 R.setLookupName(Corrected.getCorrection());
1614
Hans Wennborg701d1e72011-07-12 08:45:31 +00001615 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001616 if (Corrected.isOverloaded()) {
1617 OverloadCandidateSet OCS(R.getNameLoc());
1618 OverloadCandidateSet::iterator Best;
1619 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1620 CDEnd = Corrected.end();
1621 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001622 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001623 dyn_cast<FunctionTemplateDecl>(*CD))
1624 AddTemplateOverloadCandidate(
1625 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1626 Args, NumArgs, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001627 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1628 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1629 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1630 Args, NumArgs, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001631 }
1632 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1633 case OR_Success:
1634 ND = Best->Function;
1635 break;
1636 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001637 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001638 }
1639 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001640 R.addDecl(ND);
1641 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001643 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1644 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001645 else
1646 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001647 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001648 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001649 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1650 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001651 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001652 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001653
1654 // Tell the callee to try to recover.
1655 return false;
1656 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001657
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001658 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001659 // FIXME: If we ended up with a typo for a type name or
1660 // Objective-C class name, we're in trouble because the parser
1661 // is in the wrong place to recover. Suggest the typo
1662 // correction, but don't make it a fix-it since we're not going
1663 // to recover well anyway.
1664 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001665 Diag(R.getNameLoc(), diagnostic_suggest)
1666 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001667 else
1668 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001669 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001670 << SS.getRange();
1671
1672 // Don't try to recover; it won't work.
1673 return true;
1674 }
1675 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001676 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001677 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001678 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001679 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001680 else
Douglas Gregord203a162010-01-01 00:15:04 +00001681 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001682 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001683 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001684 return true;
1685 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001686 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001687 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001688
1689 // Emit a special diagnostic for failed member lookups.
1690 // FIXME: computing the declaration context might fail here (?)
1691 if (!SS.isEmpty()) {
1692 Diag(R.getNameLoc(), diag::err_no_member)
1693 << Name << computeDeclContext(SS, false)
1694 << SS.getRange();
1695 return true;
1696 }
1697
John McCall578b69b2009-12-16 08:11:27 +00001698 // Give up, we can't recover.
1699 Diag(R.getNameLoc(), diagnostic) << Name;
1700 return true;
1701}
1702
John McCall60d7b3a2010-08-24 06:29:42 +00001703ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001704 CXXScopeSpec &SS,
1705 UnqualifiedId &Id,
1706 bool HasTrailingLParen,
Richard Trieuccd891a2011-09-09 01:45:06 +00001707 bool IsAddressOfOperand) {
1708 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001709 "cannot be direct & operand and have a trailing lparen");
1710
1711 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001712 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001713
John McCall129e2df2009-11-30 22:42:35 +00001714 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001715
1716 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001717 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001718 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001719 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001720
Abramo Bagnara25777432010-08-11 22:01:17 +00001721 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001722 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001723 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001724
John McCallf7a1a742009-11-24 19:00:30 +00001725 // C++ [temp.dep.expr]p3:
1726 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001727 // -- an identifier that was declared with a dependent type,
1728 // (note: handled after lookup)
1729 // -- a template-id that is dependent,
1730 // (note: handled in BuildTemplateIdExpr)
1731 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001732 // -- a nested-name-specifier that contains a class-name that
1733 // names a dependent type.
1734 // Determine whether this is a member of an unknown specialization;
1735 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001736 bool DependentID = false;
1737 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1738 Name.getCXXNameType()->isDependentType()) {
1739 DependentID = true;
1740 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001741 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001742 if (RequireCompleteDeclContext(SS, DC))
1743 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001744 } else {
1745 DependentID = true;
1746 }
1747 }
1748
Chris Lattner337e5502011-02-18 01:27:55 +00001749 if (DependentID)
Richard Trieuccd891a2011-09-09 01:45:06 +00001750 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001751 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001752
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001753 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001754 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001755 LookupResult R(*this, NameInfo,
1756 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1757 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001758 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001759 // Lookup the template name again to correctly establish the context in
1760 // which it was found. This is really unfortunate as we already did the
1761 // lookup to determine that it was a template name in the first place. If
1762 // this becomes a performance hit, we can work harder to preserve those
1763 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001764 bool MemberOfUnknownSpecialization;
1765 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1766 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001767
1768 if (MemberOfUnknownSpecialization ||
1769 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuccd891a2011-09-09 01:45:06 +00001770 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001771 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001772 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001773 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001774 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001776 // If the result might be in a dependent base class, this is a dependent
1777 // id-expression.
1778 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuccd891a2011-09-09 01:45:06 +00001779 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001780 TemplateArgs);
1781
John McCallf7a1a742009-11-24 19:00:30 +00001782 // If this reference is in an Objective-C method, then we need to do
1783 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001784 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001785 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001786 if (E.isInvalid())
1787 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Chris Lattner337e5502011-02-18 01:27:55 +00001789 if (Expr *Ex = E.takeAs<Expr>())
1790 return Owned(Ex);
1791
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001792 // for further use, this must be set to false if in class method.
1793 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001794 }
Chris Lattner8a934232008-03-31 00:36:02 +00001795 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001796
John McCallf7a1a742009-11-24 19:00:30 +00001797 if (R.isAmbiguous())
1798 return ExprError();
1799
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001800 // Determine whether this name might be a candidate for
1801 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001802 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001803
John McCallf7a1a742009-11-24 19:00:30 +00001804 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001806 // in C90, extension in C99, forbidden in C++).
1807 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1808 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1809 if (D) R.addDecl(D);
1810 }
1811
1812 // If this name wasn't predeclared and if this is not a function
1813 // call, diagnose the problem.
1814 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001815
1816 // In Microsoft mode, if we are inside a template class member function
1817 // and we can't resolve an identifier then assume the identifier is type
1818 // dependent. The goal is to postpone name lookup to instantiation time
1819 // to be able to search into type dependent base classes.
1820 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1821 isa<CXXMethodDecl>(CurContext))
1822 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1823 TemplateArgs);
1824
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001825 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001826 return ExprError();
1827
1828 assert(!R.empty() &&
1829 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001830
1831 // If we found an Objective-C instance variable, let
1832 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001833 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001834 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1835 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001836 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001837 // In a hopelessly buggy code, Objective-C instance variable
1838 // lookup fails and no expression will be built to reference it.
1839 if (!E.isInvalid() && !E.get())
1840 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001841 return move(E);
1842 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 }
1844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
John McCallf7a1a742009-11-24 19:00:30 +00001846 // This is guaranteed from this point on.
1847 assert(!R.empty() || ADL);
1848
John McCallaa81e162009-12-01 22:10:20 +00001849 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001850 // C++ [class.mfct.non-static]p3:
1851 // When an id-expression that is not part of a class member access
1852 // syntax and not used to form a pointer to member is used in the
1853 // body of a non-static member function of class X, if name lookup
1854 // resolves the name in the id-expression to a non-static non-type
1855 // member of some class C, the id-expression is transformed into a
1856 // class member access expression using (*this) as the
1857 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001858 //
1859 // But we don't actually need to do this for '&' operands if R
1860 // resolved to a function or overloaded function set, because the
1861 // expression is ill-formed if it actually works out to be a
1862 // non-static member function:
1863 //
1864 // C++ [expr.ref]p4:
1865 // Otherwise, if E1.E2 refers to a non-static member function. . .
1866 // [t]he expression can be used only as the left-hand operand of a
1867 // member function call.
1868 //
1869 // There are other safeguards against such uses, but it's important
1870 // to get this right here so that we don't end up making a
1871 // spuriously dependent expression if we're inside a dependent
1872 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001873 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001874 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001875 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001876 MightBeImplicitMember = true;
1877 else if (!SS.isEmpty())
1878 MightBeImplicitMember = false;
1879 else if (R.isOverloadedResult())
1880 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001881 else if (R.isUnresolvableResult())
1882 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001883 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001884 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1885 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001886
1887 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001888 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001889 }
1890
John McCallf7a1a742009-11-24 19:00:30 +00001891 if (TemplateArgs)
1892 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001893
John McCallf7a1a742009-11-24 19:00:30 +00001894 return BuildDeclarationNameExpr(SS, R, ADL);
1895}
1896
John McCall129e2df2009-11-30 22:42:35 +00001897/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1898/// declaration name, generally during template instantiation.
1899/// There's a large number of things which don't need to be done along
1900/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001901ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001902Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001903 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001904 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001905 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001906 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001907
John McCall77bb1aa2010-05-01 00:40:08 +00001908 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001909 return ExprError();
1910
Abramo Bagnara25777432010-08-11 22:01:17 +00001911 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001912 LookupQualifiedName(R, DC);
1913
1914 if (R.isAmbiguous())
1915 return ExprError();
1916
1917 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001918 Diag(NameInfo.getLoc(), diag::err_no_member)
1919 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001920 return ExprError();
1921 }
1922
1923 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1924}
1925
1926/// LookupInObjCMethod - The parser has read a name in, and Sema has
1927/// detected that we're currently inside an ObjC method. Perform some
1928/// additional lookup.
1929///
1930/// Ideally, most of this would be done by lookup, but there's
1931/// actually quite a lot of extra work involved.
1932///
1933/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001934ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001935Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001936 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001937 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001938 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001939
John McCallf7a1a742009-11-24 19:00:30 +00001940 // There are two cases to handle here. 1) scoped lookup could have failed,
1941 // in which case we should look for an ivar. 2) scoped lookup could have
1942 // found a decl, but that decl is outside the current instance method (i.e.
1943 // a global variable). In these two cases, we do a lookup for an ivar with
1944 // this name, if the lookup sucedes, we replace it our current decl.
1945
1946 // If we're in a class method, we don't normally want to look for
1947 // ivars. But if we don't find anything else, and there's an
1948 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001949 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001950
1951 bool LookForIvars;
1952 if (Lookup.empty())
1953 LookForIvars = true;
1954 else if (IsClassMethod)
1955 LookForIvars = false;
1956 else
1957 LookForIvars = (Lookup.isSingleResult() &&
1958 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001959 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001960 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001961 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001962 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001963 ObjCIvarDecl *IV = 0;
1964 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001965 // Diagnose using an ivar in a class method.
1966 if (IsClassMethod)
1967 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1968 << IV->getDeclName());
1969
1970 // If we're referencing an invalid decl, just return this as a silent
1971 // error node. The error diagnostic was already emitted on the decl.
1972 if (IV->isInvalidDecl())
1973 return ExprError();
1974
1975 // Check if referencing a field with __attribute__((deprecated)).
1976 if (DiagnoseUseOfDecl(IV, Loc))
1977 return ExprError();
1978
1979 // Diagnose the use of an ivar outside of the declaring class.
1980 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1981 ClassDeclared != IFace)
1982 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1983
1984 // FIXME: This should use a new expr for a direct reference, don't
1985 // turn this into Self->ivar, just return a BareIVarExpr or something.
1986 IdentifierInfo &II = Context.Idents.get("self");
1987 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001988 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001989 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001990 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001991 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001992 SelfName, false, false);
1993 if (SelfExpr.isInvalid())
1994 return ExprError();
1995
John Wiegley429bb272011-04-08 18:41:53 +00001996 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1997 if (SelfExpr.isInvalid())
1998 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001999
John McCallf7a1a742009-11-24 19:00:30 +00002000 MarkDeclarationReferenced(Loc, IV);
2001 return Owned(new (Context)
2002 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002003 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002004 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002005 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002006 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002007 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2008 ObjCInterfaceDecl *ClassDeclared;
2009 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2010 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2011 IFace == ClassDeclared)
2012 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2013 }
John McCallf7a1a742009-11-24 19:00:30 +00002014 }
2015 }
2016
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002017 if (Lookup.empty() && II && AllowBuiltinCreation) {
2018 // FIXME. Consolidate this with similar code in LookupName.
2019 if (unsigned BuiltinID = II->getBuiltinID()) {
2020 if (!(getLangOptions().CPlusPlus &&
2021 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2022 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2023 S, Lookup.isForRedeclaration(),
2024 Lookup.getNameLoc());
2025 if (D) Lookup.addDecl(D);
2026 }
2027 }
2028 }
John McCallf7a1a742009-11-24 19:00:30 +00002029 // Sentinel value saying that we didn't do anything special.
2030 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002031}
John McCallba135432009-11-21 08:51:07 +00002032
John McCall6bb80172010-03-30 21:47:33 +00002033/// \brief Cast a base object to a member's actual type.
2034///
2035/// Logically this happens in three phases:
2036///
2037/// * First we cast from the base type to the naming class.
2038/// The naming class is the class into which we were looking
2039/// when we found the member; it's the qualifier type if a
2040/// qualifier was provided, and otherwise it's the base type.
2041///
2042/// * Next we cast from the naming class to the declaring class.
2043/// If the member we found was brought into a class's scope by
2044/// a using declaration, this is that class; otherwise it's
2045/// the class declaring the member.
2046///
2047/// * Finally we cast from the declaring class to the "true"
2048/// declaring class of the member. This conversion does not
2049/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002050ExprResult
2051Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002052 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002053 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002054 NamedDecl *Member) {
2055 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2056 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002057 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002058
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 QualType DestRecordType;
2060 QualType DestType;
2061 QualType FromRecordType;
2062 QualType FromType = From->getType();
2063 bool PointerConversions = false;
2064 if (isa<FieldDecl>(Member)) {
2065 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002066
Douglas Gregor5fccd362010-03-03 23:55:11 +00002067 if (FromType->getAs<PointerType>()) {
2068 DestType = Context.getPointerType(DestRecordType);
2069 FromRecordType = FromType->getPointeeType();
2070 PointerConversions = true;
2071 } else {
2072 DestType = DestRecordType;
2073 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002074 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002075 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2076 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002077 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002078
Douglas Gregor5fccd362010-03-03 23:55:11 +00002079 DestType = Method->getThisType(Context);
2080 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002081
Douglas Gregor5fccd362010-03-03 23:55:11 +00002082 if (FromType->getAs<PointerType>()) {
2083 FromRecordType = FromType->getPointeeType();
2084 PointerConversions = true;
2085 } else {
2086 FromRecordType = FromType;
2087 DestType = DestRecordType;
2088 }
2089 } else {
2090 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002091 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002092 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002093
Douglas Gregor5fccd362010-03-03 23:55:11 +00002094 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002095 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002096
Douglas Gregor5fccd362010-03-03 23:55:11 +00002097 // If the unqualified types are the same, no conversion is necessary.
2098 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002099 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002100
John McCall6bb80172010-03-30 21:47:33 +00002101 SourceRange FromRange = From->getSourceRange();
2102 SourceLocation FromLoc = FromRange.getBegin();
2103
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002104 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002105
Douglas Gregor5fccd362010-03-03 23:55:11 +00002106 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002107 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002108 // class name.
2109 //
2110 // If the member was a qualified name and the qualified referred to a
2111 // specific base subobject type, we'll cast to that intermediate type
2112 // first and then to the object in which the member is declared. That allows
2113 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2114 //
2115 // class Base { public: int x; };
2116 // class Derived1 : public Base { };
2117 // class Derived2 : public Base { };
2118 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2119 //
2120 // void VeryDerived::f() {
2121 // x = 17; // error: ambiguous base subobjects
2122 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2123 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002124 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002125 QualType QType = QualType(Qualifier->getAsType(), 0);
2126 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2127 assert(QType->isRecordType() && "lookup done with non-record type");
2128
2129 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2130
2131 // In C++98, the qualifier type doesn't actually have to be a base
2132 // type of the object type, in which case we just ignore it.
2133 // Otherwise build the appropriate casts.
2134 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002135 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002136 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002137 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002138 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002139
Douglas Gregor5fccd362010-03-03 23:55:11 +00002140 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002141 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002142 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2143 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002144
2145 FromType = QType;
2146 FromRecordType = QRecordType;
2147
2148 // If the qualifier type was the same as the destination type,
2149 // we're done.
2150 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002151 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002152 }
2153 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002154
John McCall6bb80172010-03-30 21:47:33 +00002155 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002156
John McCall6bb80172010-03-30 21:47:33 +00002157 // If we actually found the member through a using declaration, cast
2158 // down to the using declaration's type.
2159 //
2160 // Pointer equality is fine here because only one declaration of a
2161 // class ever has member declarations.
2162 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2163 assert(isa<UsingShadowDecl>(FoundDecl));
2164 QualType URecordType = Context.getTypeDeclType(
2165 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2166
2167 // We only need to do this if the naming-class to declaring-class
2168 // conversion is non-trivial.
2169 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2170 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002171 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002172 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002173 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002174 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002175
John McCall6bb80172010-03-30 21:47:33 +00002176 QualType UType = URecordType;
2177 if (PointerConversions)
2178 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002179 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2180 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002181 FromType = UType;
2182 FromRecordType = URecordType;
2183 }
2184
2185 // We don't do access control for the conversion from the
2186 // declaring class to the true declaring class.
2187 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002188 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002189
John McCallf871d0c2010-08-07 06:22:56 +00002190 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002191 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2192 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002193 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002194 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002195
John Wiegley429bb272011-04-08 18:41:53 +00002196 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2197 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002198}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002199
John McCallf7a1a742009-11-24 19:00:30 +00002200bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002201 const LookupResult &R,
2202 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002203 // Only when used directly as the postfix-expression of a call.
2204 if (!HasTrailingLParen)
2205 return false;
2206
2207 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002208 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002209 return false;
2210
2211 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002212 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002213 return false;
2214
2215 // Turn off ADL when we find certain kinds of declarations during
2216 // normal lookup:
2217 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2218 NamedDecl *D = *I;
2219
2220 // C++0x [basic.lookup.argdep]p3:
2221 // -- a declaration of a class member
2222 // Since using decls preserve this property, we check this on the
2223 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002224 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002225 return false;
2226
2227 // C++0x [basic.lookup.argdep]p3:
2228 // -- a block-scope function declaration that is not a
2229 // using-declaration
2230 // NOTE: we also trigger this for function templates (in fact, we
2231 // don't check the decl type at all, since all other decl types
2232 // turn off ADL anyway).
2233 if (isa<UsingShadowDecl>(D))
2234 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2235 else if (D->getDeclContext()->isFunctionOrMethod())
2236 return false;
2237
2238 // C++0x [basic.lookup.argdep]p3:
2239 // -- a declaration that is neither a function or a function
2240 // template
2241 // And also for builtin functions.
2242 if (isa<FunctionDecl>(D)) {
2243 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2244
2245 // But also builtin functions.
2246 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2247 return false;
2248 } else if (!isa<FunctionTemplateDecl>(D))
2249 return false;
2250 }
2251
2252 return true;
2253}
2254
2255
John McCallba135432009-11-21 08:51:07 +00002256/// Diagnoses obvious problems with the use of the given declaration
2257/// as an expression. This is only actually called for lookups that
2258/// were not overloaded, and it doesn't promise that the declaration
2259/// will in fact be used.
2260static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002261 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002262 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2263 return true;
2264 }
2265
2266 if (isa<ObjCInterfaceDecl>(D)) {
2267 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2268 return true;
2269 }
2270
2271 if (isa<NamespaceDecl>(D)) {
2272 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2273 return true;
2274 }
2275
2276 return false;
2277}
2278
John McCall60d7b3a2010-08-24 06:29:42 +00002279ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002280Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002281 LookupResult &R,
2282 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002283 // If this is a single, fully-resolved result and we don't need ADL,
2284 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002285 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002286 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2287 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002288
2289 // We only need to check the declaration if there's exactly one
2290 // result, because in the overloaded case the results can only be
2291 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002292 if (R.isSingleResult() &&
2293 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002294 return ExprError();
2295
John McCallc373d482010-01-27 01:50:18 +00002296 // Otherwise, just build an unresolved lookup expression. Suppress
2297 // any lookup-related diagnostics; we'll hash these out later, when
2298 // we've picked a target.
2299 R.suppressDiagnostics();
2300
John McCallba135432009-11-21 08:51:07 +00002301 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002302 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002303 SS.getWithLocInContext(Context),
2304 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002305 NeedsADL, R.isOverloadedResult(),
2306 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002307
2308 return Owned(ULE);
2309}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002310
John McCallba135432009-11-21 08:51:07 +00002311/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002312ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002313Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002314 const DeclarationNameInfo &NameInfo,
2315 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002316 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002317 assert(!isa<FunctionTemplateDecl>(D) &&
2318 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002319
Abramo Bagnara25777432010-08-11 22:01:17 +00002320 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002321 if (CheckDeclInExpr(*this, Loc, D))
2322 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002323
Douglas Gregor9af2f522009-12-01 16:58:18 +00002324 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2325 // Specifically diagnose references to class templates that are missing
2326 // a template argument list.
2327 Diag(Loc, diag::err_template_decl_ref)
2328 << Template << SS.getRange();
2329 Diag(Template->getLocation(), diag::note_template_decl_here);
2330 return ExprError();
2331 }
2332
2333 // Make sure that we're referring to a value.
2334 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2335 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002336 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002337 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002338 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002339 return ExprError();
2340 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002341
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002342 // Check whether this declaration can be used. Note that we suppress
2343 // this check when we're going to perform argument-dependent lookup
2344 // on this function name, because this might not be the function
2345 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002346 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002347 return ExprError();
2348
Steve Naroffdd972f22008-09-05 22:11:13 +00002349 // Only create DeclRefExpr's for valid Decl's.
2350 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002351 return ExprError();
2352
John McCall5808ce42011-02-03 08:15:49 +00002353 // Handle members of anonymous structs and unions. If we got here,
2354 // and the reference is to a class member indirect field, then this
2355 // must be the subject of a pointer-to-member expression.
2356 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2357 if (!indirectField->isCXXClassMember())
2358 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2359 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002360
Chris Lattner639e2d32008-10-20 05:16:36 +00002361 // If the identifier reference is inside a block, and it refers to a value
2362 // that is outside the block, create a BlockDeclRefExpr instead of a
2363 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2364 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002365 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002366 // We do not do this for things like enum constants, global variables, etc,
2367 // as they do not get snapshotted.
2368 //
John McCall6b5a61b2011-02-07 10:33:21 +00002369 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002370 case CR_Error:
2371 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002372
John McCall469a1eb2011-02-02 13:00:07 +00002373 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002374 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2375 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2376
2377 case CR_CaptureByRef:
2378 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2379 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002380
2381 case CR_NoCapture: {
2382 // If this reference is not in a block or if the referenced
2383 // variable is within the block, create a normal DeclRefExpr.
2384
2385 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002386 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002387
2388 switch (D->getKind()) {
2389 // Ignore all the non-ValueDecl kinds.
2390#define ABSTRACT_DECL(kind)
2391#define VALUE(type, base)
2392#define DECL(type, base) \
2393 case Decl::type:
2394#include "clang/AST/DeclNodes.inc"
2395 llvm_unreachable("invalid value decl kind");
2396 return ExprError();
2397
2398 // These shouldn't make it here.
2399 case Decl::ObjCAtDefsField:
2400 case Decl::ObjCIvar:
2401 llvm_unreachable("forming non-member reference to ivar?");
2402 return ExprError();
2403
2404 // Enum constants are always r-values and never references.
2405 // Unresolved using declarations are dependent.
2406 case Decl::EnumConstant:
2407 case Decl::UnresolvedUsingValue:
2408 valueKind = VK_RValue;
2409 break;
2410
2411 // Fields and indirect fields that got here must be for
2412 // pointer-to-member expressions; we just call them l-values for
2413 // internal consistency, because this subexpression doesn't really
2414 // exist in the high-level semantics.
2415 case Decl::Field:
2416 case Decl::IndirectField:
2417 assert(getLangOptions().CPlusPlus &&
2418 "building reference to field in C?");
2419
2420 // These can't have reference type in well-formed programs, but
2421 // for internal consistency we do this anyway.
2422 type = type.getNonReferenceType();
2423 valueKind = VK_LValue;
2424 break;
2425
2426 // Non-type template parameters are either l-values or r-values
2427 // depending on the type.
2428 case Decl::NonTypeTemplateParm: {
2429 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2430 type = reftype->getPointeeType();
2431 valueKind = VK_LValue; // even if the parameter is an r-value reference
2432 break;
2433 }
2434
2435 // For non-references, we need to strip qualifiers just in case
2436 // the template parameter was declared as 'const int' or whatever.
2437 valueKind = VK_RValue;
2438 type = type.getUnqualifiedType();
2439 break;
2440 }
2441
2442 case Decl::Var:
2443 // In C, "extern void blah;" is valid and is an r-value.
2444 if (!getLangOptions().CPlusPlus &&
2445 !type.hasQualifiers() &&
2446 type->isVoidType()) {
2447 valueKind = VK_RValue;
2448 break;
2449 }
2450 // fallthrough
2451
2452 case Decl::ImplicitParam:
2453 case Decl::ParmVar:
2454 // These are always l-values.
2455 valueKind = VK_LValue;
2456 type = type.getNonReferenceType();
2457 break;
2458
2459 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002460 const FunctionType *fty = type->castAs<FunctionType>();
2461
2462 // If we're referring to a function with an __unknown_anytype
2463 // result type, make the entire expression __unknown_anytype.
2464 if (fty->getResultType() == Context.UnknownAnyTy) {
2465 type = Context.UnknownAnyTy;
2466 valueKind = VK_RValue;
2467 break;
2468 }
2469
John McCall76a40212011-02-09 01:13:10 +00002470 // Functions are l-values in C++.
2471 if (getLangOptions().CPlusPlus) {
2472 valueKind = VK_LValue;
2473 break;
2474 }
2475
2476 // C99 DR 316 says that, if a function type comes from a
2477 // function definition (without a prototype), that type is only
2478 // used for checking compatibility. Therefore, when referencing
2479 // the function, we pretend that we don't have the full function
2480 // type.
John McCall755d8492011-04-12 00:42:48 +00002481 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2482 isa<FunctionProtoType>(fty))
2483 type = Context.getFunctionNoProtoType(fty->getResultType(),
2484 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002485
2486 // Functions are r-values in C.
2487 valueKind = VK_RValue;
2488 break;
2489 }
2490
2491 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002492 // If we're referring to a method with an __unknown_anytype
2493 // result type, make the entire expression __unknown_anytype.
2494 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002495 if (const FunctionProtoType *proto
2496 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002497 if (proto->getResultType() == Context.UnknownAnyTy) {
2498 type = Context.UnknownAnyTy;
2499 valueKind = VK_RValue;
2500 break;
2501 }
2502
John McCall76a40212011-02-09 01:13:10 +00002503 // C++ methods are l-values if static, r-values if non-static.
2504 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2505 valueKind = VK_LValue;
2506 break;
2507 }
2508 // fallthrough
2509
2510 case Decl::CXXConversion:
2511 case Decl::CXXDestructor:
2512 case Decl::CXXConstructor:
2513 valueKind = VK_RValue;
2514 break;
2515 }
2516
2517 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2518 }
2519
John McCall469a1eb2011-02-02 13:00:07 +00002520 }
John McCallf89e55a2010-11-18 06:31:45 +00002521
John McCall6b5a61b2011-02-07 10:33:21 +00002522 llvm_unreachable("unknown capture result");
2523 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002524}
2525
John McCall755d8492011-04-12 00:42:48 +00002526ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002527 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002530 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002531 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2532 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2533 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002535
Chris Lattnerfa28b302008-01-12 08:14:25 +00002536 // Pre-defined identifiers are of type char[x], where x is the length of the
2537 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Anders Carlsson3a082d82009-09-08 18:24:21 +00002539 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002540 if (!currentDecl && getCurBlock())
2541 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002542 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002543 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002544 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002545 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002546
Anders Carlsson773f3972009-09-11 01:22:35 +00002547 QualType ResTy;
2548 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2549 ResTy = Context.DependentTy;
2550 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002551 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002552
Anders Carlsson773f3972009-09-11 01:22:35 +00002553 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002554 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002555 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2556 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002557 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002558}
2559
John McCall60d7b3a2010-08-24 06:29:42 +00002560ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002562 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002563 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002564 if (Invalid)
2565 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002566
Benjamin Kramerddeea562010-02-27 13:44:12 +00002567 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002568 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002571
Chris Lattnere8337df2009-12-30 21:19:39 +00002572 QualType Ty;
2573 if (!getLangOptions().CPlusPlus)
2574 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2575 else if (Literal.isWide())
2576 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002577 else if (Literal.isUTF16())
2578 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2579 else if (Literal.isUTF32())
2580 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002581 else if (Literal.isMultiChar())
2582 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002583 else
2584 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002585
Douglas Gregor5cee1192011-07-27 05:40:30 +00002586 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2587 if (Literal.isWide())
2588 Kind = CharacterLiteral::Wide;
2589 else if (Literal.isUTF16())
2590 Kind = CharacterLiteral::UTF16;
2591 else if (Literal.isUTF32())
2592 Kind = CharacterLiteral::UTF32;
2593
2594 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2595 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002596}
2597
John McCall60d7b3a2010-08-24 06:29:42 +00002598ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002599 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2601 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002602 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002603 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002604 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002605 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
Ted Kremenek28396602009-01-13 23:19:12 +00002607
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002609 // Add padding so that NumericLiteralParser can overread by one character.
2610 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002612
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002614 bool Invalid = false;
2615 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2616 if (Invalid)
2617 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002618
Mike Stump1eb44332009-09-09 15:08:12 +00002619 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 Tok.getLocation(), PP);
2621 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002622 return ExprError();
2623
Chris Lattner5d661452007-08-26 03:42:43 +00002624 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002625
Chris Lattner5d661452007-08-26 03:42:43 +00002626 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002627 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002628 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002629 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002630 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002631 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002632 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002633 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002634
2635 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2636
John McCall94c939d2009-12-24 09:08:04 +00002637 using llvm::APFloat;
2638 APFloat Val(Format);
2639
2640 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002641
2642 // Overflow is always an error, but underflow is only an error if
2643 // we underflowed to zero (APFloat reports denormals as underflow).
2644 if ((result & APFloat::opOverflow) ||
2645 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002646 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002647 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002648 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002649 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002650 APFloat::getLargest(Format).toString(buffer);
2651 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002652 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002653 APFloat::getSmallest(Format).toString(buffer);
2654 }
2655
2656 Diag(Tok.getLocation(), diagnostic)
2657 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002659 }
2660
2661 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002662 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002663
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002664 if (Ty == Context.DoubleTy) {
2665 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002666 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002667 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2668 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002669 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002670 }
2671 }
Chris Lattner5d661452007-08-26 03:42:43 +00002672 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002673 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002674 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002675 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002676
Neil Boothb9449512007-08-29 22:00:19 +00002677 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +00002678 if (!getLangOptions().C99 && Literal.isLongLong)
2679 Diag(Tok.getLocation(),
2680 getLangOptions().CPlusPlus0x ?
2681 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002682
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 // Get the value in the widest-possible width.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002684 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002685
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 if (Literal.GetIntegerValue(ResultVal)) {
2687 // If this value didn't fit into uintmax_t, warn and force to ull.
2688 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002689 Ty = Context.UnsignedLongLongTy;
2690 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002691 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 } else {
2693 // If this value fits into a ULL, try to figure out what else it fits into
2694 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002695
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2697 // be an unsigned int.
2698 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2699
2700 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002701 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002702 if (!Literal.isLong && !Literal.isLongLong) {
2703 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002704 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002705
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 // Does it fit in a unsigned int?
2707 if (ResultVal.isIntN(IntSize)) {
2708 // Does it fit in a signed int?
2709 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002710 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002712 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002713 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002715 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002716
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002718 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002719 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002720
Reid Spencer5f016e22007-07-11 17:01:13 +00002721 // Does it fit in a unsigned long?
2722 if (ResultVal.isIntN(LongSize)) {
2723 // Does it fit in a signed long?
2724 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002725 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002727 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002728 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002730 }
2731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002733 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002734 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002735
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 // Does it fit in a unsigned long long?
2737 if (ResultVal.isIntN(LongLongSize)) {
2738 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002739 // To be compatible with MSVC, hex integer literals ending with the
2740 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002741 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet62ec1f22011-09-17 17:15:52 +00002742 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002743 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002745 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002746 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 }
2748 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002749
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 // If we still couldn't decide a type, we probably have something that
2751 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002752 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002754 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002755 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002757
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002758 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002759 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002761 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002763
Chris Lattner5d661452007-08-26 03:42:43 +00002764 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2765 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002766 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002767 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002768
2769 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002770}
2771
Richard Trieuccd891a2011-09-09 01:45:06 +00002772ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002773 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002774 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002775}
2776
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002777static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2778 SourceLocation Loc,
2779 SourceRange ArgRange) {
2780 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2781 // scalar or vector data type argument..."
2782 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2783 // type (C99 6.2.5p18) or void.
2784 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2785 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2786 << T << ArgRange;
2787 return true;
2788 }
2789
2790 assert((T->isVoidType() || !T->isIncompleteType()) &&
2791 "Scalar types should always be complete");
2792 return false;
2793}
2794
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002795static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2796 SourceLocation Loc,
2797 SourceRange ArgRange,
2798 UnaryExprOrTypeTrait TraitKind) {
2799 // C99 6.5.3.4p1:
2800 if (T->isFunctionType()) {
2801 // alignof(function) is allowed as an extension.
2802 if (TraitKind == UETT_SizeOf)
2803 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2804 return false;
2805 }
2806
2807 // Allow sizeof(void)/alignof(void) as an extension.
2808 if (T->isVoidType()) {
2809 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2810 return false;
2811 }
2812
2813 return true;
2814}
2815
2816static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2817 SourceLocation Loc,
2818 SourceRange ArgRange,
2819 UnaryExprOrTypeTrait TraitKind) {
2820 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2821 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2822 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2823 << T << (TraitKind == UETT_SizeOf)
2824 << ArgRange;
2825 return true;
2826 }
2827
2828 return false;
2829}
2830
Chandler Carruth9d342d02011-05-26 08:53:10 +00002831/// \brief Check the constrains on expression operands to unary type expression
2832/// and type traits.
2833///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002834/// Completes any types necessary and validates the constraints on the operand
2835/// expression. The logic mostly mirrors the type-based overload, but may modify
2836/// the expression as it completes the type for that expression through template
2837/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002838bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002839 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002840 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002841
2842 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2843 // the result is the size of the referenced type."
2844 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2845 // result shall be the alignment of the referenced type."
2846 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2847 ExprTy = Ref->getPointeeType();
2848
2849 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002850 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2851 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002852
2853 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002854 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2855 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002856 return false;
2857
Richard Trieuccd891a2011-09-09 01:45:06 +00002858 if (RequireCompleteExprType(E,
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002859 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuccd891a2011-09-09 01:45:06 +00002860 << ExprKind << E->getSourceRange(),
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002861 std::make_pair(SourceLocation(), PDiag(0))))
2862 return true;
2863
2864 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002865 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002866 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2867 ExprTy = Ref->getPointeeType();
2868
Richard Trieuccd891a2011-09-09 01:45:06 +00002869 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2870 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002871 return true;
2872
Nico Webercf739922011-06-15 02:47:03 +00002873 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002874 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002875 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2876 QualType OType = PVD->getOriginalType();
2877 QualType Type = PVD->getType();
2878 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002879 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002880 << Type << OType;
2881 Diag(PVD->getLocation(), diag::note_declared_at);
2882 }
2883 }
2884 }
2885 }
2886
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002887 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002888}
2889
2890/// \brief Check the constraints on operands to unary expression and type
2891/// traits.
2892///
2893/// This will complete any types necessary, and validate the various constraints
2894/// on those operands.
2895///
Reid Spencer5f016e22007-07-11 17:01:13 +00002896/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002897/// C99 6.3.2.1p[2-4] all state:
2898/// Except when it is the operand of the sizeof operator ...
2899///
2900/// C++ [expr.sizeof]p4
2901/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2902/// standard conversions are not applied to the operand of sizeof.
2903///
2904/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002905bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002906 SourceLocation OpLoc,
2907 SourceRange ExprRange,
2908 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002909 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002910 return false;
2911
Sebastian Redl5d484e82009-11-23 17:18:46 +00002912 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2913 // the result is the size of the referenced type."
2914 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2915 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002916 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2917 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002918
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002919 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002920 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002921
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002922 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002923 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002924 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002925 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Richard Trieuccd891a2011-09-09 01:45:06 +00002927 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002928 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002929 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002930 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Richard Trieuccd891a2011-09-09 01:45:06 +00002932 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002933 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002934 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chris Lattner1efaa952009-04-24 00:30:45 +00002936 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002937}
2938
Chandler Carruth9d342d02011-05-26 08:53:10 +00002939static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002940 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002941
Mike Stump1eb44332009-09-09 15:08:12 +00002942 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002943 if (isa<DeclRefExpr>(E))
2944 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002945
2946 // Cannot know anything else if the expression is dependent.
2947 if (E->isTypeDependent())
2948 return false;
2949
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002950 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002951 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2952 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002953 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002954 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002955
2956 // Alignment of a field access is always okay, so long as it isn't a
2957 // bit-field.
2958 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002959 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002960 return false;
2961
Chandler Carruth9d342d02011-05-26 08:53:10 +00002962 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002963}
2964
Chandler Carruth9d342d02011-05-26 08:53:10 +00002965bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002966 E = E->IgnoreParens();
2967
2968 // Cannot know anything else if the expression is dependent.
2969 if (E->isTypeDependent())
2970 return false;
2971
Chandler Carruth9d342d02011-05-26 08:53:10 +00002972 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002973}
2974
Douglas Gregorba498172009-03-13 21:01:28 +00002975/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002976ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002977Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2978 SourceLocation OpLoc,
2979 UnaryExprOrTypeTrait ExprKind,
2980 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002981 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002982 return ExprError();
2983
John McCalla93c9342009-12-07 02:54:59 +00002984 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002985
Douglas Gregorba498172009-03-13 21:01:28 +00002986 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002987 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002988 return ExprError();
2989
2990 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002991 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2992 Context.getSizeType(),
2993 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002994}
2995
2996/// \brief Build a sizeof or alignof expression given an expression
2997/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002998ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002999Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3000 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003001 ExprResult PE = CheckPlaceholderExpr(E);
3002 if (PE.isInvalid())
3003 return ExprError();
3004
3005 E = PE.get();
3006
Douglas Gregorba498172009-03-13 21:01:28 +00003007 // Verify that the operand is valid.
3008 bool isInvalid = false;
3009 if (E->isTypeDependent()) {
3010 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003011 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003012 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003013 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003014 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003015 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003016 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003017 isInvalid = true;
3018 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003019 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003020 }
3021
3022 if (isInvalid)
3023 return ExprError();
3024
3025 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003026 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003027 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003028 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003029}
3030
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003031/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3032/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003033/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003034ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003035Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003036 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003037 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003039 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003040
Richard Trieuccd891a2011-09-09 01:45:06 +00003041 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003042 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003043 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003044 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003045 }
Sebastian Redl05189992008-11-11 17:56:53 +00003046
Douglas Gregorba498172009-03-13 21:01:28 +00003047 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003048 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003049 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003050}
3051
John Wiegley429bb272011-04-08 18:41:53 +00003052static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003053 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003054 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003055 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003056
John McCallf6a16482010-12-04 03:47:34 +00003057 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003058 if (V.get()->getObjectKind() != OK_Ordinary) {
3059 V = S.DefaultLvalueConversion(V.take());
3060 if (V.isInvalid())
3061 return QualType();
3062 }
John McCallf6a16482010-12-04 03:47:34 +00003063
Chris Lattnercc26ed72007-08-26 05:39:26 +00003064 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003065 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003066 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Chris Lattnercc26ed72007-08-26 05:39:26 +00003068 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003069 if (V.get()->getType()->isArithmeticType())
3070 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003071
John McCall2cd11fe2010-10-12 02:09:17 +00003072 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003073 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003074 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003075 if (PR.get() != V.get()) {
3076 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00003077 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003078 }
3079
Chris Lattnercc26ed72007-08-26 05:39:26 +00003080 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003081 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003082 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003083 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003084}
3085
3086
Reid Spencer5f016e22007-07-11 17:01:13 +00003087
John McCall60d7b3a2010-08-24 06:29:42 +00003088ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003089Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003090 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003091 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003093 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003094 case tok::plusplus: Opc = UO_PostInc; break;
3095 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003097
John McCall9ae2f072010-08-23 23:25:46 +00003098 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003099}
3100
John McCall60d7b3a2010-08-24 06:29:42 +00003101ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003102Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3103 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003104 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003105 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003106 if (Result.isInvalid()) return ExprError();
3107 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003108
John McCall9ae2f072010-08-23 23:25:46 +00003109 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Douglas Gregor337c6b92008-11-19 17:17:41 +00003111 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003112 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003113 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003114 Context.DependentTy,
3115 VK_LValue, OK_Ordinary,
3116 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003117 }
3118
Mike Stump1eb44332009-09-09 15:08:12 +00003119 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003120 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003121 LHSExp->getType()->isEnumeralType() ||
3122 RHSExp->getType()->isRecordType() ||
3123 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003124 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003125 }
3126
John McCall9ae2f072010-08-23 23:25:46 +00003127 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003128}
3129
3130
John McCall60d7b3a2010-08-24 06:29:42 +00003131ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003132Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003133 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003134 Expr *LHSExp = Base;
3135 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003136
Chris Lattner12d9ff62007-07-16 00:14:47 +00003137 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003138 if (!LHSExp->getType()->getAs<VectorType>()) {
3139 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3140 if (Result.isInvalid())
3141 return ExprError();
3142 LHSExp = Result.take();
3143 }
3144 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3145 if (Result.isInvalid())
3146 return ExprError();
3147 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003148
Chris Lattner12d9ff62007-07-16 00:14:47 +00003149 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003150 ExprValueKind VK = VK_LValue;
3151 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003152
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003154 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003155 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003156 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003157 Expr *BaseExpr, *IndexExpr;
3158 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003159 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3160 BaseExpr = LHSExp;
3161 IndexExpr = RHSExp;
3162 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003163 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003164 BaseExpr = LHSExp;
3165 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003166 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003167 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003168 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003169 BaseExpr = RHSExp;
3170 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003171 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003172 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003173 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003174 BaseExpr = LHSExp;
3175 IndexExpr = RHSExp;
3176 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003177 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003178 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003179 // Handle the uncommon case of "123[Ptr]".
3180 BaseExpr = RHSExp;
3181 IndexExpr = LHSExp;
3182 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003183 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003184 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003185 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003186 VK = LHSExp->getValueKind();
3187 if (VK != VK_RValue)
3188 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003189
Chris Lattner12d9ff62007-07-16 00:14:47 +00003190 // FIXME: need to deal with const...
3191 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003192 } else if (LHSTy->isArrayType()) {
3193 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003194 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003195 // wasn't promoted because of the C90 rule that doesn't
3196 // allow promoting non-lvalue arrays. Warn, then
3197 // force the promotion here.
3198 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3199 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003200 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3201 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003202 LHSTy = LHSExp->getType();
3203
3204 BaseExpr = LHSExp;
3205 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003206 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003207 } else if (RHSTy->isArrayType()) {
3208 // Same as previous, except for 123[f().a] case
3209 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3210 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003211 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3212 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003213 RHSTy = RHSExp->getType();
3214
3215 BaseExpr = RHSExp;
3216 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003217 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003219 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3220 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003221 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003222 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003223 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003224 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3225 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003226
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003227 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003228 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3229 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003230 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3231
Douglas Gregore7450f52009-03-24 19:52:54 +00003232 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003233 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3234 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003235 // incomplete types are not object types.
3236 if (ResultType->isFunctionType()) {
3237 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3238 << ResultType << BaseExpr->getSourceRange();
3239 return ExprError();
3240 }
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Abramo Bagnara46358452010-09-13 06:50:07 +00003242 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3243 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003244 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3245 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003246
3247 // C forbids expressions of unqualified void type from being l-values.
3248 // See IsCForbiddenLValueType.
3249 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003250 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003251 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003252 PDiag(diag::err_subscript_incomplete_type)
3253 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003254 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Chris Lattner1efaa952009-04-24 00:30:45 +00003256 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003257 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003258 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3259 << ResultType << BaseExpr->getSourceRange();
3260 return ExprError();
3261 }
Mike Stump1eb44332009-09-09 15:08:12 +00003262
John McCall09431682010-11-18 19:01:18 +00003263 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003264 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003265
Mike Stumpeed9cac2009-02-19 03:04:26 +00003266 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003267 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003268}
3269
John McCall60d7b3a2010-08-24 06:29:42 +00003270ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003271 FunctionDecl *FD,
3272 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003273 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003274 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003275 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003276 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003277 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003278 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003279 return ExprError();
3280 }
3281
3282 if (Param->hasUninstantiatedDefaultArg()) {
3283 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003284
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003285 // Instantiate the expression.
3286 MultiLevelTemplateArgumentList ArgList
3287 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003288
Nico Weber08e41a62010-11-29 18:19:25 +00003289 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003290 = ArgList.getInnermost();
3291 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3292 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003293
Nico Weber08e41a62010-11-29 18:19:25 +00003294 ExprResult Result;
3295 {
3296 // C++ [dcl.fct.default]p5:
3297 // The names in the [default argument] expression are bound, and
3298 // the semantic constraints are checked, at the point where the
3299 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003300 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003301 Result = SubstExpr(UninstExpr, ArgList);
3302 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003303 if (Result.isInvalid())
3304 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003306 // Check the expression as an initializer for the parameter.
3307 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003308 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003309 InitializationKind Kind
3310 = InitializationKind::CreateCopy(Param->getLocation(),
3311 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3312 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003313
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003314 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3315 Result = InitSeq.Perform(*this, Entity, Kind,
3316 MultiExprArg(*this, &ResultE, 1));
3317 if (Result.isInvalid())
3318 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003319
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003320 // Build the default argument expression.
3321 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3322 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003323 }
3324
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003325 // If the default expression creates temporaries, we need to
3326 // push them to the current stack of expression temporaries so they'll
3327 // be properly destroyed.
3328 // FIXME: We should really be rebuilding the default argument with new
3329 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003330 // We don't need to do that with block decls, though, because
3331 // blocks in default argument expression can never capture anything.
3332 if (isa<ExprWithCleanups>(Param->getInit())) {
3333 // Set the "needs cleanups" bit regardless of whether there are
3334 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003335 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003336
3337 // Append all the objects to the cleanup list. Right now, this
3338 // should always be a no-op, because blocks in default argument
3339 // expressions should never be able to capture anything.
3340 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3341 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003342 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003343
3344 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003345 // Just mark all of the declarations in this potentially-evaluated expression
3346 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003347 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003348 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003349}
3350
Douglas Gregor88a35142008-12-22 05:46:06 +00003351/// ConvertArgumentsForCall - Converts the arguments specified in
3352/// Args/NumArgs to the parameter types of the function FDecl with
3353/// function prototype Proto. Call is the call expression itself, and
3354/// Fn is the function expression. For a C++ member function, this
3355/// routine does not attempt to convert the object argument. Returns
3356/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003357bool
3358Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003359 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003360 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003361 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003362 SourceLocation RParenLoc,
3363 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003364 // Bail out early if calling a builtin with custom typechecking.
3365 // We don't need to do this in the
3366 if (FDecl)
3367 if (unsigned ID = FDecl->getBuiltinID())
3368 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3369 return false;
3370
Mike Stumpeed9cac2009-02-19 03:04:26 +00003371 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003372 // assignment, to the types of the corresponding parameter, ...
3373 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003374 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003375 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003376 unsigned FnKind = Fn->getType()->isBlockPointerType()
3377 ? 1 /* block */
3378 : (IsExecConfig ? 3 /* kernel function (exec config) */
3379 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003380
Douglas Gregor88a35142008-12-22 05:46:06 +00003381 // If too few arguments are available (and we don't have default
3382 // arguments for the remaining parameters), don't make the call.
3383 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003384 if (NumArgs < MinArgs) {
3385 Diag(RParenLoc, MinArgs == NumArgsInProto
3386 ? diag::err_typecheck_call_too_few_args
3387 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003388 << FnKind
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003389 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003390
3391 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003392 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003393 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3394 << FDecl;
3395
3396 return true;
3397 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003398 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003399 }
3400
3401 // If too many are passed and not variadic, error on the extras and drop
3402 // them.
3403 if (NumArgs > NumArgsInProto) {
3404 if (!Proto->isVariadic()) {
3405 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003406 MinArgs == NumArgsInProto
3407 ? diag::err_typecheck_call_too_many_args
3408 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne1f240762011-10-02 23:49:29 +00003409 << FnKind
Eric Christopherccfa9632010-04-16 04:56:46 +00003410 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003411 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3412 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003413
3414 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003415 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003416 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3417 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003418
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003420 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003421 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003422 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003423 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003424 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003425 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003426 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3427 if (Fn->getType()->isBlockPointerType())
3428 CallType = VariadicBlock; // Block
3429 else if (isa<MemberExpr>(Fn))
3430 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003431 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003432 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003433 if (Invalid)
3434 return true;
3435 unsigned TotalNumArgs = AllArgs.size();
3436 for (unsigned i = 0; i < TotalNumArgs; ++i)
3437 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003438
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003439 return false;
3440}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003441
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003442bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3443 FunctionDecl *FDecl,
3444 const FunctionProtoType *Proto,
3445 unsigned FirstProtoArg,
3446 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003447 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003448 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003449 unsigned NumArgsInProto = Proto->getNumArgs();
3450 unsigned NumArgsToCheck = NumArgs;
3451 bool Invalid = false;
3452 if (NumArgs != NumArgsInProto)
3453 // Use default arguments for missing arguments
3454 NumArgsToCheck = NumArgsInProto;
3455 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003456 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003457 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003458 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003459
Douglas Gregor88a35142008-12-22 05:46:06 +00003460 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003461 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003462 if (ArgIx < NumArgs) {
3463 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003464
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003465 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3466 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003467 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003468 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003469 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003470
Douglas Gregora188ff22009-12-22 16:09:06 +00003471 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003472 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003473 if (FDecl && i < FDecl->getNumParams())
3474 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003475
John McCall5acb0c92011-10-17 18:40:02 +00003476 // Strip the unbridged-cast placeholder expression off, if applicable.
3477 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3478 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3479 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3480 Arg = stripARCUnbridgedCast(Arg);
3481
Douglas Gregora188ff22009-12-22 16:09:06 +00003482 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003483 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003484 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3485 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003486 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003487 SourceLocation(),
3488 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003489 if (ArgE.isInvalid())
3490 return true;
3491
3492 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003493 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003494 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003495
John McCall60d7b3a2010-08-24 06:29:42 +00003496 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003497 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003498 if (ArgExpr.isInvalid())
3499 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003500
Anders Carlsson56c5e332009-08-25 03:49:14 +00003501 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003502 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003503
3504 // Check for array bounds violations for each argument to the call. This
3505 // check only triggers warnings when the argument isn't a more complex Expr
3506 // with its own checking, such as a BinaryOperator.
3507 CheckArrayAccess(Arg);
3508
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003509 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3510 CheckStaticArrayArgument(CallLoc, Param, Arg);
3511
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003512 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003513 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003514
Douglas Gregor88a35142008-12-22 05:46:06 +00003515 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003516 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003517
3518 // Assume that extern "C" functions with variadic arguments that
3519 // return __unknown_anytype aren't *really* variadic.
3520 if (Proto->getResultType() == Context.UnknownAnyTy &&
3521 FDecl && FDecl->isExternC()) {
3522 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3523 ExprResult arg;
3524 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3525 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3526 else
3527 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3528 Invalid |= arg.isInvalid();
3529 AllArgs.push_back(arg.take());
3530 }
3531
3532 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3533 } else {
3534 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003535 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3536 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003537 Invalid |= Arg.isInvalid();
3538 AllArgs.push_back(Arg.take());
3539 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003540 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003541
3542 // Check for array bounds violations.
3543 for (unsigned i = ArgIx; i != NumArgs; ++i)
3544 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003545 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003546 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003547}
3548
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003549static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3550 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3551 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3552 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3553 << ATL->getLocalSourceRange();
3554}
3555
3556/// CheckStaticArrayArgument - If the given argument corresponds to a static
3557/// array parameter, check that it is non-null, and that if it is formed by
3558/// array-to-pointer decay, the underlying array is sufficiently large.
3559///
3560/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3561/// array type derivation, then for each call to the function, the value of the
3562/// corresponding actual argument shall provide access to the first element of
3563/// an array with at least as many elements as specified by the size expression.
3564void
3565Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3566 ParmVarDecl *Param,
3567 const Expr *ArgExpr) {
3568 // Static array parameters are not supported in C++.
3569 if (!Param || getLangOptions().CPlusPlus)
3570 return;
3571
3572 QualType OrigTy = Param->getOriginalType();
3573
3574 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3575 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3576 return;
3577
3578 if (ArgExpr->isNullPointerConstant(Context,
3579 Expr::NPC_NeverValueDependent)) {
3580 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3581 DiagnoseCalleeStaticArrayParam(*this, Param);
3582 return;
3583 }
3584
3585 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3586 if (!CAT)
3587 return;
3588
3589 const ConstantArrayType *ArgCAT =
3590 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3591 if (!ArgCAT)
3592 return;
3593
3594 if (ArgCAT->getSize().ult(CAT->getSize())) {
3595 Diag(CallLoc, diag::warn_static_array_too_small)
3596 << ArgExpr->getSourceRange()
3597 << (unsigned) ArgCAT->getSize().getZExtValue()
3598 << (unsigned) CAT->getSize().getZExtValue();
3599 DiagnoseCalleeStaticArrayParam(*this, Param);
3600 }
3601}
3602
John McCall755d8492011-04-12 00:42:48 +00003603/// Given a function expression of unknown-any type, try to rebuild it
3604/// to have a function type.
3605static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3606
Steve Narofff69936d2007-09-16 03:34:24 +00003607/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003608/// This provides the location of the left/right parens and a list of comma
3609/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003610ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003611Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003612 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003613 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003614 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003615
3616 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003617 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003618 if (Result.isInvalid()) return ExprError();
3619 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Richard Trieuccd891a2011-09-09 01:45:06 +00003621 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor88a35142008-12-22 05:46:06 +00003623 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003624 // If this is a pseudo-destructor expression, build the call immediately.
3625 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3626 if (NumArgs > 0) {
3627 // Pseudo-destructor calls should not have any arguments.
3628 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003629 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003630 SourceRange(Args[0]->getLocStart(),
3631 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Douglas Gregora71d8192009-09-04 17:36:40 +00003633 NumArgs = 0;
3634 }
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Douglas Gregora71d8192009-09-04 17:36:40 +00003636 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003637 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Douglas Gregor17330012009-02-04 15:01:18 +00003640 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003641 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003642 // FIXME: Will need to cache the results of name lookup (including ADL) in
3643 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003644 bool Dependent = false;
3645 if (Fn->isTypeDependent())
3646 Dependent = true;
3647 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3648 Dependent = true;
3649
Peter Collingbournee08ce652011-02-09 21:07:24 +00003650 if (Dependent) {
3651 if (ExecConfig) {
3652 return Owned(new (Context) CUDAKernelCallExpr(
3653 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3654 Context.DependentTy, VK_RValue, RParenLoc));
3655 } else {
3656 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3657 Context.DependentTy, VK_RValue,
3658 RParenLoc));
3659 }
3660 }
Douglas Gregor17330012009-02-04 15:01:18 +00003661
3662 // Determine whether this is a call to an object (C++ [over.call.object]).
3663 if (Fn->getType()->isRecordType())
3664 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003665 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003666
John McCall755d8492011-04-12 00:42:48 +00003667 if (Fn->getType() == Context.UnknownAnyTy) {
3668 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3669 if (result.isInvalid()) return ExprError();
3670 Fn = result.take();
3671 }
3672
John McCall864c0412011-04-26 20:42:42 +00003673 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003674 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003675 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003676 }
John McCall864c0412011-04-26 20:42:42 +00003677 }
John McCall129e2df2009-11-30 22:42:35 +00003678
John McCall864c0412011-04-26 20:42:42 +00003679 // Check for overloaded calls. This can happen even in C due to extensions.
3680 if (Fn->getType() == Context.OverloadTy) {
3681 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3682
Douglas Gregoree697e62011-10-13 18:10:35 +00003683 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003684 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003685 OverloadExpr *ovl = find.Expression;
3686 if (isa<UnresolvedLookupExpr>(ovl)) {
3687 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3688 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3689 RParenLoc, ExecConfig);
3690 } else {
John McCallaa81e162009-12-01 22:10:20 +00003691 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003692 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003693 }
3694 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003695 }
3696
Douglas Gregorfa047642009-02-04 00:32:51 +00003697 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003698
Eli Friedmanefa42f72009-12-26 03:35:45 +00003699 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003700
John McCall3b4294e2009-12-16 12:17:52 +00003701 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003702 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3703 if (UnOp->getOpcode() == UO_AddrOf)
3704 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3705
John McCall3b4294e2009-12-16 12:17:52 +00003706 if (isa<DeclRefExpr>(NakedFn))
3707 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003708 else if (isa<MemberExpr>(NakedFn))
3709 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003710
Peter Collingbournee08ce652011-02-09 21:07:24 +00003711 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003712 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003713}
3714
3715ExprResult
3716Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003717 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003718 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3719 if (!ConfigDecl)
3720 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3721 << "cudaConfigureCall");
3722 QualType ConfigQTy = ConfigDecl->getType();
3723
3724 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3725 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3726
Peter Collingbourne1f240762011-10-02 23:49:29 +00003727 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3728 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003729}
3730
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003731/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3732///
3733/// __builtin_astype( value, dst type )
3734///
Richard Trieuccd891a2011-09-09 01:45:06 +00003735ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003736 SourceLocation BuiltinLoc,
3737 SourceLocation RParenLoc) {
3738 ExprValueKind VK = VK_RValue;
3739 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003740 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3741 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003742 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3743 return ExprError(Diag(BuiltinLoc,
3744 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003745 << DstTy
3746 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003747 << E->getSourceRange());
3748 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003749 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003750}
3751
John McCall3b4294e2009-12-16 12:17:52 +00003752/// BuildResolvedCallExpr - Build a call to a resolved expression,
3753/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003754/// unary-convert to an expression of function-pointer or
3755/// block-pointer type.
3756///
3757/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003758ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003759Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3760 SourceLocation LParenLoc,
3761 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003762 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003763 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003764 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3765
Chris Lattner04421082008-04-08 04:40:51 +00003766 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003767 ExprResult Result = UsualUnaryConversions(Fn);
3768 if (Result.isInvalid())
3769 return ExprError();
3770 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003771
Chris Lattner925e60d2007-12-28 05:29:59 +00003772 // Make the call expr early, before semantic checks. This guarantees cleanup
3773 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003774 CallExpr *TheCall;
3775 if (Config) {
3776 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3777 cast<CallExpr>(Config),
3778 Args, NumArgs,
3779 Context.BoolTy,
3780 VK_RValue,
3781 RParenLoc);
3782 } else {
3783 TheCall = new (Context) CallExpr(Context, Fn,
3784 Args, NumArgs,
3785 Context.BoolTy,
3786 VK_RValue,
3787 RParenLoc);
3788 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003789
John McCall8e10f3b2011-02-26 05:39:39 +00003790 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3791
3792 // Bail out early if calling a builtin with custom typechecking.
3793 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3794 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3795
John McCall1de4d4e2011-04-07 08:22:57 +00003796 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003797 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003798 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003799 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3800 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003801 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003802 if (FuncT == 0)
3803 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3804 << Fn->getType() << Fn->getSourceRange());
3805 } else if (const BlockPointerType *BPT =
3806 Fn->getType()->getAs<BlockPointerType>()) {
3807 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3808 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003809 // Handle calls to expressions of unknown-any type.
3810 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003811 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003812 if (rewrite.isInvalid()) return ExprError();
3813 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003814 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003815 goto retry;
3816 }
3817
Sebastian Redl0eb23302009-01-19 00:08:26 +00003818 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3819 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003820 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003821
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003822 if (getLangOptions().CUDA) {
3823 if (Config) {
3824 // CUDA: Kernel calls must be to global functions
3825 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3826 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3827 << FDecl->getName() << Fn->getSourceRange());
3828
3829 // CUDA: Kernel function must have 'void' return type
3830 if (!FuncT->getResultType()->isVoidType())
3831 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3832 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003833 } else {
3834 // CUDA: Calls to global functions must be configured
3835 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3836 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3837 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003838 }
3839 }
3840
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003841 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003842 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003843 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003844 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003845 return ExprError();
3846
Chris Lattner925e60d2007-12-28 05:29:59 +00003847 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003848 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003849 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003850
Douglas Gregor72564e72009-02-26 23:50:07 +00003851 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003852 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003853 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003854 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003855 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003856 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003857
Douglas Gregor74734d52009-04-02 15:37:10 +00003858 if (FDecl) {
3859 // Check if we have too few/too many template arguments, based
3860 // on our knowledge of the function definition.
3861 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003862 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003863 const FunctionProtoType *Proto
3864 = Def->getType()->getAs<FunctionProtoType>();
3865 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003866 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3867 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003868 }
Douglas Gregor46542412010-10-25 20:39:23 +00003869
3870 // If the function we're calling isn't a function prototype, but we have
3871 // a function prototype from a prior declaratiom, use that prototype.
3872 if (!FDecl->hasPrototype())
3873 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003874 }
3875
Steve Naroffb291ab62007-08-28 23:30:39 +00003876 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003877 for (unsigned i = 0; i != NumArgs; i++) {
3878 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003879
3880 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003881 InitializedEntity Entity
3882 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003883 Proto->getArgType(i),
3884 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003885 ExprResult ArgE = PerformCopyInitialization(Entity,
3886 SourceLocation(),
3887 Owned(Arg));
3888 if (ArgE.isInvalid())
3889 return true;
3890
3891 Arg = ArgE.takeAs<Expr>();
3892
3893 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003894 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3895
3896 if (ArgE.isInvalid())
3897 return true;
3898
3899 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003900 }
3901
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003902 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3903 Arg->getType(),
3904 PDiag(diag::err_call_incomplete_argument)
3905 << Arg->getSourceRange()))
3906 return ExprError();
3907
Chris Lattner925e60d2007-12-28 05:29:59 +00003908 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003910 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003911
Douglas Gregor88a35142008-12-22 05:46:06 +00003912 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3913 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003914 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3915 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003916
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003917 // Check for sentinels
3918 if (NDecl)
3919 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Chris Lattner59907c42007-08-10 20:18:51 +00003921 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003922 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003923 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003924 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003925
John McCall8e10f3b2011-02-26 05:39:39 +00003926 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003927 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003928 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003929 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003930 return ExprError();
3931 }
Chris Lattner59907c42007-08-10 20:18:51 +00003932
John McCall9ae2f072010-08-23 23:25:46 +00003933 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003934}
3935
John McCall60d7b3a2010-08-24 06:29:42 +00003936ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003937Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003938 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003939 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003940 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003941 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003942
3943 TypeSourceInfo *TInfo;
3944 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3945 if (!TInfo)
3946 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3947
John McCall9ae2f072010-08-23 23:25:46 +00003948 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003949}
3950
John McCall60d7b3a2010-08-24 06:29:42 +00003951ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003952Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00003953 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003954 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003955
Eli Friedman6223c222008-05-20 05:22:08 +00003956 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003957 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3958 PDiag(diag::err_illegal_decl_array_incomplete_type)
3959 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003960 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003961 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003962 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003963 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00003964 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003965 } else if (!literalType->isDependentType() &&
3966 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003967 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003968 << SourceRange(LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003969 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003970 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003971
Douglas Gregor99a2e602009-12-16 01:38:02 +00003972 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003973 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003974 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003975 = InitializationKind::CreateCStyleCast(LParenLoc,
3976 SourceRange(LParenLoc, RParenLoc));
Richard Trieuccd891a2011-09-09 01:45:06 +00003977 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003978 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00003979 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003980 &literalType);
3981 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003982 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00003983 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003984
Chris Lattner371f2582008-12-04 23:50:19 +00003985 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003986 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00003987 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003988 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003989 }
Eli Friedman08544622009-12-22 02:35:53 +00003990
John McCallf89e55a2010-11-18 06:31:45 +00003991 // In C, compound literals are l-values for some reason.
3992 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3993
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003994 return MaybeBindToTemporary(
3995 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00003996 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003997}
3998
John McCall60d7b3a2010-08-24 06:29:42 +00003999ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004000Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004001 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004002 unsigned NumInit = InitArgList.size();
4003 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004004
John McCall3c3b7f92011-10-25 17:37:35 +00004005 // Immediately handle non-overload placeholders. Overloads can be
4006 // resolved contextually, but everything else here can't.
4007 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004008 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004009 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4010
4011 // Ignore failures; dropping the entire initializer list because
4012 // of one failure would be terrible for indexing/etc.
4013 if (result.isInvalid()) continue;
4014
4015 InitList[I] = result.take();
4016 }
4017 }
4018
Steve Naroff08d92e42007-09-15 18:49:24 +00004019 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004020 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004021
Ted Kremenek709210f2010-04-13 23:39:13 +00004022 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4023 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004024 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004025 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004026}
4027
John McCalldc05b112011-09-10 01:16:55 +00004028/// Do an explicit extend of the given block pointer if we're in ARC.
4029static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4030 assert(E.get()->getType()->isBlockPointerType());
4031 assert(E.get()->isRValue());
4032
4033 // Only do this in an r-value context.
4034 if (!S.getLangOptions().ObjCAutoRefCount) return;
4035
4036 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004037 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004038 /*base path*/ 0, VK_RValue);
4039 S.ExprNeedsCleanups = true;
4040}
4041
4042/// Prepare a conversion of the given expression to an ObjC object
4043/// pointer type.
4044CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4045 QualType type = E.get()->getType();
4046 if (type->isObjCObjectPointerType()) {
4047 return CK_BitCast;
4048 } else if (type->isBlockPointerType()) {
4049 maybeExtendBlockObject(*this, E);
4050 return CK_BlockPointerToObjCPointerCast;
4051 } else {
4052 assert(type->isPointerType());
4053 return CK_CPointerToObjCPointerCast;
4054 }
4055}
4056
John McCallf3ea8cf2010-11-14 08:17:51 +00004057/// Prepares for a scalar cast, performing all the necessary stages
4058/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004059CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004060 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4061 // Also, callers should have filtered out the invalid cases with
4062 // pointers. Everything else should be possible.
4063
John Wiegley429bb272011-04-08 18:41:53 +00004064 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004065 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004066 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004067
John McCall1d9b3b22011-09-09 05:25:32 +00004068 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004069 case Type::STK_MemberPointer:
4070 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004071
John McCall1d9b3b22011-09-09 05:25:32 +00004072 case Type::STK_CPointer:
4073 case Type::STK_BlockPointer:
4074 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004075 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004076 case Type::STK_CPointer:
4077 return CK_BitCast;
4078 case Type::STK_BlockPointer:
4079 return (SrcKind == Type::STK_BlockPointer
4080 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4081 case Type::STK_ObjCObjectPointer:
4082 if (SrcKind == Type::STK_ObjCObjectPointer)
4083 return CK_BitCast;
4084 else if (SrcKind == Type::STK_CPointer)
4085 return CK_CPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00004086 else {
John McCalla180f042011-10-06 23:25:11 +00004087 maybeExtendBlockObject(*this, Src);
John McCall1d9b3b22011-09-09 05:25:32 +00004088 return CK_BlockPointerToObjCPointerCast;
John McCalldc05b112011-09-10 01:16:55 +00004089 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004090 case Type::STK_Bool:
4091 return CK_PointerToBoolean;
4092 case Type::STK_Integral:
4093 return CK_PointerToIntegral;
4094 case Type::STK_Floating:
4095 case Type::STK_FloatingComplex:
4096 case Type::STK_IntegralComplex:
4097 case Type::STK_MemberPointer:
4098 llvm_unreachable("illegal cast from pointer");
4099 }
4100 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004101
John McCalldaa8e4e2010-11-15 09:13:47 +00004102 case Type::STK_Bool: // casting from bool is like casting from an integer
4103 case Type::STK_Integral:
4104 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004105 case Type::STK_CPointer:
4106 case Type::STK_ObjCObjectPointer:
4107 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004108 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004109 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004110 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004111 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004112 case Type::STK_Bool:
4113 return CK_IntegralToBoolean;
4114 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004115 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004116 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004117 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004118 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004119 Src = ImpCastExprToType(Src.take(),
4120 DestTy->castAs<ComplexType>()->getElementType(),
4121 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004122 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004123 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004124 Src = ImpCastExprToType(Src.take(),
4125 DestTy->castAs<ComplexType>()->getElementType(),
4126 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004127 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004128 case Type::STK_MemberPointer:
4129 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004130 }
4131 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004132
John McCalldaa8e4e2010-11-15 09:13:47 +00004133 case Type::STK_Floating:
4134 switch (DestTy->getScalarTypeKind()) {
4135 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004136 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004137 case Type::STK_Bool:
4138 return CK_FloatingToBoolean;
4139 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004140 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004141 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004142 Src = ImpCastExprToType(Src.take(),
4143 DestTy->castAs<ComplexType>()->getElementType(),
4144 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004145 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004146 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004147 Src = ImpCastExprToType(Src.take(),
4148 DestTy->castAs<ComplexType>()->getElementType(),
4149 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004150 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004151 case Type::STK_CPointer:
4152 case Type::STK_ObjCObjectPointer:
4153 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004154 llvm_unreachable("valid float->pointer cast?");
4155 case Type::STK_MemberPointer:
4156 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004157 }
4158 break;
4159
John McCalldaa8e4e2010-11-15 09:13:47 +00004160 case Type::STK_FloatingComplex:
4161 switch (DestTy->getScalarTypeKind()) {
4162 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004163 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004164 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004165 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004166 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004167 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4168 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004169 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004170 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004171 return CK_FloatingCast;
4172 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004173 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004174 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004175 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004176 Src = ImpCastExprToType(Src.take(),
4177 SrcTy->castAs<ComplexType>()->getElementType(),
4178 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004179 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004180 case Type::STK_CPointer:
4181 case Type::STK_ObjCObjectPointer:
4182 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004183 llvm_unreachable("valid complex float->pointer cast?");
4184 case Type::STK_MemberPointer:
4185 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004186 }
4187 break;
4188
John McCalldaa8e4e2010-11-15 09:13:47 +00004189 case Type::STK_IntegralComplex:
4190 switch (DestTy->getScalarTypeKind()) {
4191 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004192 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004193 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004194 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004195 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004196 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4197 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004198 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004199 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004200 return CK_IntegralCast;
4201 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004202 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004203 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004204 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004205 Src = ImpCastExprToType(Src.take(),
4206 SrcTy->castAs<ComplexType>()->getElementType(),
4207 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004208 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004209 case Type::STK_CPointer:
4210 case Type::STK_ObjCObjectPointer:
4211 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004212 llvm_unreachable("valid complex int->pointer cast?");
4213 case Type::STK_MemberPointer:
4214 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004215 }
4216 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004217 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004218
John McCallf3ea8cf2010-11-14 08:17:51 +00004219 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004220}
4221
Anders Carlssonc3516322009-10-16 02:48:28 +00004222bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004223 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004224 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004225
Anders Carlssona64db8f2007-11-27 05:51:55 +00004226 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004227 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004228 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004229 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004230 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004231 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004232 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004233 } else
4234 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004235 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004236 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004237
John McCall2de56d12010-08-25 11:45:40 +00004238 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004239 return false;
4240}
4241
John Wiegley429bb272011-04-08 18:41:53 +00004242ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4243 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004244 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004245
Anders Carlsson16a89042009-10-16 05:23:41 +00004246 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004247
Nate Begeman9b10da62009-06-27 22:05:55 +00004248 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4249 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004250 // In OpenCL, casts between vectors of different types are not allowed.
4251 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004252 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004253 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4254 || (getLangOptions().OpenCL &&
4255 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004256 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004257 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004258 return ExprError();
4259 }
John McCall2de56d12010-08-25 11:45:40 +00004260 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004261 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004262 }
4263
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004264 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004265 // conversion will take place first from scalar to elt type, and then
4266 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004267 if (SrcTy->isPointerType())
4268 return Diag(R.getBegin(),
4269 diag::err_invalid_conversion_between_vector_and_scalar)
4270 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004271
4272 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004273 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004274 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004275 if (CastExprRes.isInvalid())
4276 return ExprError();
4277 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004278
John McCall2de56d12010-08-25 11:45:40 +00004279 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004280 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004281}
4282
John McCall60d7b3a2010-08-24 06:29:42 +00004283ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004284Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4285 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004286 SourceLocation RParenLoc, Expr *CastExpr) {
4287 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004288 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004289
Richard Trieuccd891a2011-09-09 01:45:06 +00004290 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004291 if (D.isInvalidType())
4292 return ExprError();
4293
4294 if (getLangOptions().CPlusPlus) {
4295 // Check that there are no default arguments (C++ only).
4296 CheckExtraCXXDefaultArguments(D);
4297 }
4298
John McCalle82247a2011-10-01 05:17:03 +00004299 checkUnusedDeclAttributes(D);
4300
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004301 QualType castType = castTInfo->getType();
4302 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004303
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004304 bool isVectorLiteral = false;
4305
4306 // Check for an altivec or OpenCL literal,
4307 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004308 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4309 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser37c31c22011-09-21 18:28:29 +00004310 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4311 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004312 if (PLE && PLE->getNumExprs() == 0) {
4313 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4314 return ExprError();
4315 }
4316 if (PE || PLE->getNumExprs() == 1) {
4317 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4318 if (!E->getType()->isVectorType())
4319 isVectorLiteral = true;
4320 }
4321 else
4322 isVectorLiteral = true;
4323 }
4324
4325 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4326 // then handle it as such.
4327 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004328 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004329
Nate Begeman2ef13e52009-08-10 23:49:36 +00004330 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004331 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4332 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004333 if (isa<ParenListExpr>(CastExpr)) {
4334 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004335 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004336 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004337 }
John McCallb042fdf2010-01-15 18:56:44 +00004338
Richard Trieuccd891a2011-09-09 01:45:06 +00004339 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004340}
4341
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004342ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4343 SourceLocation RParenLoc, Expr *E,
4344 TypeSourceInfo *TInfo) {
4345 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4346 "Expected paren or paren list expression");
4347
4348 Expr **exprs;
4349 unsigned numExprs;
4350 Expr *subExpr;
4351 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4352 exprs = PE->getExprs();
4353 numExprs = PE->getNumExprs();
4354 } else {
4355 subExpr = cast<ParenExpr>(E)->getSubExpr();
4356 exprs = &subExpr;
4357 numExprs = 1;
4358 }
4359
4360 QualType Ty = TInfo->getType();
4361 assert(Ty->isVectorType() && "Expected vector type");
4362
Chris Lattner5f9e2722011-07-23 10:55:15 +00004363 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004364 const VectorType *VTy = Ty->getAs<VectorType>();
4365 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4366
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004367 // '(...)' form of vector initialization in AltiVec: the number of
4368 // initializers must be one or must match the size of the vector.
4369 // If a single value is specified in the initializer then it will be
4370 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004371 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004372 // The number of initializers must be one or must match the size of the
4373 // vector. If a single value is specified in the initializer then it will
4374 // be replicated to all the components of the vector
4375 if (numExprs == 1) {
4376 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004377 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4378 if (Literal.isInvalid())
4379 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004380 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004381 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004382 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4383 }
4384 else if (numExprs < numElems) {
4385 Diag(E->getExprLoc(),
4386 diag::err_incorrect_number_of_vector_initializers);
4387 return ExprError();
4388 }
4389 else
4390 for (unsigned i = 0, e = numExprs; i != e; ++i)
4391 initExprs.push_back(exprs[i]);
4392 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004393 else {
4394 // For OpenCL, when the number of initializers is a single value,
4395 // it will be replicated to all components of the vector.
4396 if (getLangOptions().OpenCL &&
4397 VTy->getVectorKind() == VectorType::GenericVector &&
4398 numExprs == 1) {
4399 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004400 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4401 if (Literal.isInvalid())
4402 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004403 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004404 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004405 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4406 }
4407
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004408 for (unsigned i = 0, e = numExprs; i != e; ++i)
4409 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004410 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004411 // FIXME: This means that pretty-printing the final AST will produce curly
4412 // braces instead of the original commas.
4413 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4414 &initExprs[0],
4415 initExprs.size(), RParenLoc);
4416 initE->setType(Ty);
4417 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4418}
4419
Nate Begeman2ef13e52009-08-10 23:49:36 +00004420/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4421/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004422ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004423Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4424 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004425 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004426 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004427
John McCall60d7b3a2010-08-24 06:29:42 +00004428 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Nate Begeman2ef13e52009-08-10 23:49:36 +00004430 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004431 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4432 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004433
John McCall9ae2f072010-08-23 23:25:46 +00004434 if (Result.isInvalid()) return ExprError();
4435
4436 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004437}
4438
John McCall60d7b3a2010-08-24 06:29:42 +00004439ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuccd891a2011-09-09 01:45:06 +00004440 SourceLocation R,
4441 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004442 unsigned nexprs = Val.size();
4443 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004444 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4445 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004446 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004447 expr = new (Context) ParenExpr(L, R, exprs[0]);
4448 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004449 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4450 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004451 return Owned(expr);
4452}
4453
Chandler Carruth82214a82011-02-18 23:54:50 +00004454/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004455/// constant and the other is not a pointer. Returns true if a diagnostic is
4456/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004457bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004458 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004459 Expr *NullExpr = LHSExpr;
4460 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004461 Expr::NullPointerConstantKind NullKind =
4462 NullExpr->isNullPointerConstant(Context,
4463 Expr::NPC_ValueDependentIsNotNull);
4464
4465 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004466 NullExpr = RHSExpr;
4467 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004468 NullKind =
4469 NullExpr->isNullPointerConstant(Context,
4470 Expr::NPC_ValueDependentIsNotNull);
4471 }
4472
4473 if (NullKind == Expr::NPCK_NotNull)
4474 return false;
4475
4476 if (NullKind == Expr::NPCK_ZeroInteger) {
4477 // In this case, check to make sure that we got here from a "NULL"
4478 // string in the source code.
4479 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004480 SourceLocation loc = NullExpr->getExprLoc();
4481 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004482 return false;
4483 }
4484
4485 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4486 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4487 << NonPointerExpr->getType() << DiagType
4488 << NonPointerExpr->getSourceRange();
4489 return true;
4490}
4491
Richard Trieu26f96072011-09-02 01:51:02 +00004492/// \brief Return false if the condition expression is valid, true otherwise.
4493static bool checkCondition(Sema &S, Expr *Cond) {
4494 QualType CondTy = Cond->getType();
4495
4496 // C99 6.5.15p2
4497 if (CondTy->isScalarType()) return false;
4498
4499 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4500 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4501 return false;
4502
4503 // Emit the proper error message.
4504 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4505 diag::err_typecheck_cond_expect_scalar :
4506 diag::err_typecheck_cond_expect_scalar_or_vector)
4507 << CondTy;
4508 return true;
4509}
4510
4511/// \brief Return false if the two expressions can be converted to a vector,
4512/// true otherwise
4513static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4514 ExprResult &RHS,
4515 QualType CondTy) {
4516 // Both operands should be of scalar type.
4517 if (!LHS.get()->getType()->isScalarType()) {
4518 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4519 << CondTy;
4520 return true;
4521 }
4522 if (!RHS.get()->getType()->isScalarType()) {
4523 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4524 << CondTy;
4525 return true;
4526 }
4527
4528 // Implicity convert these scalars to the type of the condition.
4529 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4530 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4531 return false;
4532}
4533
4534/// \brief Handle when one or both operands are void type.
4535static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4536 ExprResult &RHS) {
4537 Expr *LHSExpr = LHS.get();
4538 Expr *RHSExpr = RHS.get();
4539
4540 if (!LHSExpr->getType()->isVoidType())
4541 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4542 << RHSExpr->getSourceRange();
4543 if (!RHSExpr->getType()->isVoidType())
4544 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4545 << LHSExpr->getSourceRange();
4546 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4547 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4548 return S.Context.VoidTy;
4549}
4550
4551/// \brief Return false if the NullExpr can be promoted to PointerTy,
4552/// true otherwise.
4553static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4554 QualType PointerTy) {
4555 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4556 !NullExpr.get()->isNullPointerConstant(S.Context,
4557 Expr::NPC_ValueDependentIsNull))
4558 return true;
4559
4560 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4561 return false;
4562}
4563
4564/// \brief Checks compatibility between two pointers and return the resulting
4565/// type.
4566static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4567 ExprResult &RHS,
4568 SourceLocation Loc) {
4569 QualType LHSTy = LHS.get()->getType();
4570 QualType RHSTy = RHS.get()->getType();
4571
4572 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4573 // Two identical pointers types are always compatible.
4574 return LHSTy;
4575 }
4576
4577 QualType lhptee, rhptee;
4578
4579 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004580 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4581 lhptee = LHSBTy->getPointeeType();
4582 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004583 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004584 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4585 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004586 }
4587
4588 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4589 rhptee.getUnqualifiedType())) {
4590 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4591 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4592 << RHS.get()->getSourceRange();
4593 // In this situation, we assume void* type. No especially good
4594 // reason, but this is what gcc does, and we do have to pick
4595 // to get a consistent AST.
4596 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4597 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4598 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4599 return incompatTy;
4600 }
4601
4602 // The pointer types are compatible.
4603 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4604 // differently qualified versions of compatible types, the result type is
4605 // a pointer to an appropriately qualified version of the *composite*
4606 // type.
4607 // FIXME: Need to calculate the composite type.
4608 // FIXME: Need to add qualifiers
4609
4610 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4611 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4612 return LHSTy;
4613}
4614
4615/// \brief Return the resulting type when the operands are both block pointers.
4616static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4617 ExprResult &LHS,
4618 ExprResult &RHS,
4619 SourceLocation Loc) {
4620 QualType LHSTy = LHS.get()->getType();
4621 QualType RHSTy = RHS.get()->getType();
4622
4623 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4624 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4625 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4626 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4627 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4628 return destType;
4629 }
4630 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4631 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4632 << RHS.get()->getSourceRange();
4633 return QualType();
4634 }
4635
4636 // We have 2 block pointer types.
4637 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4638}
4639
4640/// \brief Return the resulting type when the operands are both pointers.
4641static QualType
4642checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4643 ExprResult &RHS,
4644 SourceLocation Loc) {
4645 // get the pointer types
4646 QualType LHSTy = LHS.get()->getType();
4647 QualType RHSTy = RHS.get()->getType();
4648
4649 // get the "pointed to" types
4650 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4651 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4652
4653 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4654 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4655 // Figure out necessary qualifiers (C99 6.5.15p6)
4656 QualType destPointee
4657 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4658 QualType destType = S.Context.getPointerType(destPointee);
4659 // Add qualifiers if necessary.
4660 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4661 // Promote to void*.
4662 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4663 return destType;
4664 }
4665 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4666 QualType destPointee
4667 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4668 QualType destType = S.Context.getPointerType(destPointee);
4669 // Add qualifiers if necessary.
4670 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4671 // Promote to void*.
4672 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4673 return destType;
4674 }
4675
4676 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4677}
4678
4679/// \brief Return false if the first expression is not an integer and the second
4680/// expression is not a pointer, true otherwise.
4681static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4682 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004683 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004684 if (!PointerExpr->getType()->isPointerType() ||
4685 !Int.get()->getType()->isIntegerType())
4686 return false;
4687
Richard Trieuccd891a2011-09-09 01:45:06 +00004688 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4689 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004690
4691 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4692 << Expr1->getType() << Expr2->getType()
4693 << Expr1->getSourceRange() << Expr2->getSourceRange();
4694 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4695 CK_IntegralToPointer);
4696 return true;
4697}
4698
Richard Trieu33fc7572011-09-06 20:06:39 +00004699/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4700/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004701/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004702QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4703 ExprResult &RHS, ExprValueKind &VK,
4704 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004705 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004706
Richard Trieu33fc7572011-09-06 20:06:39 +00004707 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4708 if (!LHSResult.isUsable()) return QualType();
4709 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004710
Richard Trieu33fc7572011-09-06 20:06:39 +00004711 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4712 if (!RHSResult.isUsable()) return QualType();
4713 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004714
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004715 // C++ is sufficiently different to merit its own checker.
4716 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004717 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004718
4719 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004720 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004721
John Wiegley429bb272011-04-08 18:41:53 +00004722 Cond = UsualUnaryConversions(Cond.take());
4723 if (Cond.isInvalid())
4724 return QualType();
4725 LHS = UsualUnaryConversions(LHS.take());
4726 if (LHS.isInvalid())
4727 return QualType();
4728 RHS = UsualUnaryConversions(RHS.take());
4729 if (RHS.isInvalid())
4730 return QualType();
4731
4732 QualType CondTy = Cond.get()->getType();
4733 QualType LHSTy = LHS.get()->getType();
4734 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004735
Reid Spencer5f016e22007-07-11 17:01:13 +00004736 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004737 if (checkCondition(*this, Cond.get()))
4738 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004739
Chris Lattner70d67a92008-01-06 22:42:25 +00004740 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004741 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004742 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004743
Nate Begeman6155d732010-09-20 22:41:17 +00004744 // OpenCL: If the condition is a vector, and both operands are scalar,
4745 // attempt to implicity convert them to the vector type to act like the
4746 // built in select.
Richard Trieu26f96072011-09-02 01:51:02 +00004747 if (getLangOptions().OpenCL && CondTy->isVectorType())
4748 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004749 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004750
Chris Lattner70d67a92008-01-06 22:42:25 +00004751 // If both operands have arithmetic type, do the usual arithmetic conversions
4752 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004753 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4754 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004755 if (LHS.isInvalid() || RHS.isInvalid())
4756 return QualType();
4757 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004758 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004759
Chris Lattner70d67a92008-01-06 22:42:25 +00004760 // If both operands are the same structure or union type, the result is that
4761 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004762 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4763 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004764 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004765 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004766 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004767 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004768 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004769 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004770
Chris Lattner70d67a92008-01-06 22:42:25 +00004771 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004772 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004773 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004774 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004775 }
Richard Trieu26f96072011-09-02 01:51:02 +00004776
Steve Naroffb6d54e52008-01-08 01:11:38 +00004777 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4778 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004779 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4780 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004781
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004782 // All objective-c pointer type analysis is done here.
4783 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4784 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004785 if (LHS.isInvalid() || RHS.isInvalid())
4786 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004787 if (!compositeType.isNull())
4788 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004789
4790
Steve Naroff7154a772009-07-01 14:36:47 +00004791 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004792 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4793 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4794 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004795
Steve Naroff7154a772009-07-01 14:36:47 +00004796 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004797 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4798 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4799 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004800
John McCall404cd162010-11-13 01:35:44 +00004801 // GCC compatibility: soften pointer/integer mismatch. Note that
4802 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004803 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4804 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004805 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004806 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4807 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004808 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004809
Chandler Carruth82214a82011-02-18 23:54:50 +00004810 // Emit a better diagnostic if one of the expressions is a null pointer
4811 // constant and the other is not a pointer type. In this case, the user most
4812 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004813 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004814 return QualType();
4815
Chris Lattner70d67a92008-01-06 22:42:25 +00004816 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004817 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004818 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4819 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004820 return QualType();
4821}
4822
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004823/// FindCompositeObjCPointerType - Helper method to find composite type of
4824/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004825QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004826 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004827 QualType LHSTy = LHS.get()->getType();
4828 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004829
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004830 // Handle things like Class and struct objc_class*. Here we case the result
4831 // to the pseudo-builtin, because that will be implicitly cast back to the
4832 // redefinition type if an attempt is made to access its fields.
4833 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004834 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004835 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004836 return LHSTy;
4837 }
4838 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004839 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004840 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004841 return RHSTy;
4842 }
4843 // And the same for struct objc_object* / id
4844 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004845 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004846 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004847 return LHSTy;
4848 }
4849 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004850 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004851 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004852 return RHSTy;
4853 }
4854 // And the same for struct objc_selector* / SEL
4855 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004856 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004857 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004858 return LHSTy;
4859 }
4860 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004861 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004862 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004863 return RHSTy;
4864 }
4865 // Check constraints for Objective-C object pointers types.
4866 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004867
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004868 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4869 // Two identical object pointer types are always compatible.
4870 return LHSTy;
4871 }
John McCall1d9b3b22011-09-09 05:25:32 +00004872 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4873 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004874 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004875
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004876 // If both operands are interfaces and either operand can be
4877 // assigned to the other, use that type as the composite
4878 // type. This allows
4879 // xxx ? (A*) a : (B*) b
4880 // where B is a subclass of A.
4881 //
4882 // Additionally, as for assignment, if either type is 'id'
4883 // allow silent coercion. Finally, if the types are
4884 // incompatible then make sure to use 'id' as the composite
4885 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004886
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004887 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4888 // It could return the composite type.
4889 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4890 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4891 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4892 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4893 } else if ((LHSTy->isObjCQualifiedIdType() ||
4894 RHSTy->isObjCQualifiedIdType()) &&
4895 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4896 // Need to handle "id<xx>" explicitly.
4897 // GCC allows qualified id and any Objective-C type to devolve to
4898 // id. Currently localizing to here until clear this should be
4899 // part of ObjCQualifiedIdTypesAreCompatible.
4900 compositeType = Context.getObjCIdType();
4901 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4902 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004903 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004904 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4905 ;
4906 else {
4907 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4908 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004910 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004911 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4912 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004913 return incompatTy;
4914 }
4915 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004916 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4917 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004918 return compositeType;
4919 }
4920 // Check Objective-C object pointer types and 'void *'
4921 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4922 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4923 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4924 QualType destPointee
4925 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4926 QualType destType = Context.getPointerType(destPointee);
4927 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004928 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004929 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004930 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004931 return destType;
4932 }
4933 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4934 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4935 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4936 QualType destPointee
4937 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4938 QualType destType = Context.getPointerType(destPointee);
4939 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004940 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004941 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004942 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004943 return destType;
4944 }
4945 return QualType();
4946}
4947
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004948/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004949/// ParenRange in parentheses.
4950static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004951 const PartialDiagnostic &Note,
4952 SourceRange ParenRange) {
4953 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4954 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4955 EndLoc.isValid()) {
4956 Self.Diag(Loc, Note)
4957 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4958 << FixItHint::CreateInsertion(EndLoc, ")");
4959 } else {
4960 // We can't display the parentheses, so just show the bare note.
4961 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004962 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004963}
4964
4965static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4966 return Opc >= BO_Mul && Opc <= BO_Shr;
4967}
4968
Hans Wennborg2f072b42011-06-09 17:06:51 +00004969/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4970/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00004971/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4972/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00004973static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00004974 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004975 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4976 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004977 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00004978 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004979
4980 // Built-in binary operator.
4981 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4982 if (IsArithmeticOp(OP->getOpcode())) {
4983 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00004984 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00004985 return true;
4986 }
4987 }
4988
4989 // Overloaded operator.
4990 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4991 if (Call->getNumArgs() != 2)
4992 return false;
4993
4994 // Make sure this is really a binary operator that is safe to pass into
4995 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4996 OverloadedOperatorKind OO = Call->getOperator();
4997 if (OO < OO_Plus || OO > OO_Arrow)
4998 return false;
4999
5000 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5001 if (IsArithmeticOp(OpKind)) {
5002 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005003 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005004 return true;
5005 }
5006 }
5007
5008 return false;
5009}
5010
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005011static bool IsLogicOp(BinaryOperatorKind Opc) {
5012 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5013}
5014
Hans Wennborg2f072b42011-06-09 17:06:51 +00005015/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5016/// or is a logical expression such as (x==y) which has int type, but is
5017/// commonly interpreted as boolean.
5018static bool ExprLooksBoolean(Expr *E) {
5019 E = E->IgnoreParenImpCasts();
5020
5021 if (E->getType()->isBooleanType())
5022 return true;
5023 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5024 return IsLogicOp(OP->getOpcode());
5025 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5026 return OP->getOpcode() == UO_LNot;
5027
5028 return false;
5029}
5030
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005031/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5032/// and binary operator are mixed in a way that suggests the programmer assumed
5033/// the conditional operator has higher precedence, for example:
5034/// "int x = a + someBinaryCondition ? 1 : 2".
5035static void DiagnoseConditionalPrecedence(Sema &Self,
5036 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005037 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005038 Expr *LHSExpr,
5039 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005040 BinaryOperatorKind CondOpcode;
5041 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005042
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005043 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005044 return;
5045 if (!ExprLooksBoolean(CondRHS))
5046 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005047
Hans Wennborg2f072b42011-06-09 17:06:51 +00005048 // The condition is an arithmetic binary expression, with a right-
5049 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005050
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005051 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005052 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005053 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005054
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005055 SuggestParentheses(Self, OpLoc,
5056 Self.PDiag(diag::note_precedence_conditional_silence)
5057 << BinaryOperator::getOpcodeStr(CondOpcode),
5058 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005059
5060 SuggestParentheses(Self, OpLoc,
5061 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005062 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005063}
5064
Steve Narofff69936d2007-09-16 03:34:24 +00005065/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005066/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005067ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005068 SourceLocation ColonLoc,
5069 Expr *CondExpr, Expr *LHSExpr,
5070 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005071 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5072 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005073 OpaqueValueExpr *opaqueValue = 0;
5074 Expr *commonExpr = 0;
5075 if (LHSExpr == 0) {
5076 commonExpr = CondExpr;
5077
5078 // We usually want to apply unary conversions *before* saving, except
5079 // in the special case of a C++ l-value conditional.
5080 if (!(getLangOptions().CPlusPlus
5081 && !commonExpr->isTypeDependent()
5082 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5083 && commonExpr->isGLValue()
5084 && commonExpr->isOrdinaryOrBitFieldObject()
5085 && RHSExpr->isOrdinaryOrBitFieldObject()
5086 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005087 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5088 if (commonRes.isInvalid())
5089 return ExprError();
5090 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005091 }
5092
5093 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5094 commonExpr->getType(),
5095 commonExpr->getValueKind(),
5096 commonExpr->getObjectKind());
5097 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005098 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005099
John McCallf89e55a2010-11-18 06:31:45 +00005100 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005101 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005102 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5103 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005104 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005105 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5106 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005107 return ExprError();
5108
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005109 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5110 RHS.get());
5111
John McCall56ca35d2011-02-17 10:25:35 +00005112 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005113 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5114 LHS.take(), ColonLoc,
5115 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005116
5117 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005118 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005119 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5120 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005121}
5122
John McCalle4be87e2011-01-31 23:13:11 +00005123// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005124// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005125// routine is it effectively iqnores the qualifiers on the top level pointee.
5126// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5127// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005128static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005129checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5130 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5131 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005132
Reid Spencer5f016e22007-07-11 17:01:13 +00005133 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005134 const Type *lhptee, *rhptee;
5135 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005136 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5137 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005138
John McCalle4be87e2011-01-31 23:13:11 +00005139 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005140
5141 // C99 6.5.16.1p1: This following citation is common to constraints
5142 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5143 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005144 Qualifiers lq;
5145
John McCallf85e1932011-06-15 23:02:42 +00005146 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5147 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5148 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5149 // Ignore lifetime for further calculation.
5150 lhq.removeObjCLifetime();
5151 rhq.removeObjCLifetime();
5152 }
5153
John McCall86c05f32011-02-01 00:10:29 +00005154 if (!lhq.compatiblyIncludes(rhq)) {
5155 // Treat address-space mismatches as fatal. TODO: address subspaces
5156 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5157 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5158
John McCallf85e1932011-06-15 23:02:42 +00005159 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005160 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005161 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5162 .compatiblyIncludes(
5163 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005164 && (lhptee->isVoidType() || rhptee->isVoidType()))
5165 ; // keep old
5166
John McCallf85e1932011-06-15 23:02:42 +00005167 // Treat lifetime mismatches as fatal.
5168 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5169 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5170
John McCall86c05f32011-02-01 00:10:29 +00005171 // For GCC compatibility, other qualifier mismatches are treated
5172 // as still compatible in C.
5173 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5174 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005175
Mike Stumpeed9cac2009-02-19 03:04:26 +00005176 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5177 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005178 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005179 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005180 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005181 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005182
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005183 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005184 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005185 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005186 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005187
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005188 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005189 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005190 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005191
5192 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005193 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005194 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005195 }
John McCall86c05f32011-02-01 00:10:29 +00005196
Mike Stumpeed9cac2009-02-19 03:04:26 +00005197 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005198 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005199 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5200 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005201 // Check if the pointee types are compatible ignoring the sign.
5202 // We explicitly check for char so that we catch "char" vs
5203 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005204 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005205 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005206 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005207 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005208
Chris Lattner6a2b9262009-10-17 20:33:28 +00005209 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005210 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005211 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005212 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005213
John McCall86c05f32011-02-01 00:10:29 +00005214 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005215 // Types are compatible ignoring the sign. Qualifier incompatibility
5216 // takes priority over sign incompatibility because the sign
5217 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005218 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005219 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005220
John McCalle4be87e2011-01-31 23:13:11 +00005221 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005222 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005223
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005224 // If we are a multi-level pointer, it's possible that our issue is simply
5225 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5226 // the eventual target type is the same and the pointers have the same
5227 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005228 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005229 do {
John McCall86c05f32011-02-01 00:10:29 +00005230 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5231 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005232 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005233
John McCall86c05f32011-02-01 00:10:29 +00005234 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005235 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005236 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005237
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005238 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005239 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005240 }
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005241 if (!S.getLangOptions().CPlusPlus &&
5242 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5243 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005244 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005245}
5246
John McCalle4be87e2011-01-31 23:13:11 +00005247/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005248/// block pointer types are compatible or whether a block and normal pointer
5249/// are compatible. It is more restrict than comparing two function pointer
5250// types.
John McCalle4be87e2011-01-31 23:13:11 +00005251static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005252checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5253 QualType RHSType) {
5254 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5255 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005256
Steve Naroff1c7d0672008-09-04 15:10:53 +00005257 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005258
Steve Naroff1c7d0672008-09-04 15:10:53 +00005259 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005260 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5261 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005262
John McCalle4be87e2011-01-31 23:13:11 +00005263 // In C++, the types have to match exactly.
5264 if (S.getLangOptions().CPlusPlus)
5265 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005266
John McCalle4be87e2011-01-31 23:13:11 +00005267 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005268
Steve Naroff1c7d0672008-09-04 15:10:53 +00005269 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005270 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5271 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005272
Richard Trieu1da27a12011-09-06 20:21:22 +00005273 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005274 return Sema::IncompatibleBlockPointer;
5275
Steve Naroff1c7d0672008-09-04 15:10:53 +00005276 return ConvTy;
5277}
5278
John McCalle4be87e2011-01-31 23:13:11 +00005279/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005280/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005281static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005282checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5283 QualType RHSType) {
5284 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5285 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005286
Richard Trieu1da27a12011-09-06 20:21:22 +00005287 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005288 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005289 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5290 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005291 return Sema::IncompatiblePointer;
5292 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005293 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005294 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005295 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5296 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005297 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005298 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005299 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005300 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5301 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005302
John McCalle4be87e2011-01-31 23:13:11 +00005303 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5304 return Sema::CompatiblePointerDiscardsQualifiers;
5305
Richard Trieu1da27a12011-09-06 20:21:22 +00005306 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005307 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005308 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005309 return Sema::IncompatibleObjCQualifiedId;
5310 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005311}
5312
John McCall1c23e912010-11-16 02:32:08 +00005313Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005314Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005315 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005316 // Fake up an opaque expression. We don't actually care about what
5317 // cast operations are required, so if CheckAssignmentConstraints
5318 // adds casts to this they'll be wasted, but fortunately that doesn't
5319 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005320 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5321 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005322 CastKind K = CK_Invalid;
5323
Richard Trieu1da27a12011-09-06 20:21:22 +00005324 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005325}
5326
Mike Stumpeed9cac2009-02-19 03:04:26 +00005327/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5328/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005329/// pointers. Here are some objectionable examples that GCC considers warnings:
5330///
5331/// int a, *pint;
5332/// short *pshort;
5333/// struct foo *pfoo;
5334///
5335/// pint = pshort; // warning: assignment from incompatible pointer type
5336/// a = pint; // warning: assignment makes integer from pointer without a cast
5337/// pint = a; // warning: assignment makes pointer from integer without a cast
5338/// pint = pfoo; // warning: assignment from incompatible pointer type
5339///
5340/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005341/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005342///
John McCalldaa8e4e2010-11-15 09:13:47 +00005343/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005344Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005345Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005346 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005347 QualType RHSType = RHS.get()->getType();
5348 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005349
Chris Lattnerfc144e22008-01-04 23:18:45 +00005350 // Get canonical types. We're not formatting these types, just comparing
5351 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005352 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5353 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005354
Eli Friedmanb001de72011-10-06 23:00:33 +00005355 // We can't do assignment from/to atomics yet.
5356 if (LHSType->isAtomicType())
5357 return Incompatible;
5358
John McCallb6cfa242011-01-31 22:28:28 +00005359 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005360 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005361 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005363 }
5364
Douglas Gregor9d293df2008-10-28 00:22:11 +00005365 // If the left-hand side is a reference type, then we are in a
5366 // (rare!) case where we've allowed the use of references in C,
5367 // e.g., as a parameter type in a built-in function. In this case,
5368 // just make sure that the type referenced is compatible with the
5369 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005370 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005371 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005372 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5373 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005374 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005375 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005376 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005377 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005378 }
John McCallb6cfa242011-01-31 22:28:28 +00005379
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005380 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5381 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005382 if (LHSType->isExtVectorType()) {
5383 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005384 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005385 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005386 // CK_VectorSplat does T -> vector T, so first cast to the
5387 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005388 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5389 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005390 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005391 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005392 }
5393 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005394 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005395 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005396 }
Mike Stump1eb44332009-09-09 15:08:12 +00005397
John McCallb6cfa242011-01-31 22:28:28 +00005398 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005399 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5400 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005401 // Allow assignments of an AltiVec vector type to an equivalent GCC
5402 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005403 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005404 Kind = CK_BitCast;
5405 return Compatible;
5406 }
5407
Douglas Gregor255210e2010-08-06 10:14:59 +00005408 // If we are allowing lax vector conversions, and LHS and RHS are both
5409 // vectors, the total size only needs to be the same. This is a bitcast;
5410 // no bits are changed but the result type is different.
5411 if (getLangOptions().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005412 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005413 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005414 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005415 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005416 }
5417 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005418 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005419
John McCallb6cfa242011-01-31 22:28:28 +00005420 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005421 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5422 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005423 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005424 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005425 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005426
John McCallb6cfa242011-01-31 22:28:28 +00005427 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005428 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005429 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005430 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005431 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005432 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005433 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
John McCallb6cfa242011-01-31 22:28:28 +00005435 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005436 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005437 Kind = CK_IntegralToPointer; // FIXME: null?
5438 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005439 }
John McCallb6cfa242011-01-31 22:28:28 +00005440
5441 // C pointers are not compatible with ObjC object pointers,
5442 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005443 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005444 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005445 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005446 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005447 return Compatible;
5448 }
5449
5450 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005451 if (RHSType->isObjCClassType() &&
5452 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005453 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005454 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005455 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005456 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005457
John McCallb6cfa242011-01-31 22:28:28 +00005458 Kind = CK_BitCast;
5459 return IncompatiblePointer;
5460 }
5461
5462 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005463 if (RHSType->getAs<BlockPointerType>()) {
5464 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005465 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005466 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005467 }
Steve Naroffb4406862008-09-29 18:10:17 +00005468 }
John McCallb6cfa242011-01-31 22:28:28 +00005469
Steve Naroff1c7d0672008-09-04 15:10:53 +00005470 return Incompatible;
5471 }
5472
John McCallb6cfa242011-01-31 22:28:28 +00005473 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005474 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005475 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005476 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005477 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005478 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005479 }
5480
5481 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005482 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005483 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005484 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005485 }
5486
John McCallb6cfa242011-01-31 22:28:28 +00005487 // id -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005488 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005489 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005490 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005491 }
Steve Naroffb4406862008-09-29 18:10:17 +00005492
John McCallb6cfa242011-01-31 22:28:28 +00005493 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005494 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005495 if (RHSPT->getPointeeType()->isVoidType()) {
5496 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005497 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005498 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005499
Chris Lattnerfc144e22008-01-04 23:18:45 +00005500 return Incompatible;
5501 }
5502
John McCallb6cfa242011-01-31 22:28:28 +00005503 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005504 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005505 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005506 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005507 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005508 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005509 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005510 if (getLangOptions().ObjCAutoRefCount &&
5511 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005512 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005513 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005514 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005515 }
5516
5517 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005518 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005519 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005520 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005521 }
5522
John McCallb6cfa242011-01-31 22:28:28 +00005523 // In general, C pointers are not compatible with ObjC object pointers,
5524 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005525 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005526 Kind = CK_CPointerToObjCPointerCast;
5527
John McCallb6cfa242011-01-31 22:28:28 +00005528 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005529 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005530 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005531 }
5532
5533 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005534 if (LHSType->isObjCClassType() &&
5535 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005536 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005537 return Compatible;
5538 }
5539
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005540 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005541 }
John McCallb6cfa242011-01-31 22:28:28 +00005542
5543 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005544 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005545 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005546 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005547 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005548 }
5549
Steve Naroff14108da2009-07-10 23:34:53 +00005550 return Incompatible;
5551 }
John McCallb6cfa242011-01-31 22:28:28 +00005552
5553 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005554 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005555 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005556 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005557 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005558 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005559 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005560
John McCallb6cfa242011-01-31 22:28:28 +00005561 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005562 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005563 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005564 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005565 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005566
Chris Lattnerfc144e22008-01-04 23:18:45 +00005567 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005568 }
John McCallb6cfa242011-01-31 22:28:28 +00005569
5570 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005571 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005572 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005573 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005574 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005575 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005576 }
Steve Naroff14108da2009-07-10 23:34:53 +00005577
John McCallb6cfa242011-01-31 22:28:28 +00005578 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005579 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005580 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005581 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005582 }
5583
Steve Naroff14108da2009-07-10 23:34:53 +00005584 return Incompatible;
5585 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005586
John McCallb6cfa242011-01-31 22:28:28 +00005587 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005588 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5589 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005590 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005591 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005592 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005593 }
John McCallb6cfa242011-01-31 22:28:28 +00005594
Reid Spencer5f016e22007-07-11 17:01:13 +00005595 return Incompatible;
5596}
5597
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005598/// \brief Constructs a transparent union from an expression that is
5599/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005600static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5601 ExprResult &EResult, QualType UnionType,
5602 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005603 // Build an initializer list that designates the appropriate member
5604 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005605 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005606 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005607 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005608 SourceLocation());
5609 Initializer->setType(UnionType);
5610 Initializer->setInitializedFieldInUnion(Field);
5611
5612 // Build a compound literal constructing a value of the transparent
5613 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005614 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005615 EResult = S.Owned(
5616 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5617 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005618}
5619
5620Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005621Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005622 ExprResult &RHS) {
5623 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005624
Mike Stump1eb44332009-09-09 15:08:12 +00005625 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005626 // transparent_union GCC extension.
5627 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005628 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005629 return Incompatible;
5630
5631 // The field to initialize within the transparent union.
5632 RecordDecl *UD = UT->getDecl();
5633 FieldDecl *InitField = 0;
5634 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005635 for (RecordDecl::field_iterator it = UD->field_begin(),
5636 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005637 it != itend; ++it) {
5638 if (it->getType()->isPointerType()) {
5639 // If the transparent union contains a pointer type, we allow:
5640 // 1) void pointer
5641 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005642 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005643 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005644 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005645 InitField = *it;
5646 break;
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Richard Trieuf7720da2011-09-06 20:40:12 +00005649 if (RHS.get()->isNullPointerConstant(Context,
5650 Expr::NPC_ValueDependentIsNull)) {
5651 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5652 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005653 InitField = *it;
5654 break;
5655 }
5656 }
5657
John McCalldaa8e4e2010-11-15 09:13:47 +00005658 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005659 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005660 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005661 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005662 InitField = *it;
5663 break;
5664 }
5665 }
5666
5667 if (!InitField)
5668 return Incompatible;
5669
Richard Trieuf7720da2011-09-06 20:40:12 +00005670 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005671 return Compatible;
5672}
5673
Chris Lattner5cf216b2008-01-04 18:04:52 +00005674Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005675Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5676 bool Diagnose) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005677 if (getLangOptions().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005678 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005679 // C++ 5.17p3: If the left operand is not of class type, the
5680 // expression is implicitly converted (C++ 4) to the
5681 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005682 ExprResult Res;
5683 if (Diagnose) {
5684 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5685 AA_Assigning);
5686 } else {
5687 ImplicitConversionSequence ICS =
5688 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5689 /*SuppressUserConversions=*/false,
5690 /*AllowExplicit=*/false,
5691 /*InOverloadResolution=*/false,
5692 /*CStyle=*/false,
5693 /*AllowObjCWritebackConversion=*/false);
5694 if (ICS.isFailure())
5695 return Incompatible;
5696 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5697 ICS, AA_Assigning);
5698 }
John Wiegley429bb272011-04-08 18:41:53 +00005699 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005700 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005701 Sema::AssignConvertType result = Compatible;
5702 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005703 !CheckObjCARCUnavailableWeakConversion(LHSType,
5704 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005705 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005706 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005707 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005708 }
5709
5710 // FIXME: Currently, we fall through and treat C++ classes like C
5711 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005712 // FIXME: We also fall through for atomics; not sure what should
5713 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005714 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005715
Steve Naroff529a4ad2007-11-27 17:58:44 +00005716 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5717 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005718 if ((LHSType->isPointerType() ||
5719 LHSType->isObjCObjectPointerType() ||
5720 LHSType->isBlockPointerType())
5721 && RHS.get()->isNullPointerConstant(Context,
5722 Expr::NPC_ValueDependentIsNull)) {
5723 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005724 return Compatible;
5725 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005726
Chris Lattner943140e2007-10-16 02:55:40 +00005727 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005728 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005729 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005730 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005731 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005732 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005733 if (!LHSType->isReferenceType()) {
5734 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5735 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005736 return Incompatible;
5737 }
Steve Narofff1120de2007-08-24 22:33:52 +00005738
John McCalldaa8e4e2010-11-15 09:13:47 +00005739 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005740 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005741 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005742
Steve Narofff1120de2007-08-24 22:33:52 +00005743 // C99 6.5.16.1p2: The value of the right operand is converted to the
5744 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005745 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5746 // so that we can use references in built-in functions even in C.
5747 // The getNonReferenceType() call makes sure that the resulting expression
5748 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005749 if (result != Incompatible && RHS.get()->getType() != LHSType)
5750 RHS = ImpCastExprToType(RHS.take(),
5751 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005752 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005753}
5754
Richard Trieuf7720da2011-09-06 20:40:12 +00005755QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5756 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005757 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005758 << LHS.get()->getType() << RHS.get()->getType()
5759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005760 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005761}
5762
Richard Trieu08062aa2011-09-06 21:01:04 +00005763QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005764 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005765 if (!IsCompAssign) {
5766 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5767 if (LHS.isInvalid())
5768 return QualType();
5769 }
5770 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5771 if (RHS.isInvalid())
5772 return QualType();
5773
Mike Stumpeed9cac2009-02-19 03:04:26 +00005774 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005775 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005776 QualType LHSType =
5777 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5778 QualType RHSType =
5779 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005780
Nate Begemanbe2341d2008-07-14 18:02:46 +00005781 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005782 if (LHSType == RHSType)
5783 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005784
Douglas Gregor255210e2010-08-06 10:14:59 +00005785 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005786 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5787 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5788 if (LHSType->isExtVectorType()) {
5789 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5790 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005791 }
5792
Richard Trieuccd891a2011-09-09 01:45:06 +00005793 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005794 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5795 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005796 }
5797
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005798 if (getLangOptions().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005799 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005800 // If we are allowing lax vector conversions, and LHS and RHS are both
5801 // vectors, the total size only needs to be the same. This is a
5802 // bitcast; no bits are changed but the result type is different.
5803 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005804 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5805 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005806 }
5807
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005808 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5809 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5810 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005811 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005812 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005813 std::swap(RHS, LHS);
5814 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005815 }
Mike Stump1eb44332009-09-09 15:08:12 +00005816
Nate Begemandde25982009-06-28 19:12:57 +00005817 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005818 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005819 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005820 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5821 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005822 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005823 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005824 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005825 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5826 if (swapped) std::swap(RHS, LHS);
5827 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005828 }
5829 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005830 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5831 RHSType->isRealFloatingType()) {
5832 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005833 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005834 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005835 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005836 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5837 if (swapped) std::swap(RHS, LHS);
5838 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005839 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005840 }
5841 }
Mike Stump1eb44332009-09-09 15:08:12 +00005842
Nate Begemandde25982009-06-28 19:12:57 +00005843 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00005844 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005845 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00005846 << LHS.get()->getType() << RHS.get()->getType()
5847 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005848 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005849}
5850
Richard Trieu481037f2011-09-16 00:53:10 +00005851// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5852// expression. These are mainly cases where the null pointer is used as an
5853// integer instead of a pointer.
5854static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5855 SourceLocation Loc, bool IsCompare) {
5856 // The canonical way to check for a GNU null is with isNullPointerConstant,
5857 // but we use a bit of a hack here for speed; this is a relatively
5858 // hot path, and isNullPointerConstant is slow.
5859 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5860 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5861
5862 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5863
5864 // Avoid analyzing cases where the result will either be invalid (and
5865 // diagnosed as such) or entirely valid and not something to warn about.
5866 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5867 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5868 return;
5869
5870 // Comparison operations would not make sense with a null pointer no matter
5871 // what the other expression is.
5872 if (!IsCompare) {
5873 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5874 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5875 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5876 return;
5877 }
5878
5879 // The rest of the operations only make sense with a null pointer
5880 // if the other expression is a pointer.
5881 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5882 NonNullType->canDecayToPointerType())
5883 return;
5884
5885 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5886 << LHSNull /* LHS is NULL */ << NonNullType
5887 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5888}
5889
Richard Trieu08062aa2011-09-06 21:01:04 +00005890QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005891 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005892 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00005893 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5894
Richard Trieu08062aa2011-09-06 21:01:04 +00005895 if (LHS.get()->getType()->isVectorType() ||
5896 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00005897 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005898
Richard Trieuccd891a2011-09-09 01:45:06 +00005899 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005900 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005901 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005902
Richard Trieu08062aa2011-09-06 21:01:04 +00005903 if (!LHS.get()->getType()->isArithmeticType() ||
5904 !RHS.get()->getType()->isArithmeticType())
5905 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005906
Chris Lattner7ef655a2010-01-12 21:23:57 +00005907 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00005908 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005909 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005910 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005911 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5912 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005913
Chris Lattner7ef655a2010-01-12 21:23:57 +00005914 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005915}
5916
Chris Lattner7ef655a2010-01-12 21:23:57 +00005917QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00005918 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00005919 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5920
Richard Trieu08062aa2011-09-06 21:01:04 +00005921 if (LHS.get()->getType()->isVectorType() ||
5922 RHS.get()->getType()->isVectorType()) {
5923 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5924 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00005925 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005926 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005927 }
Steve Naroff90045e82007-07-13 23:32:42 +00005928
Richard Trieuccd891a2011-09-09 01:45:06 +00005929 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00005930 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005931 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005932
Richard Trieu08062aa2011-09-06 21:01:04 +00005933 if (!LHS.get()->getType()->isIntegerType() ||
5934 !RHS.get()->getType()->isIntegerType())
5935 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005936
Chris Lattner7ef655a2010-01-12 21:23:57 +00005937 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00005938 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005939 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00005940 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5941 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005942
Chris Lattner7ef655a2010-01-12 21:23:57 +00005943 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005944}
5945
Chandler Carruth13b21be2011-06-27 08:02:19 +00005946/// \brief Diagnose invalid arithmetic on two void pointers.
5947static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00005948 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005949 S.Diag(Loc, S.getLangOptions().CPlusPlus
5950 ? diag::err_typecheck_pointer_arith_void_type
5951 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00005952 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5953 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00005954}
5955
5956/// \brief Diagnose invalid arithmetic on a void pointer.
5957static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5958 Expr *Pointer) {
5959 S.Diag(Loc, S.getLangOptions().CPlusPlus
5960 ? diag::err_typecheck_pointer_arith_void_type
5961 : diag::ext_gnu_void_ptr)
5962 << 0 /* one pointer */ << Pointer->getSourceRange();
5963}
5964
5965/// \brief Diagnose invalid arithmetic on two function pointers.
5966static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5967 Expr *LHS, Expr *RHS) {
5968 assert(LHS->getType()->isAnyPointerType());
5969 assert(RHS->getType()->isAnyPointerType());
5970 S.Diag(Loc, S.getLangOptions().CPlusPlus
5971 ? diag::err_typecheck_pointer_arith_function_type
5972 : diag::ext_gnu_ptr_func_arith)
5973 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5974 // We only show the second type if it differs from the first.
5975 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5976 RHS->getType())
5977 << RHS->getType()->getPointeeType()
5978 << LHS->getSourceRange() << RHS->getSourceRange();
5979}
5980
5981/// \brief Diagnose invalid arithmetic on a function pointer.
5982static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5983 Expr *Pointer) {
5984 assert(Pointer->getType()->isAnyPointerType());
5985 S.Diag(Loc, S.getLangOptions().CPlusPlus
5986 ? diag::err_typecheck_pointer_arith_function_type
5987 : diag::ext_gnu_ptr_func_arith)
5988 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5989 << 0 /* one pointer, so only one type */
5990 << Pointer->getSourceRange();
5991}
5992
Richard Trieud9f19342011-09-12 18:08:02 +00005993/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00005994///
5995/// \returns True if pointer has incomplete type
5996static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5997 Expr *Operand) {
5998 if ((Operand->getType()->isPointerType() &&
5999 !Operand->getType()->isDependentType()) ||
6000 Operand->getType()->isObjCObjectPointerType()) {
6001 QualType PointeeTy = Operand->getType()->getPointeeType();
6002 if (S.RequireCompleteType(
6003 Loc, PointeeTy,
6004 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6005 << PointeeTy << Operand->getSourceRange()))
6006 return true;
6007 }
6008 return false;
6009}
6010
Chandler Carruth13b21be2011-06-27 08:02:19 +00006011/// \brief Check the validity of an arithmetic pointer operand.
6012///
6013/// If the operand has pointer type, this code will check for pointer types
6014/// which are invalid in arithmetic operations. These will be diagnosed
6015/// appropriately, including whether or not the use is supported as an
6016/// extension.
6017///
6018/// \returns True when the operand is valid to use (even if as an extension).
6019static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6020 Expr *Operand) {
6021 if (!Operand->getType()->isAnyPointerType()) return true;
6022
6023 QualType PointeeTy = Operand->getType()->getPointeeType();
6024 if (PointeeTy->isVoidType()) {
6025 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6026 return !S.getLangOptions().CPlusPlus;
6027 }
6028 if (PointeeTy->isFunctionType()) {
6029 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6030 return !S.getLangOptions().CPlusPlus;
6031 }
6032
Richard Trieu097ecd22011-09-02 02:15:37 +00006033 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006034
6035 return true;
6036}
6037
6038/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6039/// operands.
6040///
6041/// This routine will diagnose any invalid arithmetic on pointer operands much
6042/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6043/// for emitting a single diagnostic even for operations where both LHS and RHS
6044/// are (potentially problematic) pointers.
6045///
6046/// \returns True when the operand is valid to use (even if as an extension).
6047static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006048 Expr *LHSExpr, Expr *RHSExpr) {
6049 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6050 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006051 if (!isLHSPointer && !isRHSPointer) return true;
6052
6053 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006054 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6055 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006056
6057 // Check for arithmetic on pointers to incomplete types.
6058 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6059 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6060 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006061 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6062 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6063 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006064
6065 return !S.getLangOptions().CPlusPlus;
6066 }
6067
6068 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6069 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6070 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006071 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6072 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6073 RHSExpr);
6074 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006075
6076 return !S.getLangOptions().CPlusPlus;
6077 }
6078
Richard Trieudef75842011-09-06 21:13:51 +00006079 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6080 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006081
Chandler Carruth13b21be2011-06-27 08:02:19 +00006082 return true;
6083}
6084
Richard Trieudb44a6b2011-09-01 22:53:23 +00006085/// \brief Check bad cases where we step over interface counts.
6086static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6087 SourceLocation OpLoc,
6088 Expr *Op) {
6089 assert(Op->getType()->isAnyPointerType());
6090 QualType PointeeTy = Op->getType()->getPointeeType();
6091 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6092 return true;
6093
6094 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6095 << PointeeTy << Op->getSourceRange();
6096 return false;
6097}
6098
Richard Trieud9f19342011-09-12 18:08:02 +00006099/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006100static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006101 Expr *LHSExpr, Expr *RHSExpr) {
6102 assert(LHSExpr->getType()->isAnyPointerType());
6103 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006104 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006105 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6106 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006107}
6108
Chris Lattner7ef655a2010-01-12 21:23:57 +00006109QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006110 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006111 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6112
Richard Trieudef75842011-09-06 21:13:51 +00006113 if (LHS.get()->getType()->isVectorType() ||
6114 RHS.get()->getType()->isVectorType()) {
6115 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006116 if (CompLHSTy) *CompLHSTy = compType;
6117 return compType;
6118 }
Steve Naroff49b45262007-07-13 16:58:59 +00006119
Richard Trieudef75842011-09-06 21:13:51 +00006120 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6121 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006122 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006123
Reid Spencer5f016e22007-07-11 17:01:13 +00006124 // handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006125 if (LHS.get()->getType()->isArithmeticType() &&
6126 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006127 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006128 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006129 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006130
Eli Friedmand72d16e2008-05-18 18:08:51 +00006131 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006132 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006133 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006134 std::swap(PExp, IExp);
6135
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006136 if (!PExp->getType()->isAnyPointerType())
6137 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006138
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006139 if (!IExp->getType()->isIntegerType())
6140 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006141
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006142 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6143 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006144
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006145 // Diagnose bad cases where we step over interface counts.
6146 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6147 return QualType();
6148
6149 // Check array bounds for pointer arithemtic
6150 CheckArrayAccess(PExp, IExp);
6151
6152 if (CompLHSTy) {
6153 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6154 if (LHSTy.isNull()) {
6155 LHSTy = LHS.get()->getType();
6156 if (LHSTy->isPromotableIntegerType())
6157 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006158 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006159 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006160 }
6161
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006162 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006163}
6164
Chris Lattnereca7be62008-04-07 05:30:13 +00006165// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006166QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006167 SourceLocation Loc,
6168 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006169 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6170
Richard Trieudef75842011-09-06 21:13:51 +00006171 if (LHS.get()->getType()->isVectorType() ||
6172 RHS.get()->getType()->isVectorType()) {
6173 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006174 if (CompLHSTy) *CompLHSTy = compType;
6175 return compType;
6176 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006177
Richard Trieudef75842011-09-06 21:13:51 +00006178 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6179 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006180 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006181
Chris Lattner6e4ab612007-12-09 21:53:25 +00006182 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006183
Chris Lattner6e4ab612007-12-09 21:53:25 +00006184 // Handle the common case first (both operands are arithmetic).
Richard Trieudef75842011-09-06 21:13:51 +00006185 if (LHS.get()->getType()->isArithmeticType() &&
6186 RHS.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006187 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006188 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006189 }
Mike Stump1eb44332009-09-09 15:08:12 +00006190
Chris Lattner6e4ab612007-12-09 21:53:25 +00006191 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006192 if (LHS.get()->getType()->isAnyPointerType()) {
6193 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006194
Chris Lattnerb5f15622009-04-24 23:50:08 +00006195 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006196 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006197 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006198
Chris Lattner6e4ab612007-12-09 21:53:25 +00006199 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006200 if (RHS.get()->getType()->isIntegerType()) {
6201 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006202 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006203
Richard Trieudef75842011-09-06 21:13:51 +00006204 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006205 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6206 OK_Ordinary, IExpr->getExprLoc());
6207 // Check array bounds for pointer arithemtic
Richard Trieudef75842011-09-06 21:13:51 +00006208 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006209
Richard Trieudef75842011-09-06 21:13:51 +00006210 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6211 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006212 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006213
Chris Lattner6e4ab612007-12-09 21:53:25 +00006214 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006215 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006216 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006217 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006218
Eli Friedman88d936b2009-05-16 13:54:38 +00006219 if (getLangOptions().CPlusPlus) {
6220 // Pointee types must be the same: C++ [expr.add]
6221 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006222 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006223 }
6224 } else {
6225 // Pointee types must be compatible C99 6.5.6p3
6226 if (!Context.typesAreCompatible(
6227 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6228 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006229 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006230 return QualType();
6231 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006232 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006233
Chandler Carruth13b21be2011-06-27 08:02:19 +00006234 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006235 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006236 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006237
Richard Trieudef75842011-09-06 21:13:51 +00006238 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006239 return Context.getPointerDiffType();
6240 }
6241 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006242
Richard Trieudef75842011-09-06 21:13:51 +00006243 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006244}
6245
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006246static bool isScopedEnumerationType(QualType T) {
6247 if (const EnumType *ET = dyn_cast<EnumType>(T))
6248 return ET->getDecl()->isScoped();
6249 return false;
6250}
6251
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006252static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006253 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006254 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006255 llvm::APSInt Right;
6256 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006257 if (RHS.get()->isValueDependent() ||
6258 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006259 return;
6260
6261 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006262 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006263 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006264 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006265 return;
6266 }
6267 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006268 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006269 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006270 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006271 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006272 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006273 return;
6274 }
6275 if (Opc != BO_Shl)
6276 return;
6277
6278 // When left shifting an ICE which is signed, we can check for overflow which
6279 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6280 // integers have defined behavior modulo one more than the maximum value
6281 // representable in the result type, so never warn for those.
6282 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006283 if (LHS.get()->isValueDependent() ||
6284 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6285 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006286 return;
6287 llvm::APInt ResultBits =
6288 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6289 if (LeftBits.uge(ResultBits))
6290 return;
6291 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6292 Result = Result.shl(Right);
6293
Ted Kremenekfa821382011-06-15 00:54:52 +00006294 // Print the bit representation of the signed integer as an unsigned
6295 // hexadecimal number.
6296 llvm::SmallString<40> HexResult;
6297 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6298
Chandler Carruth21206d52011-02-23 23:34:11 +00006299 // If we are only missing a sign bit, this is less likely to result in actual
6300 // bugs -- if the result is cast back to an unsigned type, it will have the
6301 // expected value. Thus we place this behind a different warning that can be
6302 // turned off separately if needed.
6303 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006304 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006305 << HexResult.str() << LHSType
6306 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006307 return;
6308 }
6309
6310 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006311 << HexResult.str() << Result.getMinSignedBits() << LHSType
6312 << Left.getBitWidth() << LHS.get()->getSourceRange()
6313 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006314}
6315
Chris Lattnereca7be62008-04-07 05:30:13 +00006316// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006317QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006318 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006319 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006320 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6321
Chris Lattnerca5eede2007-12-12 05:47:28 +00006322 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006323 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6324 !RHS.get()->getType()->hasIntegerRepresentation())
6325 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006326
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006327 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6328 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006329 if (isScopedEnumerationType(LHS.get()->getType()) ||
6330 isScopedEnumerationType(RHS.get()->getType())) {
6331 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006332 }
6333
Nate Begeman2207d792009-10-25 02:26:48 +00006334 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006335 if (LHS.get()->getType()->isVectorType() ||
6336 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006337 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006338
Chris Lattnerca5eede2007-12-12 05:47:28 +00006339 // Shifts don't perform usual arithmetic conversions, they just do integer
6340 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006341
John McCall1bc80af2010-12-16 19:28:59 +00006342 // For the LHS, do usual unary conversions, but then reset them away
6343 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006344 ExprResult OldLHS = LHS;
6345 LHS = UsualUnaryConversions(LHS.take());
6346 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006347 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006348 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006349 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006350
6351 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006352 RHS = UsualUnaryConversions(RHS.take());
6353 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006354 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006355
Ryan Flynnd0439682009-08-07 16:20:20 +00006356 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006357 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006358
Chris Lattnerca5eede2007-12-12 05:47:28 +00006359 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006360 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006361}
6362
Chandler Carruth99919472010-07-10 12:30:03 +00006363static bool IsWithinTemplateSpecialization(Decl *D) {
6364 if (DeclContext *DC = D->getDeclContext()) {
6365 if (isa<ClassTemplateSpecializationDecl>(DC))
6366 return true;
6367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6368 return FD->isFunctionTemplateSpecialization();
6369 }
6370 return false;
6371}
6372
Richard Trieue648ac32011-09-02 03:48:46 +00006373/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006374static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6375 ExprResult &RHS) {
6376 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6377 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006378
6379 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6380 if (!LHSEnumType)
6381 return;
6382 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6383 if (!RHSEnumType)
6384 return;
6385
6386 // Ignore anonymous enums.
6387 if (!LHSEnumType->getDecl()->getIdentifier())
6388 return;
6389 if (!RHSEnumType->getDecl()->getIdentifier())
6390 return;
6391
6392 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6393 return;
6394
6395 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6396 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006397 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006398}
6399
Richard Trieu7be1be02011-09-02 02:55:45 +00006400/// \brief Diagnose bad pointer comparisons.
6401static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006402 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006403 bool IsError) {
6404 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006405 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006406 << LHS.get()->getType() << RHS.get()->getType()
6407 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006408}
6409
6410/// \brief Returns false if the pointers are converted to a composite type,
6411/// true otherwise.
6412static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006413 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006414 // C++ [expr.rel]p2:
6415 // [...] Pointer conversions (4.10) and qualification
6416 // conversions (4.4) are performed on pointer operands (or on
6417 // a pointer operand and a null pointer constant) to bring
6418 // them to their composite pointer type. [...]
6419 //
6420 // C++ [expr.eq]p1 uses the same notion for (in)equality
6421 // comparisons of pointers.
6422
6423 // C++ [expr.eq]p2:
6424 // In addition, pointers to members can be compared, or a pointer to
6425 // member and a null pointer constant. Pointer to member conversions
6426 // (4.11) and qualification conversions (4.4) are performed to bring
6427 // them to a common type. If one operand is a null pointer constant,
6428 // the common type is the type of the other operand. Otherwise, the
6429 // common type is a pointer to member type similar (4.4) to the type
6430 // of one of the operands, with a cv-qualification signature (4.4)
6431 // that is the union of the cv-qualification signatures of the operand
6432 // types.
6433
Richard Trieuba261492011-09-06 21:27:33 +00006434 QualType LHSType = LHS.get()->getType();
6435 QualType RHSType = RHS.get()->getType();
6436 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6437 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006438
6439 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006440 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006441 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006442 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006443 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006444 return true;
6445 }
6446
6447 if (NonStandardCompositeType)
6448 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006449 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6450 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006451
Richard Trieuba261492011-09-06 21:27:33 +00006452 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6453 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006454 return false;
6455}
6456
6457static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006458 ExprResult &LHS,
6459 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006460 bool IsError) {
6461 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6462 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006463 << LHS.get()->getType() << RHS.get()->getType()
6464 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006465}
6466
Douglas Gregor0c6db942009-05-04 06:07:12 +00006467// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006468QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006469 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006470 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006471 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6472
John McCall2de56d12010-08-25 11:45:40 +00006473 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006474
Chris Lattner02dd4b12009-12-05 05:40:13 +00006475 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006476 if (LHS.get()->getType()->isVectorType() ||
6477 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006478 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006479
Richard Trieuf1775fb2011-09-06 21:43:51 +00006480 QualType LHSType = LHS.get()->getType();
6481 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006482
Richard Trieuf1775fb2011-09-06 21:43:51 +00006483 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6484 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006485
Richard Trieuf1775fb2011-09-06 21:43:51 +00006486 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006487
Richard Trieuf1775fb2011-09-06 21:43:51 +00006488 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006489 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006490 !LHS.get()->getLocStart().isMacroID() &&
6491 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006492 // For non-floating point types, check for self-comparisons of the form
6493 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6494 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006495 //
6496 // NOTE: Don't warn about comparison expressions resulting from macro
6497 // expansion. Also don't warn about comparisons which are only self
6498 // comparisons within a template specialization. The warnings should catch
6499 // obvious cases in the definition of the template anyways. The idea is to
6500 // warn when the typed comparison operator will always evaluate to the same
6501 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006502 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006503 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006504 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006505 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006506 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006507 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006508 << (Opc == BO_EQ
6509 || Opc == BO_LE
6510 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006511 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006512 !DRL->getDecl()->getType()->isReferenceType() &&
6513 !DRR->getDecl()->getType()->isReferenceType()) {
6514 // what is it always going to eval to?
6515 char always_evals_to;
6516 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006517 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006518 always_evals_to = 0; // false
6519 break;
John McCall2de56d12010-08-25 11:45:40 +00006520 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006521 always_evals_to = 1; // true
6522 break;
6523 default:
6524 // best we can say is 'a constant'
6525 always_evals_to = 2; // e.g. array1 <= array2
6526 break;
6527 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006528 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006529 << 1 // array
6530 << always_evals_to);
6531 }
6532 }
Chandler Carruth99919472010-07-10 12:30:03 +00006533 }
Mike Stump1eb44332009-09-09 15:08:12 +00006534
Chris Lattner55660a72009-03-08 19:39:53 +00006535 if (isa<CastExpr>(LHSStripped))
6536 LHSStripped = LHSStripped->IgnoreParenCasts();
6537 if (isa<CastExpr>(RHSStripped))
6538 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006539
Chris Lattner55660a72009-03-08 19:39:53 +00006540 // Warn about comparisons against a string constant (unless the other
6541 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006542 Expr *literalString = 0;
6543 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006544 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006545 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006546 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006547 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006548 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006549 } else if ((isa<StringLiteral>(RHSStripped) ||
6550 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006551 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006552 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006553 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006554 literalStringStripped = RHSStripped;
6555 }
6556
6557 if (literalString) {
6558 std::string resultComparison;
6559 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006560 case BO_LT: resultComparison = ") < 0"; break;
6561 case BO_GT: resultComparison = ") > 0"; break;
6562 case BO_LE: resultComparison = ") <= 0"; break;
6563 case BO_GE: resultComparison = ") >= 0"; break;
6564 case BO_EQ: resultComparison = ") == 0"; break;
6565 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006566 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006567 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006568
Ted Kremenek351ba912011-02-23 01:52:04 +00006569 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006570 PDiag(diag::warn_stringcompare)
6571 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006572 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006573 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006574 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006575
Douglas Gregord64fdd02010-06-08 19:50:34 +00006576 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006577 if (LHS.get()->getType()->isArithmeticType() &&
6578 RHS.get()->getType()->isArithmeticType()) {
6579 UsualArithmeticConversions(LHS, RHS);
6580 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006581 return QualType();
6582 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006583 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006584 LHS = UsualUnaryConversions(LHS.take());
6585 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006586 return QualType();
6587
Richard Trieuf1775fb2011-09-06 21:43:51 +00006588 RHS = UsualUnaryConversions(RHS.take());
6589 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006590 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006591 }
6592
Richard Trieuf1775fb2011-09-06 21:43:51 +00006593 LHSType = LHS.get()->getType();
6594 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006595
Douglas Gregor447b69e2008-11-19 03:25:36 +00006596 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006597 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006598
Richard Trieuccd891a2011-09-09 01:45:06 +00006599 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006600 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006601 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006602 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006603 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006604 if (LHSType->hasFloatingRepresentation())
6605 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006606
Richard Trieuf1775fb2011-09-06 21:43:51 +00006607 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006608 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006609 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006610
Richard Trieuf1775fb2011-09-06 21:43:51 +00006611 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006612 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006613 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006614 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006615
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006616 // All of the following pointer-related warnings are GCC extensions, except
6617 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006618 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006619 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006620 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006621 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006622 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006623
Douglas Gregor0c6db942009-05-04 06:07:12 +00006624 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006625 if (LCanPointeeTy == RCanPointeeTy)
6626 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006627 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006628 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6629 // Valid unless comparison between non-null pointer and function pointer
6630 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006631 // In a SFINAE context, we treat this as a hard error to maintain
6632 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006633 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6634 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006635 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006636 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006637
6638 if (isSFINAEContext())
6639 return QualType();
6640
Richard Trieuf1775fb2011-09-06 21:43:51 +00006641 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006642 return ResultTy;
6643 }
6644 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006645
Richard Trieuf1775fb2011-09-06 21:43:51 +00006646 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00006647 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006648 else
6649 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00006650 }
Eli Friedman3075e762009-08-23 00:27:47 +00006651 // C99 6.5.9p2 and C99 6.5.8p2
6652 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6653 RCanPointeeTy.getUnqualifiedType())) {
6654 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00006655 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00006656 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006657 << LHSType << RHSType << LHS.get()->getSourceRange()
6658 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006659 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006660 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00006661 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6662 // Valid unless comparison between non-null pointer and function pointer
6663 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00006664 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006665 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006666 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00006667 } else {
6668 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00006669 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00006670 }
John McCall34d6f932011-03-11 04:25:25 +00006671 if (LCanPointeeTy != RCanPointeeTy) {
6672 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006673 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006674 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006675 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006676 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006677 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006678 }
Mike Stump1eb44332009-09-09 15:08:12 +00006679
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006680 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006681 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006682 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006683 return ResultTy;
6684
Mike Stump1eb44332009-09-09 15:08:12 +00006685 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006686 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006687 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006688 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006689 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006690 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6691 RHS = ImpCastExprToType(RHS.take(), LHSType,
6692 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006693 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006694 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006695 return ResultTy;
6696 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006697 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006698 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00006699 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006700 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6701 LHS = ImpCastExprToType(LHS.take(), RHSType,
6702 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006703 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006704 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006705 return ResultTy;
6706 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006707
6708 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006709 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006710 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6711 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00006712 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00006713 else
6714 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00006715 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006716
6717 // Handle scoped enumeration types specifically, since they don't promote
6718 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006719 if (LHS.get()->getType()->isEnumeralType() &&
6720 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6721 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006722 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006723 }
Mike Stump1eb44332009-09-09 15:08:12 +00006724
Steve Naroff1c7d0672008-09-04 15:10:53 +00006725 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00006726 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006727 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006728 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6729 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006730
Steve Naroff1c7d0672008-09-04 15:10:53 +00006731 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006732 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006733 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006734 << LHSType << RHSType << LHS.get()->getSourceRange()
6735 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006736 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006737 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006738 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006739 }
John Wiegley429bb272011-04-08 18:41:53 +00006740
Steve Naroff59f53942008-09-28 01:11:11 +00006741 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00006742 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00006743 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6744 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006745 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006746 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006747 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00006748 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006749 ->getPointeeType()->isVoidType())))
6750 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006751 << LHSType << RHSType << LHS.get()->getSourceRange()
6752 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006753 }
John McCall34d6f932011-03-11 04:25:25 +00006754 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006755 LHS = ImpCastExprToType(LHS.take(), RHSType,
6756 RHSType->isPointerType() ? CK_BitCast
6757 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006758 else
John McCall1d9b3b22011-09-09 05:25:32 +00006759 RHS = ImpCastExprToType(RHS.take(), LHSType,
6760 LHSType->isPointerType() ? CK_BitCast
6761 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006762 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006763 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006764
Richard Trieuf1775fb2011-09-06 21:43:51 +00006765 if (LHSType->isObjCObjectPointerType() ||
6766 RHSType->isObjCObjectPointerType()) {
6767 const PointerType *LPT = LHSType->getAs<PointerType>();
6768 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00006769 if (LPT || RPT) {
6770 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6771 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006772
Steve Naroffa8069f12008-11-17 19:49:16 +00006773 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006774 !Context.typesAreCompatible(LHSType, RHSType)) {
6775 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006776 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00006777 }
John McCall34d6f932011-03-11 04:25:25 +00006778 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00006779 LHS = ImpCastExprToType(LHS.take(), RHSType,
6780 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00006781 else
John McCall1d9b3b22011-09-09 05:25:32 +00006782 RHS = ImpCastExprToType(RHS.take(), LHSType,
6783 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006784 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006785 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006786 if (LHSType->isObjCObjectPointerType() &&
6787 RHSType->isObjCObjectPointerType()) {
6788 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6789 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00006790 /*isError*/false);
John McCall34d6f932011-03-11 04:25:25 +00006791 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006792 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006793 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006794 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006795 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006796 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006797 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00006798 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6799 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006800 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006801 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00006802 if ((LHSIsNull && LHSType->isIntegerType()) ||
6803 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuccd891a2011-09-09 01:45:06 +00006804 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006805 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuccd891a2011-09-09 01:45:06 +00006806 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006807 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006808 else if (getLangOptions().CPlusPlus) {
6809 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6810 isError = true;
6811 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006812 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006813
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006814 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006815 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00006816 << LHSType << RHSType << LHS.get()->getSourceRange()
6817 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006818 if (isError)
6819 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006820 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006821
Richard Trieuf1775fb2011-09-06 21:43:51 +00006822 if (LHSType->isIntegerType())
6823 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00006824 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006825 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00006826 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00006827 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006828 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006829 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006830
Steve Naroff39218df2008-09-04 16:56:14 +00006831 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00006832 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006833 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6834 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006835 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006836 }
Richard Trieuccd891a2011-09-09 01:45:06 +00006837 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00006838 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6839 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006840 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006841 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006842
Richard Trieuf1775fb2011-09-06 21:43:51 +00006843 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006844}
6845
Nate Begemanbe2341d2008-07-14 18:02:46 +00006846/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006847/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006848/// like a scalar comparison, a vector comparison produces a vector of integer
6849/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006850QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006851 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006852 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006853 // Check to make sure we're operating on vectors of the same type and width,
6854 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006855 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006856 if (vType.isNull())
6857 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858
Richard Trieu9f60dee2011-09-07 01:19:57 +00006859 QualType LHSType = LHS.get()->getType();
6860 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006861
Anton Yartsev7870b132011-03-27 15:36:07 +00006862 // If AltiVec, the comparison results in a numeric type, i.e.
6863 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006864 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006865 return Context.getLogicalOperationType();
6866
Nate Begemanbe2341d2008-07-14 18:02:46 +00006867 // For non-floating point types, check for self-comparisons of the form
6868 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6869 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006870 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00006871 if (DeclRefExpr* DRL
6872 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6873 if (DeclRefExpr* DRR
6874 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006875 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006876 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006877 PDiag(diag::warn_comparison_always)
6878 << 0 // self-
6879 << 2 // "a constant"
6880 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006881 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006882
Nate Begemanbe2341d2008-07-14 18:02:46 +00006883 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00006884 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006885 assert (RHSType->hasFloatingRepresentation());
6886 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006887 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006888
Tanya Lattner6ec96432011-10-17 21:00:38 +00006889 // Return a signed type that is of identical size and number of elements.
6890 // For floating point vectors, return an integer type of identical size
6891 // and number of elements.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006892 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006893 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Tanya Lattner6ec96432011-10-17 21:00:38 +00006894 if (TypeSize == Context.getTypeSize(Context.CharTy))
6895 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6896 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6897 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6898 else if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006899 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Tanya Lattner6ec96432011-10-17 21:00:38 +00006900 else if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006901 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006903 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006904 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6905}
6906
Reid Spencer5f016e22007-07-11 17:01:13 +00006907inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006908 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006909 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6910
Richard Trieu9f60dee2011-09-07 01:19:57 +00006911 if (LHS.get()->getType()->isVectorType() ||
6912 RHS.get()->getType()->isVectorType()) {
6913 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6914 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006915 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006916
Richard Trieu9f60dee2011-09-07 01:19:57 +00006917 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00006918 }
Steve Naroff90045e82007-07-13 23:32:42 +00006919
Richard Trieu9f60dee2011-09-07 01:19:57 +00006920 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6921 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00006922 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00006923 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006924 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00006925 LHS = LHSResult.take();
6926 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006927
Richard Trieu9f60dee2011-09-07 01:19:57 +00006928 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6929 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006930 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00006931 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006932}
6933
6934inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00006935 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006936
6937 // Diagnose cases where the user write a logical and/or but probably meant a
6938 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6939 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006940 if (LHS.get()->getType()->isIntegerType() &&
6941 !LHS.get()->getType()->isBooleanType() &&
6942 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006943 // Don't warn in macros or template instantiations.
6944 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006945 // If the RHS can be constant folded, and if it constant folds to something
6946 // that isn't 0 or 1 (which indicate a potential logical operation that
6947 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006948 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00006949 llvm::APSInt Result;
6950 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieu9f60dee2011-09-07 01:19:57 +00006951 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00006952 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00006953 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00006954 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006955 << (Opc == BO_LAnd ? "&&" : "||");
6956 // Suggest replacing the logical operator with the bitwise version
6957 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6958 << (Opc == BO_LAnd ? "&" : "|")
6959 << FixItHint::CreateReplacement(SourceRange(
6960 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6961 getLangOptions())),
6962 Opc == BO_LAnd ? "&" : "|");
6963 if (Opc == BO_LAnd)
6964 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6965 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6966 << FixItHint::CreateRemoval(
6967 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00006968 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006969 0, getSourceManager(),
6970 getLangOptions()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00006971 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00006972 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00006973 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006974
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006975 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00006976 LHS = UsualUnaryConversions(LHS.take());
6977 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006978 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006979
Richard Trieu9f60dee2011-09-07 01:19:57 +00006980 RHS = UsualUnaryConversions(RHS.take());
6981 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006982 return QualType();
6983
Richard Trieu9f60dee2011-09-07 01:19:57 +00006984 if (!LHS.get()->getType()->isScalarType() ||
6985 !RHS.get()->getType()->isScalarType())
6986 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006987
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006988 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006989 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006990
John McCall75f7c0f2010-06-04 00:29:51 +00006991 // The following is safe because we only use this method for
6992 // non-overloadable operands.
6993
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006994 // C++ [expr.log.and]p1
6995 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006996 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00006997 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6998 if (LHSRes.isInvalid())
6999 return InvalidOperands(Loc, LHS, RHS);
7000 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007001
Richard Trieu9f60dee2011-09-07 01:19:57 +00007002 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7003 if (RHSRes.isInvalid())
7004 return InvalidOperands(Loc, LHS, RHS);
7005 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007006
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007007 // C++ [expr.log.and]p2
7008 // C++ [expr.log.or]p2
7009 // The result is a bool.
7010 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007011}
7012
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007013/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7014/// is a read-only property; return true if so. A readonly property expression
7015/// depends on various declarations and thus must be treated specially.
7016///
Mike Stump1eb44332009-09-09 15:08:12 +00007017static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007018 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7019 if (!PropExpr) return false;
7020 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007021
John McCall3c3b7f92011-10-25 17:37:35 +00007022 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7023 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007024 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007025 PropExpr->getBase()->getType();
7026
John McCall3c3b7f92011-10-25 17:37:35 +00007027 if (const ObjCObjectPointerType *OPT =
7028 BaseType->getAsObjCInterfacePointerType())
7029 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7030 if (S.isPropertyReadonly(PDecl, IFace))
7031 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007032 return false;
7033}
7034
Fariborz Jahanian14086762011-03-28 23:47:18 +00007035static bool IsConstProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007036 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7037 if (!PropExpr) return false;
7038 if (PropExpr->isImplicitProperty()) return false;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007039
John McCall3c3b7f92011-10-25 17:37:35 +00007040 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7041 QualType T = PDecl->getType().getNonReferenceType();
7042 return T.isConstQualified();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007043}
7044
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007045static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007046 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7047 if (!ME) return false;
7048 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7049 ObjCMessageExpr *Base =
7050 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7051 if (!Base) return false;
7052 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007053}
7054
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007055/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7056/// emit an error and return true. If so, return false.
7057static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007058 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007059 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007060 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007061 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7062 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007063 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7064 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007065 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7066 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007067 if (IsLV == Expr::MLV_Valid)
7068 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007069
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007070 unsigned Diag = 0;
7071 bool NeedType = false;
7072 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007073 case Expr::MLV_ConstQualified:
7074 Diag = diag::err_typecheck_assign_const;
7075
John McCall7acddac2011-06-17 06:42:21 +00007076 // In ARC, use some specialized diagnostics for occasions where we
7077 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00007078 if (S.getLangOptions().ObjCAutoRefCount) {
7079 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7080 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7081 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7082
John McCall7acddac2011-06-17 06:42:21 +00007083 // Use the normal diagnostic if it's pseudo-__strong but the
7084 // user actually wrote 'const'.
7085 if (var->isARCPseudoStrong() &&
7086 (!var->getTypeSourceInfo() ||
7087 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7088 // There are two pseudo-strong cases:
7089 // - self
John McCallf85e1932011-06-15 23:02:42 +00007090 ObjCMethodDecl *method = S.getCurMethodDecl();
7091 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007092 Diag = method->isClassMethod()
7093 ? diag::err_typecheck_arc_assign_self_class_method
7094 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007095
7096 // - fast enumeration variables
7097 else
John McCallf85e1932011-06-15 23:02:42 +00007098 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007099
John McCallf85e1932011-06-15 23:02:42 +00007100 SourceRange Assign;
7101 if (Loc != OrigLoc)
7102 Assign = SourceRange(OrigLoc, OrigLoc);
7103 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7104 // We need to preserve the AST regardless, so migration tool
7105 // can do its job.
7106 return false;
7107 }
7108 }
7109 }
7110
7111 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007112 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007113 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7114 NeedType = true;
7115 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007116 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007117 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7118 NeedType = true;
7119 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007120 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007121 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7122 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007123 case Expr::MLV_Valid:
7124 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007125 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007126 case Expr::MLV_MemberFunction:
7127 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007128 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7129 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007130 case Expr::MLV_IncompleteType:
7131 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007132 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007133 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007134 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007135 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007136 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7137 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007138 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007139 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7140 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007141 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007142 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007143 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007144 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007145 case Expr::MLV_InvalidMessageExpression:
7146 Diag = diag::error_readonly_message_assignment;
7147 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007148 case Expr::MLV_SubObjCPropertySetting:
7149 Diag = diag::error_no_subobject_property_setting;
7150 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007151 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007152
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007153 SourceRange Assign;
7154 if (Loc != OrigLoc)
7155 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007156 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007157 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007158 else
Mike Stump1eb44332009-09-09 15:08:12 +00007159 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007160 return true;
7161}
7162
7163
7164
7165// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007166QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007167 SourceLocation Loc,
7168 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007169 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7170
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007171 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007172 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007173 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007174
Richard Trieu268942b2011-09-07 01:33:52 +00007175 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007176 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7177 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007178 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007179 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007180 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007181 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007182 if (RHS.isInvalid())
7183 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007184 // Special case of NSObject attributes on c-style pointer types.
7185 if (ConvTy == IncompatiblePointer &&
7186 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007187 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007188 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007189 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007190 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007191
John McCallf89e55a2010-11-18 06:31:45 +00007192 if (ConvTy == Compatible &&
7193 getLangOptions().ObjCNonFragileABI &&
7194 LHSType->isObjCObjectType())
7195 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7196 << LHSType;
7197
Chris Lattner2c156472008-08-21 18:04:13 +00007198 // If the RHS is a unary plus or minus, check to see if they = and + are
7199 // right next to each other. If so, the user may have typo'd "x =+ 4"
7200 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007201 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7203 RHSCheck = ICE->getSubExpr();
7204 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007205 if ((UO->getOpcode() == UO_Plus ||
7206 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007207 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007208 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007209 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007210 // And there is a space or other character before the subexpr of the
7211 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007212 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007213 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007214 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007215 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007216 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007217 }
Chris Lattner2c156472008-08-21 18:04:13 +00007218 }
John McCallf85e1932011-06-15 23:02:42 +00007219
7220 if (ConvTy == Compatible) {
7221 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007222 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007223 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007224 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007225 }
Chris Lattner2c156472008-08-21 18:04:13 +00007226 } else {
7227 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007228 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007229 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007230
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007231 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007232 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007233 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007234
Richard Trieu268942b2011-09-07 01:33:52 +00007235 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007236
Reid Spencer5f016e22007-07-11 17:01:13 +00007237 // C99 6.5.16p3: The type of an assignment expression is the type of the
7238 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007239 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007240 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7241 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007242 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007243 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007244 return (getLangOptions().CPlusPlus
7245 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007246}
7247
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007248// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007249static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007250 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007251 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007252
John McCallfb8721c2011-04-10 19:13:55 +00007253 LHS = S.CheckPlaceholderExpr(LHS.take());
7254 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007255 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007256 return QualType();
7257
John McCallcf2e5062010-10-12 07:14:40 +00007258 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7259 // operands, but not unary promotions.
7260 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007261
John McCallf6a16482010-12-04 03:47:34 +00007262 // So we treat the LHS as a ignored value, and in C++ we allow the
7263 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007264 LHS = S.IgnoredValueConversions(LHS.take());
7265 if (LHS.isInvalid())
7266 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007267
7268 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007269 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7270 if (RHS.isInvalid())
7271 return QualType();
7272 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007273 S.RequireCompleteType(Loc, RHS.get()->getType(),
7274 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007275 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007276
John Wiegley429bb272011-04-08 18:41:53 +00007277 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007278}
7279
Steve Naroff49b45262007-07-13 16:58:59 +00007280/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7281/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007282static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7283 ExprValueKind &VK,
7284 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007285 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007286 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007287 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007288
Chris Lattner3528d352008-11-21 07:05:48 +00007289 QualType ResType = Op->getType();
7290 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007291
John McCall09431682010-11-18 19:01:18 +00007292 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007293 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007294 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007295 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007296 return QualType();
7297 }
7298 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007299 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007300 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007301 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007302 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007303 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007304 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007305 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007306
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007307 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007308 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007309 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007310 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007311 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007312 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007313 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007314 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007315 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007316 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007317 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007318 IsInc, IsPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007319 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7320 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007321 } else {
John McCall09431682010-11-18 19:01:18 +00007322 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007323 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007324 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007325 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007326 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007327 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007328 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007329 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007330 // In C++, a prefix increment is the same type as the operand. Otherwise
7331 // (in C or with postfix), the increment is the unqualified type of the
7332 // operand.
Richard Trieuccd891a2011-09-09 01:45:06 +00007333 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007334 VK = VK_LValue;
7335 return ResType;
7336 } else {
7337 VK = VK_RValue;
7338 return ResType.getUnqualifiedType();
7339 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007340}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007341
7342
Anders Carlsson369dee42008-02-01 07:15:58 +00007343/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007344/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007345/// where the declaration is needed for type checking. We only need to
7346/// handle cases when the expression references a function designator
7347/// or is an lvalue. Here are some examples:
7348/// - &(x) => x
7349/// - &*****f => f for f a function designator.
7350/// - &s.xx => s
7351/// - &s.zz[1].yy -> s, if zz is an array
7352/// - *(x + 1) -> x, if x is an array
7353/// - &"123"[2] -> 0
7354/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007355static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007356 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007357 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007358 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007359 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007360 // If this is an arrow operator, the address is an offset from
7361 // the base's value, so the object the base refers to is
7362 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007363 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007364 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007365 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007366 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007367 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007368 // FIXME: This code shouldn't be necessary! We should catch the implicit
7369 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007370 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7371 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7372 if (ICE->getSubExpr()->getType()->isArrayType())
7373 return getPrimaryDecl(ICE->getSubExpr());
7374 }
7375 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007376 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007377 case Stmt::UnaryOperatorClass: {
7378 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007379
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007380 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007381 case UO_Real:
7382 case UO_Imag:
7383 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007384 return getPrimaryDecl(UO->getSubExpr());
7385 default:
7386 return 0;
7387 }
7388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007389 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007390 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007391 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007392 // If the result of an implicit cast is an l-value, we care about
7393 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007394 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007395 default:
7396 return 0;
7397 }
7398}
7399
Richard Trieu5520f232011-09-07 21:46:33 +00007400namespace {
7401 enum {
7402 AO_Bit_Field = 0,
7403 AO_Vector_Element = 1,
7404 AO_Property_Expansion = 2,
7405 AO_Register_Variable = 3,
7406 AO_No_Error = 4
7407 };
7408}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007409/// \brief Diagnose invalid operand for address of operations.
7410///
7411/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007412static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7413 Expr *E, unsigned Type) {
7414 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7415}
7416
Reid Spencer5f016e22007-07-11 17:01:13 +00007417/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007418/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007419/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007420/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007421/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007422/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007423/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007424static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007425 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007426 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7427 if (PTy->getKind() == BuiltinType::Overload) {
7428 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7429 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7430 << OrigOp.get()->getSourceRange();
7431 return QualType();
7432 }
7433
7434 return S.Context.OverloadTy;
7435 }
7436
7437 if (PTy->getKind() == BuiltinType::UnknownAny)
7438 return S.Context.UnknownAnyTy;
7439
7440 if (PTy->getKind() == BuiltinType::BoundMember) {
7441 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7442 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007443 return QualType();
7444 }
John McCall3c3b7f92011-10-25 17:37:35 +00007445
7446 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7447 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007448 }
John McCall9c72c602010-08-27 09:08:28 +00007449
John McCall3c3b7f92011-10-25 17:37:35 +00007450 if (OrigOp.get()->isTypeDependent())
7451 return S.Context.DependentTy;
7452
7453 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007454
John McCall9c72c602010-08-27 09:08:28 +00007455 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007456 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007457
John McCall09431682010-11-18 19:01:18 +00007458 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007459 // Implement C99-only parts of addressof rules.
7460 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007461 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007462 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7463 // (assuming the deref expression is valid).
7464 return uOp->getSubExpr()->getType();
7465 }
7466 // Technically, there should be a check for array subscript
7467 // expressions here, but the result of one is always an lvalue anyway.
7468 }
John McCall5808ce42011-02-03 08:15:49 +00007469 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007470 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007471 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007472
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007473 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007474 bool sfinae = S.isSFINAEContext();
7475 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7476 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007477 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007478 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007479 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007480 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007481 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007482 } else if (lval == Expr::LV_MemberFunction) {
7483 // If it's an instance method, make a member pointer.
7484 // The expression must have exactly the form &A::foo.
7485
7486 // If the underlying expression isn't a decl ref, give up.
7487 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007488 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007489 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007490 return QualType();
7491 }
7492 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7493 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7494
7495 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007496 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007497 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007498 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007499
7500 // The method was named without a qualifier.
7501 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007502 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007503 << op->getSourceRange();
7504 }
7505
John McCall09431682010-11-18 19:01:18 +00007506 return S.Context.getMemberPointerType(op->getType(),
7507 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007508 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007509 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007510 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007511 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007512 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007513 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007514 AddressOfError = AO_Property_Expansion;
7515 } else {
7516 // FIXME: emit more specific diag...
7517 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7518 << op->getSourceRange();
7519 return QualType();
7520 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007521 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007522 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007523 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007524 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007525 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007526 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007527 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007528 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007529 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007530 // with the register storage-class specifier.
7531 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007532 // in C++ it is not error to take address of a register
7533 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007534 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007535 !S.getLangOptions().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007536 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007537 }
John McCallba135432009-11-21 08:51:07 +00007538 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007539 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007540 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007541 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007542 // Could be a pointer to member, though, if there is an explicit
7543 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007544 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007545 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007546 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007547 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007548 S.Diag(OpLoc,
7549 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007550 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007551 return QualType();
7552 }
Mike Stump1eb44332009-09-09 15:08:12 +00007553
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007554 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7555 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007556 return S.Context.getMemberPointerType(op->getType(),
7557 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007558 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007559 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007560 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007561 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007562 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007563
Richard Trieu5520f232011-09-07 21:46:33 +00007564 if (AddressOfError != AO_No_Error) {
7565 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7566 return QualType();
7567 }
7568
Eli Friedman441cf102009-05-16 23:27:50 +00007569 if (lval == Expr::LV_IncompleteVoidType) {
7570 // Taking the address of a void variable is technically illegal, but we
7571 // allow it in cases which are otherwise valid.
7572 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007573 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007574 }
7575
Reid Spencer5f016e22007-07-11 17:01:13 +00007576 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007577 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007578 return S.Context.getObjCObjectPointerType(op->getType());
7579 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007580}
7581
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007582/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007583static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7584 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007585 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007586 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007587
John Wiegley429bb272011-04-08 18:41:53 +00007588 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7589 if (ConvResult.isInvalid())
7590 return QualType();
7591 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007592 QualType OpTy = Op->getType();
7593 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007594
7595 if (isa<CXXReinterpretCastExpr>(Op)) {
7596 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7597 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7598 Op->getSourceRange());
7599 }
7600
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007601 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7602 // is an incomplete type or void. It would be possible to warn about
7603 // dereferencing a void pointer, but it's completely well-defined, and such a
7604 // warning is unlikely to catch any mistakes.
7605 if (const PointerType *PT = OpTy->getAs<PointerType>())
7606 Result = PT->getPointeeType();
7607 else if (const ObjCObjectPointerType *OPT =
7608 OpTy->getAs<ObjCObjectPointerType>())
7609 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007610 else {
John McCallfb8721c2011-04-10 19:13:55 +00007611 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007612 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007613 if (PR.take() != Op)
7614 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007615 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007616
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007617 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007618 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007619 << OpTy << Op->getSourceRange();
7620 return QualType();
7621 }
John McCall09431682010-11-18 19:01:18 +00007622
7623 // Dereferences are usually l-values...
7624 VK = VK_LValue;
7625
7626 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007627 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007628 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007629
7630 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007631}
7632
John McCall2de56d12010-08-25 11:45:40 +00007633static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007634 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007635 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007636 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007637 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007638 case tok::periodstar: Opc = BO_PtrMemD; break;
7639 case tok::arrowstar: Opc = BO_PtrMemI; break;
7640 case tok::star: Opc = BO_Mul; break;
7641 case tok::slash: Opc = BO_Div; break;
7642 case tok::percent: Opc = BO_Rem; break;
7643 case tok::plus: Opc = BO_Add; break;
7644 case tok::minus: Opc = BO_Sub; break;
7645 case tok::lessless: Opc = BO_Shl; break;
7646 case tok::greatergreater: Opc = BO_Shr; break;
7647 case tok::lessequal: Opc = BO_LE; break;
7648 case tok::less: Opc = BO_LT; break;
7649 case tok::greaterequal: Opc = BO_GE; break;
7650 case tok::greater: Opc = BO_GT; break;
7651 case tok::exclaimequal: Opc = BO_NE; break;
7652 case tok::equalequal: Opc = BO_EQ; break;
7653 case tok::amp: Opc = BO_And; break;
7654 case tok::caret: Opc = BO_Xor; break;
7655 case tok::pipe: Opc = BO_Or; break;
7656 case tok::ampamp: Opc = BO_LAnd; break;
7657 case tok::pipepipe: Opc = BO_LOr; break;
7658 case tok::equal: Opc = BO_Assign; break;
7659 case tok::starequal: Opc = BO_MulAssign; break;
7660 case tok::slashequal: Opc = BO_DivAssign; break;
7661 case tok::percentequal: Opc = BO_RemAssign; break;
7662 case tok::plusequal: Opc = BO_AddAssign; break;
7663 case tok::minusequal: Opc = BO_SubAssign; break;
7664 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7665 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7666 case tok::ampequal: Opc = BO_AndAssign; break;
7667 case tok::caretequal: Opc = BO_XorAssign; break;
7668 case tok::pipeequal: Opc = BO_OrAssign; break;
7669 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007670 }
7671 return Opc;
7672}
7673
John McCall2de56d12010-08-25 11:45:40 +00007674static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007675 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007676 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007677 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007678 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007679 case tok::plusplus: Opc = UO_PreInc; break;
7680 case tok::minusminus: Opc = UO_PreDec; break;
7681 case tok::amp: Opc = UO_AddrOf; break;
7682 case tok::star: Opc = UO_Deref; break;
7683 case tok::plus: Opc = UO_Plus; break;
7684 case tok::minus: Opc = UO_Minus; break;
7685 case tok::tilde: Opc = UO_Not; break;
7686 case tok::exclaim: Opc = UO_LNot; break;
7687 case tok::kw___real: Opc = UO_Real; break;
7688 case tok::kw___imag: Opc = UO_Imag; break;
7689 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007690 }
7691 return Opc;
7692}
7693
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007694/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7695/// This warning is only emitted for builtin assignment operations. It is also
7696/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00007697static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007698 SourceLocation OpLoc) {
7699 if (!S.ActiveTemplateInstantiations.empty())
7700 return;
7701 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7702 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007703 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7704 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7705 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7706 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7707 if (!LHSDeclRef || !RHSDeclRef ||
7708 LHSDeclRef->getLocation().isMacroID() ||
7709 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007710 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007711 const ValueDecl *LHSDecl =
7712 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7713 const ValueDecl *RHSDecl =
7714 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7715 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007716 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007717 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007718 return;
Richard Trieu268942b2011-09-07 01:33:52 +00007719 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007720 if (RefTy->getPointeeType().isVolatileQualified())
7721 return;
7722
7723 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00007724 << LHSDeclRef->getType()
7725 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007726}
7727
Douglas Gregoreaebc752008-11-06 23:29:22 +00007728/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7729/// operator @p Opc at location @c TokLoc. This routine only supports
7730/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007731ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007732 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007733 Expr *LHSExpr, Expr *RHSExpr) {
7734 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007735 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007736 // The following two variables are used for compound assignment operators
7737 QualType CompLHSTy; // Type of LHS after promotions for computation
7738 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007739 ExprValueKind VK = VK_RValue;
7740 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007741
7742 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007743 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007744 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007745 if (getLangOptions().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00007746 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7747 VK = LHS.get()->getValueKind();
7748 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007749 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007750 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007751 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007752 break;
John McCall2de56d12010-08-25 11:45:40 +00007753 case BO_PtrMemD:
7754 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007755 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007756 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007757 break;
John McCall2de56d12010-08-25 11:45:40 +00007758 case BO_Mul:
7759 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007760 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007761 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007762 break;
John McCall2de56d12010-08-25 11:45:40 +00007763 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007764 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007765 break;
John McCall2de56d12010-08-25 11:45:40 +00007766 case BO_Add:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007767 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007768 break;
John McCall2de56d12010-08-25 11:45:40 +00007769 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007770 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007771 break;
John McCall2de56d12010-08-25 11:45:40 +00007772 case BO_Shl:
7773 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007774 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007775 break;
John McCall2de56d12010-08-25 11:45:40 +00007776 case BO_LE:
7777 case BO_LT:
7778 case BO_GE:
7779 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007780 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007781 break;
John McCall2de56d12010-08-25 11:45:40 +00007782 case BO_EQ:
7783 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007784 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007785 break;
John McCall2de56d12010-08-25 11:45:40 +00007786 case BO_And:
7787 case BO_Xor:
7788 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007789 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007790 break;
John McCall2de56d12010-08-25 11:45:40 +00007791 case BO_LAnd:
7792 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007793 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007794 break;
John McCall2de56d12010-08-25 11:45:40 +00007795 case BO_MulAssign:
7796 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007797 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007798 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007799 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007800 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7801 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007802 break;
John McCall2de56d12010-08-25 11:45:40 +00007803 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007804 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007805 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007806 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7807 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007808 break;
John McCall2de56d12010-08-25 11:45:40 +00007809 case BO_AddAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007810 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7811 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7812 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007813 break;
John McCall2de56d12010-08-25 11:45:40 +00007814 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007815 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7816 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7817 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007818 break;
John McCall2de56d12010-08-25 11:45:40 +00007819 case BO_ShlAssign:
7820 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007821 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007822 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007823 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7824 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007825 break;
John McCall2de56d12010-08-25 11:45:40 +00007826 case BO_AndAssign:
7827 case BO_XorAssign:
7828 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007829 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007830 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007831 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7832 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007833 break;
John McCall2de56d12010-08-25 11:45:40 +00007834 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00007835 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7836 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7837 VK = RHS.get()->getValueKind();
7838 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007839 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007840 break;
7841 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007842 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007843 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007844
7845 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00007846 CheckArrayAccess(LHS.get());
7847 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007848
Eli Friedmanab3a8522009-03-28 01:22:36 +00007849 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00007850 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007851 ResultTy, VK, OK, OpLoc));
Richard Trieu78ea78b2011-09-07 01:49:20 +00007852 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00007853 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007854 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007855 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007856 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00007857 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007858 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007859 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007860}
7861
Sebastian Redlaee3c932009-10-27 12:10:02 +00007862/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7863/// operators are mixed in a way that suggests that the programmer forgot that
7864/// comparison operators have higher precedence. The most typical example of
7865/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007866static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007867 SourceLocation OpLoc, Expr *LHSExpr,
7868 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00007869 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00007870 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7871 RHSopc = static_cast<BinOp::Opcode>(-1);
7872 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7873 LHSopc = BO->getOpcode();
7874 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7875 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007876
7877 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007878 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007879 return;
7880
7881 // Bitwise operations are sometimes used as eager logical ops.
7882 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00007883 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7884 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007885 return;
7886
Richard Trieu78ea78b2011-09-07 01:49:20 +00007887 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7888 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007889 if (!isLeftComp && !isRightComp) return;
7890
Richard Trieu78ea78b2011-09-07 01:49:20 +00007891 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7892 OpLoc)
7893 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7894 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7895 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00007896 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00007897 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7898 RHSExpr->getLocEnd())
7899 : SourceRange(LHSExpr->getLocStart(),
7900 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00007901
7902 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7903 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7904 SuggestParentheses(Self, OpLoc,
7905 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu78ea78b2011-09-07 01:49:20 +00007906 RHSExpr->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00007907 SuggestParentheses(Self, OpLoc,
7908 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7909 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007910}
7911
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007912/// \brief It accepts a '&' expr that is inside a '|' one.
7913/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7914/// in parentheses.
7915static void
7916EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7917 BinaryOperator *Bop) {
7918 assert(Bop->getOpcode() == BO_And);
7919 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7920 << Bop->getSourceRange() << OpLoc;
7921 SuggestParentheses(Self, Bop->getOperatorLoc(),
7922 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7923 Bop->getSourceRange());
7924}
7925
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007926/// \brief It accepts a '&&' expr that is inside a '||' one.
7927/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7928/// in parentheses.
7929static void
7930EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007931 BinaryOperator *Bop) {
7932 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007933 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7934 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007935 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007936 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007937 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007938}
7939
7940/// \brief Returns true if the given expression can be evaluated as a constant
7941/// 'true'.
7942static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7943 bool Res;
7944 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7945}
7946
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007947/// \brief Returns true if the given expression can be evaluated as a constant
7948/// 'false'.
7949static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7950 bool Res;
7951 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7952}
7953
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007954/// \brief Look for '&&' in the left hand of a '||' expr.
7955static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007956 Expr *LHSExpr, Expr *RHSExpr) {
7957 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007958 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007959 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007960 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007961 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007962 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7963 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7964 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7965 } else if (Bop->getOpcode() == BO_LOr) {
7966 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7967 // If it's "a || b && 1 || c" we didn't warn earlier for
7968 // "a || b && 1", but warn now.
7969 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7970 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7971 }
7972 }
7973 }
7974}
7975
7976/// \brief Look for '&&' in the right hand of a '||' expr.
7977static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00007978 Expr *LHSExpr, Expr *RHSExpr) {
7979 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007980 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007981 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00007982 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007983 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007984 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7985 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7986 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007987 }
7988 }
7989}
7990
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007991/// \brief Look for '&' in the left or right hand of a '|' expr.
7992static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7993 Expr *OrArg) {
7994 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7995 if (Bop->getOpcode() == BO_And)
7996 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7997 }
7998}
7999
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008000/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008001/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008002static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008003 SourceLocation OpLoc, Expr *LHSExpr,
8004 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008005 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008006 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008007 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008008
8009 // Diagnose "arg1 & arg2 | arg3"
8010 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008011 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8012 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008013 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008014
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008015 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8016 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008017 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008018 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8019 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008020 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008021}
8022
Reid Spencer5f016e22007-07-11 17:01:13 +00008023// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008024ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008025 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008026 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008027 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008028 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8029 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008030
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008031 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008032 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008033
Richard Trieubefece12011-09-07 02:02:10 +00008034 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008035}
8036
John McCall3c3b7f92011-10-25 17:37:35 +00008037/// Build an overloaded binary operator expression in the given scope.
8038static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8039 BinaryOperatorKind Opc,
8040 Expr *LHS, Expr *RHS) {
8041 // Find all of the overloaded operators visible from this
8042 // point. We perform both an operator-name lookup from the local
8043 // scope and an argument-dependent lookup based on the types of
8044 // the arguments.
8045 UnresolvedSet<16> Functions;
8046 OverloadedOperatorKind OverOp
8047 = BinaryOperator::getOverloadedOperator(Opc);
8048 if (Sc && OverOp != OO_None)
8049 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8050 RHS->getType(), Functions);
8051
8052 // Build the (potentially-overloaded, potentially-dependent)
8053 // binary operation.
8054 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8055}
8056
John McCall60d7b3a2010-08-24 06:29:42 +00008057ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008058 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008059 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008060 // We want to end up calling one of checkPseudoObjectAssignment
8061 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8062 // both expressions are overloadable or either is type-dependent),
8063 // or CreateBuiltinBinOp (in any other case). We also want to get
8064 // any placeholder types out of the way.
8065
John McCall3c3b7f92011-10-25 17:37:35 +00008066 // Handle pseudo-objects in the LHS.
8067 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8068 // Assignments with a pseudo-object l-value need special analysis.
8069 if (pty->getKind() == BuiltinType::PseudoObject &&
8070 BinaryOperator::isAssignmentOp(Opc))
8071 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8072
8073 // Don't resolve overloads if the other type is overloadable.
8074 if (pty->getKind() == BuiltinType::Overload) {
8075 // We can't actually test that if we still have a placeholder,
8076 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008077 // code below are valid when the LHS is an overload set. Note
8078 // that an overload set can be dependently-typed, but it never
8079 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008080 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8081 if (resolvedRHS.isInvalid()) return ExprError();
8082 RHSExpr = resolvedRHS.take();
8083
John McCallac516502011-10-28 01:04:34 +00008084 if (RHSExpr->isTypeDependent() ||
8085 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008086 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8087 }
8088
8089 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8090 if (LHS.isInvalid()) return ExprError();
8091 LHSExpr = LHS.take();
8092 }
8093
8094 // Handle pseudo-objects in the RHS.
8095 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8096 // An overload in the RHS can potentially be resolved by the type
8097 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008098 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8099 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8100 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8101
John McCall3c3b7f92011-10-25 17:37:35 +00008102 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008103 }
John McCall3c3b7f92011-10-25 17:37:35 +00008104
8105 // Don't resolve overloads if the other type is overloadable.
8106 if (pty->getKind() == BuiltinType::Overload &&
8107 LHSExpr->getType()->isOverloadableType())
8108 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8109
8110 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8111 if (!resolvedRHS.isUsable()) return ExprError();
8112 RHSExpr = resolvedRHS.take();
8113 }
8114
John McCall01b2e4e2010-12-06 05:26:58 +00008115 if (getLangOptions().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008116 // If either expression is type-dependent, always build an
8117 // overloaded op.
8118 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8119 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008120
John McCallac516502011-10-28 01:04:34 +00008121 // Otherwise, build an overloaded op if either expression has an
8122 // overloadable type.
8123 if (LHSExpr->getType()->isOverloadableType() ||
8124 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008125 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008126 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008127
Douglas Gregoreaebc752008-11-06 23:29:22 +00008128 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008129 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008130}
8131
John McCall60d7b3a2010-08-24 06:29:42 +00008132ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008133 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008134 Expr *InputExpr) {
8135 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008136 ExprValueKind VK = VK_RValue;
8137 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008138 QualType resultType;
8139 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008140 case UO_PreInc:
8141 case UO_PreDec:
8142 case UO_PostInc:
8143 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008144 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008145 Opc == UO_PreInc ||
8146 Opc == UO_PostInc,
8147 Opc == UO_PreInc ||
8148 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008149 break;
John McCall2de56d12010-08-25 11:45:40 +00008150 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008151 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008152 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008153 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008154 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8155 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008156 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008157 }
John McCall2de56d12010-08-25 11:45:40 +00008158 case UO_Plus:
8159 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008160 Input = UsualUnaryConversions(Input.take());
8161 if (Input.isInvalid()) return ExprError();
8162 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008163 if (resultType->isDependentType())
8164 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008165 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8166 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008167 break;
8168 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8169 resultType->isEnumeralType())
8170 break;
8171 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008172 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008173 resultType->isPointerType())
8174 break;
8175
Sebastian Redl0eb23302009-01-19 00:08:26 +00008176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008177 << resultType << Input.get()->getSourceRange());
8178
John McCall2de56d12010-08-25 11:45:40 +00008179 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008180 Input = UsualUnaryConversions(Input.take());
8181 if (Input.isInvalid()) return ExprError();
8182 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008183 if (resultType->isDependentType())
8184 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008185 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8186 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8187 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008188 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008189 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008190 else if (resultType->hasIntegerRepresentation())
8191 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008192 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008193 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008194 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008195 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008196 break;
John Wiegley429bb272011-04-08 18:41:53 +00008197
John McCall2de56d12010-08-25 11:45:40 +00008198 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008199 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008200 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8201 if (Input.isInvalid()) return ExprError();
8202 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008203
8204 // Though we still have to promote half FP to float...
8205 if (resultType->isHalfType()) {
8206 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8207 resultType = Context.FloatTy;
8208 }
8209
Sebastian Redl28507842009-02-26 14:39:58 +00008210 if (resultType->isDependentType())
8211 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008212 if (resultType->isScalarType()) {
8213 // C99 6.5.3.3p1: ok, fallthrough;
8214 if (Context.getLangOptions().CPlusPlus) {
8215 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8216 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008217 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8218 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008219 }
John McCall2cd11fe2010-10-12 02:09:17 +00008220 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008221 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008222 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008223 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008224
Reid Spencer5f016e22007-07-11 17:01:13 +00008225 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008226 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008227 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008228 break;
John McCall2de56d12010-08-25 11:45:40 +00008229 case UO_Real:
8230 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008231 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008232 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008233 if (Input.isInvalid()) return ExprError();
8234 if (Input.get()->getValueKind() != VK_RValue &&
8235 Input.get()->getObjectKind() == OK_Ordinary)
8236 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008237 break;
John McCall2de56d12010-08-25 11:45:40 +00008238 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008239 resultType = Input.get()->getType();
8240 VK = Input.get()->getValueKind();
8241 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008242 break;
8243 }
John Wiegley429bb272011-04-08 18:41:53 +00008244 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008245 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008246
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008247 // Check for array bounds violations in the operand of the UnaryOperator,
8248 // except for the '*' and '&' operators that have to be handled specially
8249 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8250 // that are explicitly defined as valid by the standard).
8251 if (Opc != UO_AddrOf && Opc != UO_Deref)
8252 CheckArrayAccess(Input.get());
8253
John Wiegley429bb272011-04-08 18:41:53 +00008254 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008255 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008256}
8257
John McCall60d7b3a2010-08-24 06:29:42 +00008258ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008259 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008260 // First things first: handle placeholders so that the
8261 // overloaded-operator check considers the right type.
8262 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8263 // Increment and decrement of pseudo-object references.
8264 if (pty->getKind() == BuiltinType::PseudoObject &&
8265 UnaryOperator::isIncrementDecrementOp(Opc))
8266 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8267
8268 // extension is always a builtin operator.
8269 if (Opc == UO_Extension)
8270 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8271
8272 // & gets special logic for several kinds of placeholder.
8273 // The builtin code knows what to do.
8274 if (Opc == UO_AddrOf &&
8275 (pty->getKind() == BuiltinType::Overload ||
8276 pty->getKind() == BuiltinType::UnknownAny ||
8277 pty->getKind() == BuiltinType::BoundMember))
8278 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8279
8280 // Anything else needs to be handled now.
8281 ExprResult Result = CheckPlaceholderExpr(Input);
8282 if (Result.isInvalid()) return ExprError();
8283 Input = Result.take();
8284 }
8285
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008286 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008287 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008288 // Find all of the overloaded operators visible from this
8289 // point. We perform both an operator-name lookup from the local
8290 // scope and an argument-dependent lookup based on the types of
8291 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008292 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008293 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008294 if (S && OverOp != OO_None)
8295 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8296 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008297
John McCall9ae2f072010-08-23 23:25:46 +00008298 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008299 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008300
John McCall9ae2f072010-08-23 23:25:46 +00008301 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008302}
8303
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008304// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008305ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008306 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008307 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008308}
8309
Steve Naroff1b273c42007-09-16 14:56:35 +00008310/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008311ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008312 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008313 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008314 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008315 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008316 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008317}
8318
John McCallf85e1932011-06-15 23:02:42 +00008319/// Given the last statement in a statement-expression, check whether
8320/// the result is a producing expression (like a call to an
8321/// ns_returns_retained function) and, if so, rebuild it to hoist the
8322/// release out of the full-expression. Otherwise, return null.
8323/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008324static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008325 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008326 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008327 if (!cleanups) return 0;
8328
8329 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008330 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008331 return 0;
8332
8333 // Splice out the cast. This shouldn't modify any interesting
8334 // features of the statement.
8335 Expr *producer = cast->getSubExpr();
8336 assert(producer->getType() == cast->getType());
8337 assert(producer->getValueKind() == cast->getValueKind());
8338 cleanups->setSubExpr(producer);
8339 return cleanups;
8340}
8341
John McCall60d7b3a2010-08-24 06:29:42 +00008342ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008343Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008344 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008345 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8346 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8347
Douglas Gregordd8f5692010-03-10 04:54:39 +00008348 bool isFileScope
8349 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008350 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008351 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008352
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008353 // FIXME: there are a variety of strange constraints to enforce here, for
8354 // example, it is not possible to goto into a stmt expression apparently.
8355 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008356
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008357 // If there are sub stmts in the compound stmt, take the type of the last one
8358 // as the type of the stmtexpr.
8359 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008360 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008361 if (!Compound->body_empty()) {
8362 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008363 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008364 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008365 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8366 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008367 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008368 }
John McCallf85e1932011-06-15 23:02:42 +00008369
John Wiegley429bb272011-04-08 18:41:53 +00008370 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008371 // Do function/array conversion on the last expression, but not
8372 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008373 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8374 if (LastExpr.isInvalid())
8375 return ExprError();
8376 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008377
John Wiegley429bb272011-04-08 18:41:53 +00008378 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008379 // In ARC, if the final expression ends in a consume, splice
8380 // the consume out and bind it later. In the alternate case
8381 // (when dealing with a retainable type), the result
8382 // initialization will create a produce. In both cases the
8383 // result will be +1, and we'll need to balance that out with
8384 // a bind.
8385 if (Expr *rebuiltLastStmt
8386 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8387 LastExpr = rebuiltLastStmt;
8388 } else {
8389 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008390 InitializedEntity::InitializeResult(LPLoc,
8391 Ty,
8392 false),
8393 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008394 LastExpr);
8395 }
8396
John Wiegley429bb272011-04-08 18:41:53 +00008397 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008398 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008399 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008400 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008401 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008402 else
John Wiegley429bb272011-04-08 18:41:53 +00008403 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008404 StmtExprMayBindToTemp = true;
8405 }
8406 }
8407 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008409
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008410 // FIXME: Check that expression type is complete/non-abstract; statement
8411 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008412 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8413 if (StmtExprMayBindToTemp)
8414 return MaybeBindToTemporary(ResStmtExpr);
8415 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008416}
Steve Naroffd34e9152007-08-01 22:05:33 +00008417
John McCall60d7b3a2010-08-24 06:29:42 +00008418ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008419 TypeSourceInfo *TInfo,
8420 OffsetOfComponent *CompPtr,
8421 unsigned NumComponents,
8422 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008423 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008424 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008425 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008426
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008427 // We must have at least one component that refers to the type, and the first
8428 // one is known to be a field designator. Verify that the ArgTy represents
8429 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008430 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008431 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8432 << ArgTy << TypeRange);
8433
8434 // Type must be complete per C99 7.17p3 because a declaring a variable
8435 // with an incomplete type would be ill-formed.
8436 if (!Dependent
8437 && RequireCompleteType(BuiltinLoc, ArgTy,
8438 PDiag(diag::err_offsetof_incomplete_type)
8439 << TypeRange))
8440 return ExprError();
8441
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008442 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8443 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008444 // FIXME: This diagnostic isn't actually visible because the location is in
8445 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008446 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008447 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8448 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008449
8450 bool DidWarnAboutNonPOD = false;
8451 QualType CurrentType = ArgTy;
8452 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008453 SmallVector<OffsetOfNode, 4> Comps;
8454 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008455 for (unsigned i = 0; i != NumComponents; ++i) {
8456 const OffsetOfComponent &OC = CompPtr[i];
8457 if (OC.isBrackets) {
8458 // Offset of an array sub-field. TODO: Should we allow vector elements?
8459 if (!CurrentType->isDependentType()) {
8460 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8461 if(!AT)
8462 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8463 << CurrentType);
8464 CurrentType = AT->getElementType();
8465 } else
8466 CurrentType = Context.DependentTy;
8467
Richard Smithea011432011-10-17 23:29:39 +00008468 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8469 if (IdxRval.isInvalid())
8470 return ExprError();
8471 Expr *Idx = IdxRval.take();
8472
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008473 // The expression must be an integral expression.
8474 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008475 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8476 !Idx->getType()->isIntegerType())
8477 return ExprError(Diag(Idx->getLocStart(),
8478 diag::err_typecheck_subscript_not_integer)
8479 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00008480
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008481 // Record this array index.
8482 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00008483 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008484 continue;
8485 }
8486
8487 // Offset of a field.
8488 if (CurrentType->isDependentType()) {
8489 // We have the offset of a field, but we can't look into the dependent
8490 // type. Just record the identifier of the field.
8491 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8492 CurrentType = Context.DependentTy;
8493 continue;
8494 }
8495
8496 // We need to have a complete type to look into.
8497 if (RequireCompleteType(OC.LocStart, CurrentType,
8498 diag::err_offsetof_incomplete_type))
8499 return ExprError();
8500
8501 // Look for the designated field.
8502 const RecordType *RC = CurrentType->getAs<RecordType>();
8503 if (!RC)
8504 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8505 << CurrentType);
8506 RecordDecl *RD = RC->getDecl();
8507
8508 // C++ [lib.support.types]p5:
8509 // The macro offsetof accepts a restricted set of type arguments in this
8510 // International Standard. type shall be a POD structure or a POD union
8511 // (clause 9).
8512 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8513 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008514 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008515 PDiag(diag::warn_offsetof_non_pod_type)
8516 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8517 << CurrentType))
8518 DidWarnAboutNonPOD = true;
8519 }
8520
8521 // Look for the field.
8522 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8523 LookupQualifiedName(R, RD);
8524 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008525 IndirectFieldDecl *IndirectMemberDecl = 0;
8526 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008527 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008528 MemberDecl = IndirectMemberDecl->getAnonField();
8529 }
8530
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008531 if (!MemberDecl)
8532 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8533 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8534 OC.LocEnd));
8535
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008536 // C99 7.17p3:
8537 // (If the specified member is a bit-field, the behavior is undefined.)
8538 //
8539 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008540 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008541 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8542 << MemberDecl->getDeclName()
8543 << SourceRange(BuiltinLoc, RParenLoc);
8544 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8545 return ExprError();
8546 }
Eli Friedman19410a72010-08-05 10:11:36 +00008547
8548 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008549 if (IndirectMemberDecl)
8550 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008551
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008552 // If the member was found in a base class, introduce OffsetOfNodes for
8553 // the base class indirections.
8554 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8555 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008556 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008557 CXXBasePath &Path = Paths.front();
8558 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8559 B != BEnd; ++B)
8560 Comps.push_back(OffsetOfNode(B->Base));
8561 }
Eli Friedman19410a72010-08-05 10:11:36 +00008562
Francois Pichet87c2e122010-11-21 06:08:52 +00008563 if (IndirectMemberDecl) {
8564 for (IndirectFieldDecl::chain_iterator FI =
8565 IndirectMemberDecl->chain_begin(),
8566 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8567 assert(isa<FieldDecl>(*FI));
8568 Comps.push_back(OffsetOfNode(OC.LocStart,
8569 cast<FieldDecl>(*FI), OC.LocEnd));
8570 }
8571 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008572 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008573
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008574 CurrentType = MemberDecl->getType().getNonReferenceType();
8575 }
8576
8577 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8578 TInfo, Comps.data(), Comps.size(),
8579 Exprs.data(), Exprs.size(), RParenLoc));
8580}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008581
John McCall60d7b3a2010-08-24 06:29:42 +00008582ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008583 SourceLocation BuiltinLoc,
8584 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008585 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00008586 OffsetOfComponent *CompPtr,
8587 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008588 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00008589
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008590 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008591 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008592 if (ArgTy.isNull())
8593 return ExprError();
8594
Eli Friedman5a15dc12010-08-05 10:15:45 +00008595 if (!ArgTInfo)
8596 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8597
8598 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00008599 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008600}
8601
8602
John McCall60d7b3a2010-08-24 06:29:42 +00008603ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008604 Expr *CondExpr,
8605 Expr *LHSExpr, Expr *RHSExpr,
8606 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008607 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8608
John McCallf89e55a2010-11-18 06:31:45 +00008609 ExprValueKind VK = VK_RValue;
8610 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008611 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008612 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008613 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008614 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008615 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008616 } else {
8617 // The conditional expression is required to be a constant expression.
8618 llvm::APSInt condEval(32);
8619 SourceLocation ExpLoc;
8620 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008621 return ExprError(Diag(ExpLoc,
8622 diag::err_typecheck_choose_expr_requires_constant)
8623 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008624
Sebastian Redl28507842009-02-26 14:39:58 +00008625 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008626 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8627
8628 resType = ActiveExpr->getType();
8629 ValueDependent = ActiveExpr->isValueDependent();
8630 VK = ActiveExpr->getValueKind();
8631 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008632 }
8633
Sebastian Redlf53597f2009-03-15 17:47:39 +00008634 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008635 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008636 resType->isDependentType(),
8637 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008638}
8639
Steve Naroff4eb206b2008-09-03 18:15:37 +00008640//===----------------------------------------------------------------------===//
8641// Clang Extensions.
8642//===----------------------------------------------------------------------===//
8643
8644/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00008645void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008646 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00008647 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008648 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00008649 if (CurScope)
8650 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008651 else
8652 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00008653
8654 // Enter a new evaluation context to insulate the block from any
8655 // cleanups from the enclosing full-expression.
8656 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00008657}
8658
Mike Stump98eb8a72009-02-04 22:31:32 +00008659void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008660 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008661 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008662 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008663
John McCallbf1a0282010-06-04 23:28:52 +00008664 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008665 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008666
John McCall711c52b2011-01-05 12:14:39 +00008667 // GetTypeForDeclarator always produces a function type for a block
8668 // literal signature. Furthermore, it is always a FunctionProtoType
8669 // unless the function was written with a typedef.
8670 assert(T->isFunctionType() &&
8671 "GetTypeForDeclarator made a non-function block signature");
8672
8673 // Look for an explicit signature in that function type.
8674 FunctionProtoTypeLoc ExplicitSignature;
8675
8676 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8677 if (isa<FunctionProtoTypeLoc>(tmp)) {
8678 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8679
8680 // Check whether that explicit signature was synthesized by
8681 // GetTypeForDeclarator. If so, don't save that as part of the
8682 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008683 if (ExplicitSignature.getLocalRangeBegin() ==
8684 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008685 // This would be much cheaper if we stored TypeLocs instead of
8686 // TypeSourceInfos.
8687 TypeLoc Result = ExplicitSignature.getResultLoc();
8688 unsigned Size = Result.getFullDataSize();
8689 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8690 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8691
8692 ExplicitSignature = FunctionProtoTypeLoc();
8693 }
John McCall82dc0092010-06-04 11:21:44 +00008694 }
Mike Stump1eb44332009-09-09 15:08:12 +00008695
John McCall711c52b2011-01-05 12:14:39 +00008696 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8697 CurBlock->FunctionType = T;
8698
8699 const FunctionType *Fn = T->getAs<FunctionType>();
8700 QualType RetTy = Fn->getResultType();
8701 bool isVariadic =
8702 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8703
John McCallc71a4912010-06-04 19:02:56 +00008704 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008705
John McCall82dc0092010-06-04 11:21:44 +00008706 // Don't allow returning a objc interface by value.
8707 if (RetTy->isObjCObjectType()) {
8708 Diag(ParamInfo.getSourceRange().getBegin(),
8709 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8710 return;
8711 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008712
John McCall82dc0092010-06-04 11:21:44 +00008713 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008714 // return type. TODO: what should we do with declarators like:
8715 // ^ * { ... }
8716 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008717 if (RetTy != Context.DependentTy)
8718 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008719
John McCall82dc0092010-06-04 11:21:44 +00008720 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008721 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008722 if (ExplicitSignature) {
8723 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8724 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008725 if (Param->getIdentifier() == 0 &&
8726 !Param->isImplicit() &&
8727 !Param->isInvalidDecl() &&
8728 !getLangOptions().CPlusPlus)
8729 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008730 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008731 }
John McCall82dc0092010-06-04 11:21:44 +00008732
8733 // Fake up parameter variables if we have a typedef, like
8734 // ^ fntype { ... }
8735 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8736 for (FunctionProtoType::arg_type_iterator
8737 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8738 ParmVarDecl *Param =
8739 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8740 ParamInfo.getSourceRange().getBegin(),
8741 *I);
John McCallc71a4912010-06-04 19:02:56 +00008742 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008743 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008744 }
John McCall82dc0092010-06-04 11:21:44 +00008745
John McCallc71a4912010-06-04 19:02:56 +00008746 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008747 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00008748 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00008749 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8750 CurBlock->TheDecl->param_end(),
8751 /*CheckParameterNames=*/false);
8752 }
8753
John McCall82dc0092010-06-04 11:21:44 +00008754 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008755 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008756
John McCallc71a4912010-06-04 19:02:56 +00008757 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008758 Diag(ParamInfo.getAttributes()->getLoc(),
8759 diag::warn_attribute_sentinel_not_variadic) << 1;
8760 // FIXME: remove the attribute.
8761 }
8762
8763 // Put the parameter variables in scope. We can bail out immediately
8764 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008765 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008766 return;
8767
Steve Naroff090276f2008-10-10 01:28:17 +00008768 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008769 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8770 (*AI)->setOwningFunction(CurBlock->TheDecl);
8771
Steve Naroff090276f2008-10-10 01:28:17 +00008772 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008773 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008774 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008775
Steve Naroff090276f2008-10-10 01:28:17 +00008776 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008777 }
John McCall7a9813c2010-01-22 00:28:27 +00008778 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008779}
8780
8781/// ActOnBlockError - If there is an error parsing a block, this callback
8782/// is invoked to pop the information about the block from the action impl.
8783void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00008784 // Leave the expression-evaluation context.
8785 DiscardCleanupsInEvaluationContext();
8786 PopExpressionEvaluationContext();
8787
Steve Naroff4eb206b2008-09-03 18:15:37 +00008788 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008789 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008790 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008791}
8792
8793/// ActOnBlockStmtExpr - This is called when the body of a block statement
8794/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008795ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008796 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008797 // If blocks are disabled, emit an error.
8798 if (!LangOpts.Blocks)
8799 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008800
John McCall538773c2011-11-11 03:19:12 +00008801 // Leave the expression-evaluation context.
8802 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8803 PopExpressionEvaluationContext();
8804
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008805 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008806
Steve Naroff090276f2008-10-10 01:28:17 +00008807 PopDeclContext();
8808
Steve Naroff4eb206b2008-09-03 18:15:37 +00008809 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008810 if (!BSI->ReturnType.isNull())
8811 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008812
Mike Stump56925862009-07-28 22:04:01 +00008813 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008814 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008815
John McCall469a1eb2011-02-02 13:00:07 +00008816 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008817 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8818 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008819
John McCallc71a4912010-06-04 19:02:56 +00008820 // If the user wrote a function type in some form, try to use that.
8821 if (!BSI->FunctionType.isNull()) {
8822 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8823
8824 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8825 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8826
8827 // Turn protoless block types into nullary block types.
8828 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008829 FunctionProtoType::ExtProtoInfo EPI;
8830 EPI.ExtInfo = Ext;
8831 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008832
8833 // Otherwise, if we don't need to change anything about the function type,
8834 // preserve its sugar structure.
8835 } else if (FTy->getResultType() == RetTy &&
8836 (!NoReturn || FTy->getNoReturnAttr())) {
8837 BlockTy = BSI->FunctionType;
8838
8839 // Otherwise, make the minimal modifications to the function type.
8840 } else {
8841 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008842 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8843 EPI.TypeQuals = 0; // FIXME: silently?
8844 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008845 BlockTy = Context.getFunctionType(RetTy,
8846 FPT->arg_type_begin(),
8847 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008848 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008849 }
8850
8851 // If we don't have a function type, just build one from nothing.
8852 } else {
John McCalle23cf432010-12-14 08:05:40 +00008853 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008854 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008855 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008857
John McCallc71a4912010-06-04 19:02:56 +00008858 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8859 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008860 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008861
Chris Lattner17a78302009-04-19 05:28:12 +00008862 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008863 if (getCurFunction()->NeedsScopeChecking() &&
8864 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008865 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008866
Chris Lattnere476bdc2011-02-17 23:58:47 +00008867 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008868
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008869 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8870 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8871 const VarDecl *variable = ci->getVariable();
8872 QualType T = variable->getType();
8873 QualType::DestructionKind destructKind = T.isDestructedType();
8874 if (destructKind != QualType::DK_none)
8875 getCurFunction()->setHasBranchProtectedScope();
8876 }
8877
Douglas Gregorf8b7f712011-09-06 20:46:03 +00008878 computeNRVO(Body, getCurBlock());
8879
Benjamin Kramerd2486192011-07-12 14:11:05 +00008880 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8881 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8882 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8883
John McCall80ee6e82011-11-10 05:35:25 +00008884 // If the block isn't obviously global, i.e. it captures anything at
8885 // all, mark this full-expression as needing a cleanup.
8886 if (Result->getBlockDecl()->hasCaptures()) {
8887 ExprCleanupObjects.push_back(Result->getBlockDecl());
8888 ExprNeedsCleanups = true;
8889 }
8890
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008891 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008892}
8893
John McCall60d7b3a2010-08-24 06:29:42 +00008894ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008895 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008896 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008897 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00008898 GetTypeFromParser(Ty, &TInfo);
8899 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008900}
8901
John McCall60d7b3a2010-08-24 06:29:42 +00008902ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008903 Expr *E, TypeSourceInfo *TInfo,
8904 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008905 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008906
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008907 // Get the va_list type
8908 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008909 if (VaListType->isArrayType()) {
8910 // Deal with implicit array decay; for example, on x86-64,
8911 // va_list is an array, but it's supposed to decay to
8912 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008913 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008914 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008915 ExprResult Result = UsualUnaryConversions(E);
8916 if (Result.isInvalid())
8917 return ExprError();
8918 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008919 } else {
8920 // Otherwise, the va_list argument must be an l-value because
8921 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008922 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008923 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008924 return ExprError();
8925 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008926
Douglas Gregordd027302009-05-19 23:10:31 +00008927 if (!E->isTypeDependent() &&
8928 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008929 return ExprError(Diag(E->getLocStart(),
8930 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008931 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008932 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008933
David Majnemer0adde122011-06-14 05:17:32 +00008934 if (!TInfo->getType()->isDependentType()) {
8935 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8936 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8937 << TInfo->getTypeLoc().getSourceRange()))
8938 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008939
David Majnemer0adde122011-06-14 05:17:32 +00008940 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8941 TInfo->getType(),
8942 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8943 << TInfo->getTypeLoc().getSourceRange()))
8944 return ExprError();
8945
Douglas Gregor4eb75222011-07-30 06:45:27 +00008946 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008947 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008948 TInfo->getType()->isObjCLifetimeType()
8949 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8950 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008951 << TInfo->getType()
8952 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008953 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008954
8955 // Check for va_arg where arguments of the given type will be promoted
8956 // (i.e. this va_arg is guaranteed to have undefined behavior).
8957 QualType PromoteType;
8958 if (TInfo->getType()->isPromotableIntegerType()) {
8959 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8960 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8961 PromoteType = QualType();
8962 }
8963 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8964 PromoteType = Context.DoubleTy;
8965 if (!PromoteType.isNull())
8966 Diag(TInfo->getTypeLoc().getBeginLoc(),
8967 diag::warn_second_parameter_to_va_arg_never_compatible)
8968 << TInfo->getType()
8969 << PromoteType
8970 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008971 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008972
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008973 QualType T = TInfo->getType().getNonLValueExprType(Context);
8974 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008975}
8976
John McCall60d7b3a2010-08-24 06:29:42 +00008977ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008978 // The type of __null will be int or long, depending on the size of
8979 // pointers on the target.
8980 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008981 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8982 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008983 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008984 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008985 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00008986 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008987 Ty = Context.LongLongTy;
8988 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00008989 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008990 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008991
Sebastian Redlf53597f2009-03-15 17:47:39 +00008992 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008993}
8994
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008995static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008996 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008997 if (!SemaRef.getLangOptions().ObjC1)
8998 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008999
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009000 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9001 if (!PT)
9002 return;
9003
9004 // Check if the destination is of type 'id'.
9005 if (!PT->isObjCIdType()) {
9006 // Check if the destination is the 'NSString' interface.
9007 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9008 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9009 return;
9010 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009011
John McCall4b9c2d22011-11-06 09:01:30 +00009012 // Ignore any parens, implicit casts (should only be
9013 // array-to-pointer decays), and not-so-opaque values. The last is
9014 // important for making this trigger for property assignments.
9015 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9016 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9017 if (OV->getSourceExpr())
9018 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9019
9020 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009021 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009022 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009023
Douglas Gregor849b2432010-03-31 17:46:05 +00009024 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009025}
9026
Chris Lattner5cf216b2008-01-04 18:04:52 +00009027bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9028 SourceLocation Loc,
9029 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009030 Expr *SrcExpr, AssignmentAction Action,
9031 bool *Complained) {
9032 if (Complained)
9033 *Complained = false;
9034
Chris Lattner5cf216b2008-01-04 18:04:52 +00009035 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009036 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009037 bool isInvalid = false;
9038 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009039 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009040 ConversionFixItGenerator ConvHints;
9041 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009042 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009043
Chris Lattner5cf216b2008-01-04 18:04:52 +00009044 switch (ConvTy) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009045 default: llvm_unreachable("Unknown conversion type");
Chris Lattner5cf216b2008-01-04 18:04:52 +00009046 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009047 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009048 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009049 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9050 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009051 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009052 case IntToPointer:
9053 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009054 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9055 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009056 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009057 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009058 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009059 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009060 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9061 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009062 if (Hint.isNull() && !CheckInferredResultType) {
9063 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9064 }
9065 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009066 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009067 case IncompatiblePointerSign:
9068 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9069 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009070 case FunctionVoidPointer:
9071 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9072 break;
John McCall86c05f32011-02-01 00:10:29 +00009073 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009074 // Perform array-to-pointer decay if necessary.
9075 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9076
John McCall86c05f32011-02-01 00:10:29 +00009077 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9078 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9079 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9080 DiagKind = diag::err_typecheck_incompatible_address_space;
9081 break;
John McCallf85e1932011-06-15 23:02:42 +00009082
9083
9084 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009085 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009086 break;
John McCall86c05f32011-02-01 00:10:29 +00009087 }
9088
9089 llvm_unreachable("unknown error case for discarding qualifiers!");
9090 // fallthrough
9091 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009092 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009093 // If the qualifiers lost were because we were applying the
9094 // (deprecated) C++ conversion from a string literal to a char*
9095 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9096 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009097 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009098 // bit of refactoring (so that the second argument is an
9099 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009100 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009101 // C++ semantics.
9102 if (getLangOptions().CPlusPlus &&
9103 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9104 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009105 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9106 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009107 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009108 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009109 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009110 case IntToBlockPointer:
9111 DiagKind = diag::err_int_to_block_pointer;
9112 break;
9113 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009114 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009115 break;
Steve Naroff39579072008-10-14 22:18:38 +00009116 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009117 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009118 // it can give a more specific diagnostic.
9119 DiagKind = diag::warn_incompatible_qualified_id;
9120 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009121 case IncompatibleVectors:
9122 DiagKind = diag::warn_incompatible_vectors;
9123 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009124 case IncompatibleObjCWeakRef:
9125 DiagKind = diag::err_arc_weak_unavailable_assign;
9126 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009127 case Incompatible:
9128 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009129 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9130 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009131 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009132 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009133 break;
9134 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009135
Douglas Gregord4eea832010-04-09 00:35:39 +00009136 QualType FirstType, SecondType;
9137 switch (Action) {
9138 case AA_Assigning:
9139 case AA_Initializing:
9140 // The destination type comes first.
9141 FirstType = DstType;
9142 SecondType = SrcType;
9143 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009144
Douglas Gregord4eea832010-04-09 00:35:39 +00009145 case AA_Returning:
9146 case AA_Passing:
9147 case AA_Converting:
9148 case AA_Sending:
9149 case AA_Casting:
9150 // The source type comes first.
9151 FirstType = SrcType;
9152 SecondType = DstType;
9153 break;
9154 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009155
Anna Zaks67221552011-07-28 19:51:27 +00009156 PartialDiagnostic FDiag = PDiag(DiagKind);
9157 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9158
9159 // If we can fix the conversion, suggest the FixIts.
9160 assert(ConvHints.isNull() || Hint.isNull());
9161 if (!ConvHints.isNull()) {
9162 for (llvm::SmallVector<FixItHint, 1>::iterator
9163 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9164 HI != HE; ++HI)
9165 FDiag << *HI;
9166 } else {
9167 FDiag << Hint;
9168 }
9169 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9170
Richard Trieu6efd4c52011-11-23 22:32:32 +00009171 if (MayHaveFunctionDiff)
9172 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9173
Anna Zaks67221552011-07-28 19:51:27 +00009174 Diag(Loc, FDiag);
9175
Richard Trieu6efd4c52011-11-23 22:32:32 +00009176 if (SecondType == Context.OverloadTy)
9177 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9178 FirstType);
9179
Douglas Gregor926df6c2011-06-11 01:09:30 +00009180 if (CheckInferredResultType)
9181 EmitRelatedResultTypeNote(SrcExpr);
9182
Douglas Gregora41a8c52010-04-22 00:20:18 +00009183 if (Complained)
9184 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009185 return isInvalid;
9186}
Anders Carlssone21555e2008-11-30 19:50:32 +00009187
Chris Lattner3bf68932009-04-25 21:59:05 +00009188bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009189 llvm::APSInt ICEResult;
9190 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9191 if (Result)
9192 *Result = ICEResult;
9193 return false;
9194 }
9195
Anders Carlssone21555e2008-11-30 19:50:32 +00009196 Expr::EvalResult EvalResult;
9197
Richard Smith51f47082011-10-29 00:50:52 +00009198 if (!E->EvaluateAsRValue(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009199 EvalResult.HasSideEffects) {
9200 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9201
9202 if (EvalResult.Diag) {
9203 // We only show the note if it's not the usual "invalid subexpression"
9204 // or if it's actually in a subexpression.
9205 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9206 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9207 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9208 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009209
Anders Carlssone21555e2008-11-30 19:50:32 +00009210 return true;
9211 }
9212
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009213 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9214 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009215
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009216 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009217 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikied6471f72011-09-25 23:23:43 +00009218 != DiagnosticsEngine::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009219 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009220
Anders Carlssone21555e2008-11-30 19:50:32 +00009221 if (Result)
9222 *Result = EvalResult.Val.getInt();
9223 return false;
9224}
Douglas Gregore0762c92009-06-19 23:52:42 +00009225
Douglas Gregor2afce722009-11-26 00:44:06 +00009226void
Mike Stump1eb44332009-09-09 15:08:12 +00009227Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009228 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00009229 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +00009230 ExprCleanupObjects.size(),
John McCallf85e1932011-06-15 23:02:42 +00009231 ExprNeedsCleanups));
9232 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009233}
9234
Richard Trieu67e29332011-08-02 04:35:43 +00009235void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00009236 // Pop the current expression evaluation context off the stack.
9237 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9238 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009239
Douglas Gregor06d33692009-12-12 07:57:52 +00009240 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9241 if (Rec.PotentiallyReferenced) {
9242 // Mark any remaining declarations in the current position of the stack
9243 // as "referenced". If they were not meant to be referenced, semantic
9244 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009245 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009246 I = Rec.PotentiallyReferenced->begin(),
9247 IEnd = Rec.PotentiallyReferenced->end();
9248 I != IEnd; ++I)
9249 MarkDeclarationReferenced(I->first, I->second);
9250 }
9251
9252 if (Rec.PotentiallyDiagnosed) {
9253 // Emit any pending diagnostics.
9254 for (PotentiallyEmittedDiagnostics::iterator
9255 I = Rec.PotentiallyDiagnosed->begin(),
9256 IEnd = Rec.PotentiallyDiagnosed->end();
9257 I != IEnd; ++I)
9258 Diag(I->first, I->second);
9259 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009260 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009261
9262 // When are coming out of an unevaluated context, clear out any
9263 // temporaries that we may have created as part of the evaluation of
9264 // the expression in that context: they aren't relevant because they
9265 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009266 if (Rec.Context == Unevaluated) {
John McCall80ee6e82011-11-10 05:35:25 +00009267 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9268 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +00009269 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9270
9271 // Otherwise, merge the contexts together.
9272 } else {
9273 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9274 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009275
9276 // Destroy the popped expression evaluation record.
9277 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009278}
Douglas Gregore0762c92009-06-19 23:52:42 +00009279
John McCallf85e1932011-06-15 23:02:42 +00009280void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +00009281 ExprCleanupObjects.erase(
9282 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9283 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +00009284 ExprNeedsCleanups = false;
9285}
9286
Douglas Gregore0762c92009-06-19 23:52:42 +00009287/// \brief Note that the given declaration was referenced in the source code.
9288///
9289/// This routine should be invoke whenever a given declaration is referenced
9290/// in the source code, and where that reference occurred. If this declaration
9291/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9292/// C99 6.9p3), then the declaration will be marked as used.
9293///
9294/// \param Loc the location where the declaration was referenced.
9295///
9296/// \param D the declaration that has been referenced by the source code.
9297void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9298 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009299
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009300 D->setReferenced();
9301
Douglas Gregorc070cc62010-06-17 23:14:26 +00009302 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009303 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009304
Richard Trieu67e29332011-08-02 04:35:43 +00009305 // Mark a parameter or variable declaration "used", regardless of whether
9306 // we're in a template or not. The reason for this is that unevaluated
9307 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9308 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009309 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009310 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009311 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009312 return;
9313 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009314
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009315 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9316 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009317
Douglas Gregore0762c92009-06-19 23:52:42 +00009318 // Do not mark anything as "used" within a dependent context; wait for
9319 // an instantiation.
9320 if (CurContext->isDependentContext())
9321 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009322
Douglas Gregor2afce722009-11-26 00:44:06 +00009323 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009324 case Unevaluated:
9325 // We are in an expression that is not potentially evaluated; do nothing.
9326 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009327
Douglas Gregorac7610d2009-06-22 20:57:11 +00009328 case PotentiallyEvaluated:
9329 // We are in a potentially-evaluated expression, so this declaration is
9330 // "used"; handle this below.
9331 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009332
Douglas Gregorac7610d2009-06-22 20:57:11 +00009333 case PotentiallyPotentiallyEvaluated:
9334 // We are in an expression that may be potentially evaluated; queue this
9335 // declaration reference until we know whether the expression is
9336 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009337 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009338 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009339
9340 case PotentiallyEvaluatedIfUsed:
9341 // Referenced declarations will only be used if the construct in the
9342 // containing expression is used.
9343 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009344 }
Mike Stump1eb44332009-09-09 15:08:12 +00009345
Douglas Gregore0762c92009-06-19 23:52:42 +00009346 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009348 if (Constructor->isDefaulted()) {
9349 if (Constructor->isDefaultConstructor()) {
9350 if (Constructor->isTrivial())
9351 return;
9352 if (!Constructor->isUsed(false))
9353 DefineImplicitDefaultConstructor(Loc, Constructor);
9354 } else if (Constructor->isCopyConstructor()) {
9355 if (!Constructor->isUsed(false))
9356 DefineImplicitCopyConstructor(Loc, Constructor);
9357 } else if (Constructor->isMoveConstructor()) {
9358 if (!Constructor->isUsed(false))
9359 DefineImplicitMoveConstructor(Loc, Constructor);
9360 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009361 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009362
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009363 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009364 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009365 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009366 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009367 if (Destructor->isVirtual())
9368 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009369 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009370 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009371 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009372 if (!MethodDecl->isUsed(false)) {
9373 if (MethodDecl->isCopyAssignmentOperator())
9374 DefineImplicitCopyAssignment(Loc, MethodDecl);
9375 else
9376 DefineImplicitMoveAssignment(Loc, MethodDecl);
9377 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009378 } else if (MethodDecl->isVirtual())
9379 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009380 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009381 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009382 // Recursive functions should be marked when used from another function.
9383 if (CurContext == Function) return;
9384
Mike Stump1eb44332009-09-09 15:08:12 +00009385 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009386 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009387 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009388 bool AlreadyInstantiated = false;
9389 if (FunctionTemplateSpecializationInfo *SpecInfo
9390 = Function->getTemplateSpecializationInfo()) {
9391 if (SpecInfo->getPointOfInstantiation().isInvalid())
9392 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009393 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009394 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009395 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009396 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009397 = Function->getMemberSpecializationInfo()) {
9398 if (MSInfo->getPointOfInstantiation().isInvalid())
9399 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009400 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009401 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009402 AlreadyInstantiated = true;
9403 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009404
Douglas Gregor60406be2010-01-16 22:29:39 +00009405 if (!AlreadyInstantiated) {
9406 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9407 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9408 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9409 Loc));
9410 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009411 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009412 }
John McCall15e310a2011-02-19 02:53:41 +00009413 } else {
9414 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009415 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9416 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009417 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009418 MarkDeclarationReferenced(Loc, *i);
9419 }
John McCall15e310a2011-02-19 02:53:41 +00009420 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009421
John McCall15e310a2011-02-19 02:53:41 +00009422 // Keep track of used but undefined functions.
9423 if (!Function->isPure() && !Function->hasBody() &&
9424 Function->getLinkage() != ExternalLinkage) {
9425 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9426 if (old.isInvalid()) old = Loc;
9427 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009428
John McCall15e310a2011-02-19 02:53:41 +00009429 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009430 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009431 }
Mike Stump1eb44332009-09-09 15:08:12 +00009432
Douglas Gregore0762c92009-06-19 23:52:42 +00009433 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009434 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009435 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009436 Var->getInstantiatedFromStaticDataMember()) {
9437 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9438 assert(MSInfo && "Missing member specialization information?");
9439 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9440 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9441 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009442 // This is a modification of an existing AST node. Notify listeners.
9443 if (ASTMutationListener *L = getASTMutationListener())
9444 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009445 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009446 }
9447 }
Mike Stump1eb44332009-09-09 15:08:12 +00009448
John McCall77efc682011-02-21 19:25:48 +00009449 // Keep track of used but undefined variables. We make a hole in
9450 // the warning for static const data members with in-line
9451 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009452 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009453 && Var->getLinkage() != ExternalLinkage
9454 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009455 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9456 if (old.isInvalid()) old = Loc;
9457 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009458
Douglas Gregore0762c92009-06-19 23:52:42 +00009459 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009460 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009461 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009462}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009463
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009464namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009465 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009466 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009467 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009468 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9469 Sema &S;
9470 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009471
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009472 public:
9473 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009474
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009475 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009476
9477 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9478 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009479 };
9480}
9481
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009482bool MarkReferencedDecls::TraverseTemplateArgument(
9483 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009484 if (Arg.getKind() == TemplateArgument::Declaration) {
9485 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9486 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009487
9488 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009489}
9490
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009491bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009492 if (ClassTemplateSpecializationDecl *Spec
9493 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9494 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009495 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009496 }
9497
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009498 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009499}
9500
9501void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9502 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009503 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009504}
9505
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009506namespace {
9507 /// \brief Helper class that marks all of the declarations referenced by
9508 /// potentially-evaluated subexpressions as "referenced".
9509 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9510 Sema &S;
9511
9512 public:
9513 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9514
9515 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9516
9517 void VisitDeclRefExpr(DeclRefExpr *E) {
9518 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9519 }
9520
9521 void VisitMemberExpr(MemberExpr *E) {
9522 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009523 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009524 }
9525
John McCall80ee6e82011-11-10 05:35:25 +00009526 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9527 S.MarkDeclarationReferenced(E->getLocStart(),
9528 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
9529 Visit(E->getSubExpr());
9530 }
9531
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009532 void VisitCXXNewExpr(CXXNewExpr *E) {
9533 if (E->getConstructor())
9534 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9535 if (E->getOperatorNew())
9536 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9537 if (E->getOperatorDelete())
9538 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009539 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009540 }
9541
9542 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9543 if (E->getOperatorDelete())
9544 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009545 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9546 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9547 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9548 S.MarkDeclarationReferenced(E->getLocStart(),
9549 S.LookupDestructor(Record));
9550 }
9551
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009552 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009553 }
9554
9555 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9556 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009557 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009558 }
9559
9560 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9561 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9562 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009563
9564 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9565 Visit(E->getExpr());
9566 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009567 };
9568}
9569
9570/// \brief Mark any declarations that appear within this expression or any
9571/// potentially-evaluated subexpressions as "referenced".
9572void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9573 EvaluatedExprMarker(*this).Visit(E);
9574}
9575
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009576/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9577/// of the program being compiled.
9578///
9579/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009580/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009581/// possibility that the code will actually be executable. Code in sizeof()
9582/// expressions, code used only during overload resolution, etc., are not
9583/// potentially evaluated. This routine will suppress such diagnostics or,
9584/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009585/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009586/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009587///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009588/// This routine should be used for all diagnostics that describe the run-time
9589/// behavior of a program, such as passing a non-POD value through an ellipsis.
9590/// Failure to do so will likely result in spurious diagnostics or failures
9591/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +00009592bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009593 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009594 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009595 case Unevaluated:
9596 // The argument will never be evaluated, so don't complain.
9597 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009598
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009599 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009600 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +00009601 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00009602 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +00009603 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +00009604 }
9605 else
9606 Diag(Loc, PD);
9607
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009608 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009609
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009610 case PotentiallyPotentiallyEvaluated:
9611 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9612 break;
9613 }
9614
9615 return false;
9616}
9617
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009618bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9619 CallExpr *CE, FunctionDecl *FD) {
9620 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9621 return false;
9622
9623 PartialDiagnostic Note =
9624 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9625 << FD->getDeclName() : PDiag();
9626 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009627
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009628 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009629 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009630 PDiag(diag::err_call_function_incomplete_return)
9631 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009632 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009633 << CE->getSourceRange(),
9634 std::make_pair(NoteLoc, Note)))
9635 return true;
9636
9637 return false;
9638}
9639
Douglas Gregor92c3a042011-01-19 16:50:08 +00009640// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009641// will prevent this condition from triggering, which is what we want.
9642void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9643 SourceLocation Loc;
9644
John McCalla52ef082009-11-11 02:41:58 +00009645 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009646 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009647
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009648 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009649 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009650 return;
9651
Douglas Gregor92c3a042011-01-19 16:50:08 +00009652 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9653
John McCallc8d8ac52009-11-12 00:06:05 +00009654 // Greylist some idioms by putting them into a warning subcategory.
9655 if (ObjCMessageExpr *ME
9656 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9657 Selector Sel = ME->getSelector();
9658
John McCallc8d8ac52009-11-12 00:06:05 +00009659 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +00009660 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009661 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9662
9663 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009664 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009665 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9666 }
John McCalla52ef082009-11-11 02:41:58 +00009667
John McCall5a881bb2009-10-12 21:59:07 +00009668 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +00009669 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +00009670 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009671 return;
9672
Douglas Gregor92c3a042011-01-19 16:50:08 +00009673 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009674 Loc = Op->getOperatorLoc();
9675 } else {
9676 // Not an assignment.
9677 return;
9678 }
9679
Douglas Gregor55b38842010-04-14 16:09:52 +00009680 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009681
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009682 SourceLocation Open = E->getSourceRange().getBegin();
9683 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9684 Diag(Loc, diag::note_condition_assign_silence)
9685 << FixItHint::CreateInsertion(Open, "(")
9686 << FixItHint::CreateInsertion(Close, ")");
9687
Douglas Gregor92c3a042011-01-19 16:50:08 +00009688 if (IsOrAssign)
9689 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9690 << FixItHint::CreateReplacement(Loc, "!=");
9691 else
9692 Diag(Loc, diag::note_condition_assign_to_comparison)
9693 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009694}
9695
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009696/// \brief Redundant parentheses over an equality comparison can indicate
9697/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +00009698void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009699 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +00009700 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009701 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9702 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009703 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00009704 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009705 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009706
Richard Trieuccd891a2011-09-09 01:45:06 +00009707 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009708
9709 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009710 if (opE->getOpcode() == BO_EQ &&
9711 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9712 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009713 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009714
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009715 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009716 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuccd891a2011-09-09 01:45:06 +00009717 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9718 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009719 Diag(Loc, diag::note_equality_comparison_to_assign)
9720 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009721 }
9722}
9723
John Wiegley429bb272011-04-08 18:41:53 +00009724ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009725 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009726 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9727 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009728
John McCall864c0412011-04-26 20:42:42 +00009729 ExprResult result = CheckPlaceholderExpr(E);
9730 if (result.isInvalid()) return ExprError();
9731 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009732
John McCall864c0412011-04-26 20:42:42 +00009733 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009734 if (getLangOptions().CPlusPlus)
9735 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9736
John Wiegley429bb272011-04-08 18:41:53 +00009737 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9738 if (ERes.isInvalid())
9739 return ExprError();
9740 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009741
9742 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009743 if (!T->isScalarType()) { // C99 6.8.4.1p1
9744 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9745 << T << E->getSourceRange();
9746 return ExprError();
9747 }
John McCall5a881bb2009-10-12 21:59:07 +00009748 }
9749
John Wiegley429bb272011-04-08 18:41:53 +00009750 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009751}
Douglas Gregor586596f2010-05-06 17:25:47 +00009752
John McCall60d7b3a2010-08-24 06:29:42 +00009753ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009754 Expr *SubExpr) {
9755 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +00009756 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009757
Richard Trieuccd891a2011-09-09 01:45:06 +00009758 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009759}
John McCall2a984ca2010-10-12 00:20:44 +00009760
John McCall1de4d4e2011-04-07 08:22:57 +00009761namespace {
John McCall755d8492011-04-12 00:42:48 +00009762 /// A visitor for rebuilding a call to an __unknown_any expression
9763 /// to have an appropriate type.
9764 struct RebuildUnknownAnyFunction
9765 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9766
9767 Sema &S;
9768
9769 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9770
9771 ExprResult VisitStmt(Stmt *S) {
9772 llvm_unreachable("unexpected statement!");
9773 return ExprError();
9774 }
9775
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009776 ExprResult VisitExpr(Expr *E) {
9777 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9778 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009779 return ExprError();
9780 }
9781
9782 /// Rebuild an expression which simply semantically wraps another
9783 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009784 template <class T> ExprResult rebuildSugarExpr(T *E) {
9785 ExprResult SubResult = Visit(E->getSubExpr());
9786 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009787
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009788 Expr *SubExpr = SubResult.take();
9789 E->setSubExpr(SubExpr);
9790 E->setType(SubExpr->getType());
9791 E->setValueKind(SubExpr->getValueKind());
9792 assert(E->getObjectKind() == OK_Ordinary);
9793 return E;
John McCall755d8492011-04-12 00:42:48 +00009794 }
9795
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009796 ExprResult VisitParenExpr(ParenExpr *E) {
9797 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009798 }
9799
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009800 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9801 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009802 }
9803
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009804 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9805 ExprResult SubResult = Visit(E->getSubExpr());
9806 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +00009807
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009808 Expr *SubExpr = SubResult.take();
9809 E->setSubExpr(SubExpr);
9810 E->setType(S.Context.getPointerType(SubExpr->getType()));
9811 assert(E->getValueKind() == VK_RValue);
9812 assert(E->getObjectKind() == OK_Ordinary);
9813 return E;
John McCall755d8492011-04-12 00:42:48 +00009814 }
9815
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009816 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9817 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +00009818
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009819 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +00009820
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009821 assert(E->getValueKind() == VK_RValue);
John McCall755d8492011-04-12 00:42:48 +00009822 if (S.getLangOptions().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009823 !(isa<CXXMethodDecl>(VD) &&
9824 cast<CXXMethodDecl>(VD)->isInstance()))
9825 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +00009826
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009827 return E;
John McCall755d8492011-04-12 00:42:48 +00009828 }
9829
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009830 ExprResult VisitMemberExpr(MemberExpr *E) {
9831 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009832 }
9833
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009834 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9835 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +00009836 }
9837 };
9838}
9839
9840/// Given a function expression of unknown-any type, try to rebuild it
9841/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009842static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9843 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9844 if (Result.isInvalid()) return ExprError();
9845 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +00009846}
9847
9848namespace {
John McCall379b5152011-04-11 07:02:50 +00009849 /// A visitor for rebuilding an expression of type __unknown_anytype
9850 /// into one which resolves the type directly on the referring
9851 /// expression. Strict preservation of the original source
9852 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009853 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009854 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009855
9856 Sema &S;
9857
9858 /// The current destination type.
9859 QualType DestType;
9860
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009861 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9862 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +00009863
John McCalla5fc4722011-04-09 22:50:59 +00009864 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009865 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009866 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009867 }
9868
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009869 ExprResult VisitExpr(Expr *E) {
9870 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9871 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +00009872 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009873 }
9874
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009875 ExprResult VisitCallExpr(CallExpr *E);
9876 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +00009877
John McCalla5fc4722011-04-09 22:50:59 +00009878 /// Rebuild an expression which simply semantically wraps another
9879 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009880 template <class T> ExprResult rebuildSugarExpr(T *E) {
9881 ExprResult SubResult = Visit(E->getSubExpr());
9882 if (SubResult.isInvalid()) return ExprError();
9883 Expr *SubExpr = SubResult.take();
9884 E->setSubExpr(SubExpr);
9885 E->setType(SubExpr->getType());
9886 E->setValueKind(SubExpr->getValueKind());
9887 assert(E->getObjectKind() == OK_Ordinary);
9888 return E;
John McCalla5fc4722011-04-09 22:50:59 +00009889 }
John McCall1de4d4e2011-04-07 08:22:57 +00009890
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009891 ExprResult VisitParenExpr(ParenExpr *E) {
9892 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009893 }
9894
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009895 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9896 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +00009897 }
9898
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009899 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9900 const PointerType *Ptr = DestType->getAs<PointerType>();
9901 if (!Ptr) {
9902 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9903 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +00009904 return ExprError();
9905 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009906 assert(E->getValueKind() == VK_RValue);
9907 assert(E->getObjectKind() == OK_Ordinary);
9908 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +00009909
9910 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009911 DestType = Ptr->getPointeeType();
9912 ExprResult SubResult = Visit(E->getSubExpr());
9913 if (SubResult.isInvalid()) return ExprError();
9914 E->setSubExpr(SubResult.take());
9915 return E;
John McCall755d8492011-04-12 00:42:48 +00009916 }
9917
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009918 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +00009919
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009920 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +00009921
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009922 ExprResult VisitMemberExpr(MemberExpr *E) {
9923 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +00009924 }
John McCalla5fc4722011-04-09 22:50:59 +00009925
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009926 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9927 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009928 }
9929 };
9930}
9931
John McCall379b5152011-04-11 07:02:50 +00009932/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009933ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9934 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009935
9936 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009937 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009938 FK_FunctionPointer,
9939 FK_BlockPointer
9940 };
9941
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009942 FnKind Kind;
9943 QualType CalleeType = CalleeExpr->getType();
9944 if (CalleeType == S.Context.BoundMemberTy) {
9945 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9946 Kind = FK_MemberFunction;
9947 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9948 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9949 CalleeType = Ptr->getPointeeType();
9950 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +00009951 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009952 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9953 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +00009954 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009955 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +00009956
9957 // Verify that this is a legal result type of a function.
9958 if (DestType->isArrayType() || DestType->isFunctionType()) {
9959 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009960 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +00009961 diagID = diag::err_block_returning_array_function;
9962
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009963 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +00009964 << DestType->isFunctionType() << DestType;
9965 return ExprError();
9966 }
9967
9968 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009969 E->setType(DestType.getNonLValueExprType(S.Context));
9970 E->setValueKind(Expr::getValueKindForType(DestType));
9971 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +00009972
9973 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009974 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +00009975 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009976 Proto->arg_type_begin(),
9977 Proto->getNumArgs(),
9978 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +00009979 else
9980 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009981 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +00009982
9983 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009984 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +00009985 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009986 // Nothing to do.
9987 break;
9988
9989 case FK_FunctionPointer:
9990 DestType = S.Context.getPointerType(DestType);
9991 break;
9992
9993 case FK_BlockPointer:
9994 DestType = S.Context.getBlockPointerType(DestType);
9995 break;
9996 }
9997
9998 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +00009999 ExprResult CalleeResult = Visit(CalleeExpr);
10000 if (!CalleeResult.isUsable()) return ExprError();
10001 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000010002
10003 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010004 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010005}
10006
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010007ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010008 // Verify that this is a legal result type of a call.
10009 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010010 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000010011 << DestType->isFunctionType() << DestType;
10012 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010013 }
10014
John McCall48218c62011-07-13 17:56:40 +000010015 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010016 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10017 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10018 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000010019 }
John McCall755d8492011-04-12 00:42:48 +000010020
John McCall379b5152011-04-11 07:02:50 +000010021 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010022 E->setType(DestType.getNonReferenceType());
10023 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010024
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010025 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000010026}
10027
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010028ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000010029 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010030 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10031 assert(E->getValueKind() == VK_RValue);
10032 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000010033
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010034 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000010035
John McCall379b5152011-04-11 07:02:50 +000010036 // Rebuild the sub-expression as the pointee (function) type.
10037 DestType = DestType->castAs<PointerType>()->getPointeeType();
10038
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010039 ExprResult Result = Visit(E->getSubExpr());
10040 if (!Result.isUsable()) return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010041
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010042 E->setSubExpr(Result.take());
10043 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010044}
10045
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010046ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10047 ExprValueKind ValueKind = VK_LValue;
10048 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000010049
10050 // We know how to make this work for certain kinds of decls:
10051
10052 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10054 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10055 DestType = Ptr->getPointeeType();
10056 ExprResult Result = resolveDecl(E, VD);
10057 if (Result.isInvalid()) return ExprError();
10058 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000010059 CK_FunctionToPointerDecay, VK_RValue);
10060 }
10061
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010062 if (!Type->isFunctionType()) {
10063 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10064 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000010065 return ExprError();
10066 }
John McCall379b5152011-04-11 07:02:50 +000010067
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010068 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10069 if (MD->isInstance()) {
10070 ValueKind = VK_RValue;
10071 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000010072 }
10073
John McCall379b5152011-04-11 07:02:50 +000010074 // Function references aren't l-values in C.
10075 if (!S.getLangOptions().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010076 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000010077
10078 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010079 } else if (isa<VarDecl>(VD)) {
10080 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10081 Type = RefTy->getPointeeType();
10082 } else if (Type->isFunctionType()) {
10083 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10084 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000010085 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010086 }
10087
10088 // - nothing else
10089 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010090 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10091 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010092 return ExprError();
10093 }
10094
Richard Trieu5e4c80b2011-09-09 03:59:41 +000010095 VD->setType(DestType);
10096 E->setType(Type);
10097 E->setValueKind(ValueKind);
10098 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000010099}
10100
John McCall1de4d4e2011-04-07 08:22:57 +000010101/// Check a cast of an unknown-any type. We intentionally only
10102/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000010103ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10104 Expr *CastExpr, CastKind &CastKind,
10105 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010106 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000010107 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000010108 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010109
Richard Trieuccd891a2011-09-09 01:45:06 +000010110 CastExpr = result.take();
10111 VK = CastExpr->getValueKind();
10112 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000010113
Richard Trieuccd891a2011-09-09 01:45:06 +000010114 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010115}
10116
Richard Trieuccd891a2011-09-09 01:45:06 +000010117static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10118 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000010119 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010120 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000010121 E = E->IgnoreParenImpCasts();
10122 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10123 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010124 diagID = diag::err_uncasted_call_of_unknown_any;
10125 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010126 break;
John McCall379b5152011-04-11 07:02:50 +000010127 }
John McCall1de4d4e2011-04-07 08:22:57 +000010128 }
10129
John McCall379b5152011-04-11 07:02:50 +000010130 SourceLocation loc;
10131 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000010132 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010133 loc = ref->getLocation();
10134 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010135 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010136 loc = mem->getMemberLoc();
10137 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000010138 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000010139 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000010140 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000010141 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000010142 if (!d) {
10143 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10144 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10145 << orig->getSourceRange();
10146 return ExprError();
10147 }
John McCall379b5152011-04-11 07:02:50 +000010148 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000010149 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10150 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000010151 return ExprError();
10152 }
10153
10154 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010155
10156 // Never recoverable.
10157 return ExprError();
10158}
10159
John McCall2a984ca2010-10-12 00:20:44 +000010160/// Check for operands with placeholder types and complain if found.
10161/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010162ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000010163 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
10164 if (!placeholderType) return Owned(E);
10165
10166 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000010167
John McCall1de4d4e2011-04-07 08:22:57 +000010168 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000010169 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000010170 // Try to resolve a single function template specialization.
10171 // This is obligatory.
10172 ExprResult result = Owned(E);
10173 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10174 return result;
10175
10176 // If that failed, try to recover with a call.
10177 } else {
10178 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10179 /*complain*/ true);
10180 return result;
10181 }
10182 }
John McCall1de4d4e2011-04-07 08:22:57 +000010183
John McCall864c0412011-04-26 20:42:42 +000010184 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000010185 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000010186 ExprResult result = Owned(E);
10187 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10188 /*complain*/ true);
10189 return result;
John McCall5acb0c92011-10-17 18:40:02 +000010190 }
10191
10192 // ARC unbridged casts.
10193 case BuiltinType::ARCUnbridgedCast: {
10194 Expr *realCast = stripARCUnbridgedCast(E);
10195 diagnoseARCUnbridgedCast(realCast);
10196 return Owned(realCast);
10197 }
John McCall864c0412011-04-26 20:42:42 +000010198
John McCall1de4d4e2011-04-07 08:22:57 +000010199 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000010200 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000010201 return diagnoseUnknownAnyExpr(*this, E);
10202
John McCall3c3b7f92011-10-25 17:37:35 +000010203 // Pseudo-objects.
10204 case BuiltinType::PseudoObject:
10205 return checkPseudoObjectRValue(E);
10206
John McCalle0a22d02011-10-18 21:02:43 +000010207 // Everything else should be impossible.
10208#define BUILTIN_TYPE(Id, SingletonId) \
10209 case BuiltinType::Id:
10210#define PLACEHOLDER_TYPE(Id, SingletonId)
10211#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000010212 break;
10213 }
10214
10215 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000010216}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010217
Richard Trieuccd891a2011-09-09 01:45:06 +000010218bool Sema::CheckCaseExpression(Expr *E) {
10219 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000010220 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000010221 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10222 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000010223 return false;
10224}