blob: 97591be98eb2971a0a97c1733a05edc919f5d918 [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"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenekd6cf9122012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
90
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000091 switch (Result) {
92 case AR_Available:
93 case AR_NotYetIntroduced:
94 break;
95
96 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 break;
99
100 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 if (Message.empty()) {
103 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000104 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000105 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000106 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000107 << D->getDeclName();
108 }
109 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000110 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000111 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000112 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 << isa<FunctionDecl>(D) << false;
114 }
115 break;
116 }
117 return Result;
118}
119
Richard Smith6c4c36c2012-03-30 20:53:28 +0000120/// \brief Emit a note explaining that this function is deleted or unavailable.
121void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
122 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
123
Richard Smith5bdaac52012-04-02 20:59:25 +0000124 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Method->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000131 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000132 if (CSM != CXXInvalid)
133 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
134
135 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000136 }
137
138 Diag(Decl->getLocation(), diag::note_unavailable_here)
139 << 1 << Decl->isDeleted();
140}
141
Jordan Rose0eb3f452012-06-18 22:09:19 +0000142/// \brief Determine whether a FunctionDecl was ever declared with an
143/// explicit storage class.
144static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
145 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
146 E = D->redecls_end();
147 I != E; ++I) {
148 if (I->getStorageClassAsWritten() != SC_None)
149 return true;
150 }
151 return false;
152}
153
154/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000155/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000156///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000157/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000158/// in many cases it will not behave correctly. This is not enabled in C++ mode
159/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
160/// and so while there may still be user mistakes, most of the time we can't
161/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000162static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
163 const NamedDecl *D,
164 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000165 // This is disabled under C++; there are too many ways for this to fire in
166 // contexts where the warning is a false positive, or where it is technically
167 // correct but benign.
168 if (S.getLangOpts().CPlusPlus)
169 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000170
171 // Check if this is an inlined function or method.
172 FunctionDecl *Current = S.getCurFunctionDecl();
173 if (!Current)
174 return;
175 if (!Current->isInlined())
176 return;
177 if (Current->getLinkage() != ExternalLinkage)
178 return;
179
180 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000181 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000182 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000183
Jordan Rose05233272012-06-21 05:54:50 +0000184 // Downgrade from ExtWarn to Extension if
185 // (1) the supposedly external inline function is in the main file,
186 // and probably won't be included anywhere else.
187 // (2) the thing we're referencing is a pure function.
188 // (3) the thing we're referencing is another inline function.
189 // This last can give us false negatives, but it's better than warning on
190 // wrappers for simple C library functions.
191 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
192 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
193 if (!DowngradeWarning && UsedFn)
194 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
195
196 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
197 : diag::warn_internal_in_extern_inline)
198 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000199
200 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000201 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000202 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
203 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
204 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
205 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
206 }
207
208 S.Diag(D->getCanonicalDecl()->getLocation(),
209 diag::note_internal_decl_declared_here)
210 << D;
211}
212
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000213/// \brief Determine whether the use of this declaration is valid, and
214/// emit any corresponding diagnostics.
215///
216/// This routine diagnoses various problems with referencing
217/// declarations that can occur when using a declaration. For example,
218/// it might warn if a deprecated or unavailable declaration is being
219/// used, or produce an error (and return true) if a C++0x deleted
220/// function is being used.
221///
222/// \returns true if there was an error (this declaration cannot be
223/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000224///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000225bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000226 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000228 // If there were any diagnostics suppressed by template argument deduction,
229 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000230 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000231 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
232 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000233 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000234 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
235 Diag(Suppressed[I].first, Suppressed[I].second);
236
237 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000238 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000239 // entry from the table, because we want to avoid ever emitting these
240 // diagnostics again.
241 Suppressed.clear();
242 }
243 }
244
Richard Smith34b41d92011-02-20 03:19:35 +0000245 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000246 if (ParsingInitForAutoVars.count(D)) {
247 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
248 << D->getDeclName();
249 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000250 }
251
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000252 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000254 if (FD->isDeleted()) {
255 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000256 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000257 return true;
258 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000259 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000260 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000261
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000262 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000263
Jordan Rose0eb3f452012-06-18 22:09:19 +0000264 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000265
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000266 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000267}
268
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000269/// \brief Retrieve the message suffix that should be added to a
270/// diagnostic complaining about the given function being deleted or
271/// unavailable.
272std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
273 // FIXME: C++0x implicitly-deleted special member functions could be
274 // detected here so that we could improve diagnostics to say, e.g.,
275 // "base class 'A' had a deleted copy constructor".
276 if (FD->isDeleted())
277 return std::string();
278
279 std::string Message;
280 if (FD->getAvailability(&Message))
281 return ": " + Message;
282
283 return std::string();
284}
285
John McCall3323fad2011-09-09 07:56:05 +0000286/// DiagnoseSentinelCalls - This routine checks whether a call or
287/// message-send is to a declaration with the sentinel attribute, and
288/// if so, it checks that the requirements of the sentinel are
289/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000290void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000291 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000292 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000293 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000294 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000295
John McCall3323fad2011-09-09 07:56:05 +0000296 // The number of formal parameters of the declaration.
297 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000298
John McCall3323fad2011-09-09 07:56:05 +0000299 // The kind of declaration. This is also an index into a %select in
300 // the diagnostic.
301 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
302
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000303 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000304 numFormalParams = MD->param_size();
305 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000306 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000307 numFormalParams = FD->param_size();
308 calleeType = CT_Function;
309 } else if (isa<VarDecl>(D)) {
310 QualType type = cast<ValueDecl>(D)->getType();
311 const FunctionType *fn = 0;
312 if (const PointerType *ptr = type->getAs<PointerType>()) {
313 fn = ptr->getPointeeType()->getAs<FunctionType>();
314 if (!fn) return;
315 calleeType = CT_Function;
316 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
317 fn = ptr->getPointeeType()->castAs<FunctionType>();
318 calleeType = CT_Block;
319 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000320 return;
John McCall3323fad2011-09-09 07:56:05 +0000321 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000322
John McCall3323fad2011-09-09 07:56:05 +0000323 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
324 numFormalParams = proto->getNumArgs();
325 } else {
326 numFormalParams = 0;
327 }
328 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000329 return;
330 }
John McCall3323fad2011-09-09 07:56:05 +0000331
332 // "nullPos" is the number of formal parameters at the end which
333 // effectively count as part of the variadic arguments. This is
334 // useful if you would prefer to not have *any* formal parameters,
335 // but the language forces you to have at least one.
336 unsigned nullPos = attr->getNullPos();
337 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
338 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
339
340 // The number of arguments which should follow the sentinel.
341 unsigned numArgsAfterSentinel = attr->getSentinel();
342
343 // If there aren't enough arguments for all the formal parameters,
344 // the sentinel, and the args after the sentinel, complain.
345 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000346 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000347 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000348 return;
349 }
John McCall3323fad2011-09-09 07:56:05 +0000350
351 // Otherwise, find the sentinel expression.
352 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000353 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000354 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000355 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000356
John McCall3323fad2011-09-09 07:56:05 +0000357 // Pick a reasonable string to insert. Optimistically use 'nil' or
358 // 'NULL' if those are actually defined in the context. Only use
359 // 'nil' for ObjC methods, where it's much more likely that the
360 // variadic arguments form a list of object pointers.
361 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000362 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
363 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000364 if (calleeType == CT_Method &&
365 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000366 NullValue = "nil";
367 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
368 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000369 else
John McCall3323fad2011-09-09 07:56:05 +0000370 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000371
372 if (MissingNilLoc.isInvalid())
373 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
374 else
375 Diag(MissingNilLoc, diag::warn_missing_sentinel)
376 << calleeType
377 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000378 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000379}
380
Richard Trieuccd891a2011-09-09 01:45:06 +0000381SourceRange Sema::getExprRange(Expr *E) const {
382 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000383}
384
Chris Lattnere7a2e912008-07-25 21:10:04 +0000385//===----------------------------------------------------------------------===//
386// Standard Promotions and Conversions
387//===----------------------------------------------------------------------===//
388
Chris Lattnere7a2e912008-07-25 21:10:04 +0000389/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000390ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000391 // Handle any placeholder expressions which made it here.
392 if (E->getType()->isPlaceholderType()) {
393 ExprResult result = CheckPlaceholderExpr(E);
394 if (result.isInvalid()) return ExprError();
395 E = result.take();
396 }
397
Chris Lattnere7a2e912008-07-25 21:10:04 +0000398 QualType Ty = E->getType();
399 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
400
Chris Lattnere7a2e912008-07-25 21:10:04 +0000401 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000402 E = ImpCastExprToType(E, Context.getPointerType(Ty),
403 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000404 else if (Ty->isArrayType()) {
405 // In C90 mode, arrays only promote to pointers if the array expression is
406 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
407 // type 'array of type' is converted to an expression that has type 'pointer
408 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
409 // that has type 'array of type' ...". The relevant change is "an lvalue"
410 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000411 //
412 // C++ 4.2p1:
413 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
414 // T" can be converted to an rvalue of type "pointer to T".
415 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000416 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000417 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
418 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000419 }
John Wiegley429bb272011-04-08 18:41:53 +0000420 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000421}
422
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000423static void CheckForNullPointerDereference(Sema &S, Expr *E) {
424 // Check to see if we are dereferencing a null pointer. If so,
425 // and if not volatile-qualified, this is undefined behavior that the
426 // optimizer will delete, so warn about it. People sometimes try to use this
427 // to get a deterministic trap and are surprised by clang's behavior. This
428 // only handles the pattern "*null", which is a very syntactic check.
429 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
430 if (UO->getOpcode() == UO_Deref &&
431 UO->getSubExpr()->IgnoreParenCasts()->
432 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
433 !UO->getType().isVolatileQualified()) {
434 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
435 S.PDiag(diag::warn_indirection_through_null)
436 << UO->getSubExpr()->getSourceRange());
437 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
438 S.PDiag(diag::note_indirection_through_null));
439 }
440}
441
John Wiegley429bb272011-04-08 18:41:53 +0000442ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000443 // Handle any placeholder expressions which made it here.
444 if (E->getType()->isPlaceholderType()) {
445 ExprResult result = CheckPlaceholderExpr(E);
446 if (result.isInvalid()) return ExprError();
447 E = result.take();
448 }
449
John McCall0ae287a2010-12-01 04:43:34 +0000450 // C++ [conv.lval]p1:
451 // A glvalue of a non-function, non-array type T can be
452 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000453 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000454
John McCall409fa9a2010-12-06 20:48:59 +0000455 QualType T = E->getType();
456 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000457
John McCall409fa9a2010-12-06 20:48:59 +0000458 // We don't want to throw lvalue-to-rvalue casts on top of
459 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000460 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000461 (E->getType() == Context.OverloadTy ||
462 T->isDependentType() ||
463 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000464 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000465
466 // The C standard is actually really unclear on this point, and
467 // DR106 tells us what the result should be but not why. It's
468 // generally best to say that void types just doesn't undergo
469 // lvalue-to-rvalue at all. Note that expressions of unqualified
470 // 'void' type are never l-values, but qualified void can be.
471 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000472 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000473
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000474 CheckForNullPointerDereference(*this, E);
475
John McCall409fa9a2010-12-06 20:48:59 +0000476 // C++ [conv.lval]p1:
477 // [...] If T is a non-class type, the type of the prvalue is the
478 // cv-unqualified version of T. Otherwise, the type of the
479 // rvalue is T.
480 //
481 // C99 6.3.2.1p2:
482 // If the lvalue has qualified type, the value has the unqualified
483 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000484 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000485 if (T.hasQualifiers())
486 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000487
Eli Friedmand2cce132012-02-02 23:15:15 +0000488 UpdateMarkingForLValueToRValue(E);
489
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000490 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
491 E, 0, VK_RValue));
492
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000493 // C11 6.3.2.1p2:
494 // ... if the lvalue has atomic type, the value has the non-atomic version
495 // of the type of the lvalue ...
496 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
497 T = Atomic->getValueType().getUnqualifiedType();
498 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
499 Res.get(), 0, VK_RValue));
500 }
501
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000502 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000503}
504
John Wiegley429bb272011-04-08 18:41:53 +0000505ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
506 ExprResult Res = DefaultFunctionArrayConversion(E);
507 if (Res.isInvalid())
508 return ExprError();
509 Res = DefaultLvalueConversion(Res.take());
510 if (Res.isInvalid())
511 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000512 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000513}
514
515
Chris Lattnere7a2e912008-07-25 21:10:04 +0000516/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000517/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000518/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000519/// apply if the array is an argument to the sizeof or address (&) operators.
520/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000521ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000522 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000523 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
524 if (Res.isInvalid())
525 return Owned(E);
526 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000527
John McCall0ae287a2010-12-01 04:43:34 +0000528 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000529 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000530
531 // Half FP is a bit different: it's a storage-only type, meaning that any
532 // "use" of it should be promoted to float.
533 if (Ty->isHalfType())
534 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
535
John McCall0ae287a2010-12-01 04:43:34 +0000536 // Try to perform integral promotions if the object has a theoretically
537 // promotable type.
538 if (Ty->isIntegralOrUnscopedEnumerationType()) {
539 // C99 6.3.1.1p2:
540 //
541 // The following may be used in an expression wherever an int or
542 // unsigned int may be used:
543 // - an object or expression with an integer type whose integer
544 // conversion rank is less than or equal to the rank of int
545 // and unsigned int.
546 // - A bit-field of type _Bool, int, signed int, or unsigned int.
547 //
548 // If an int can represent all values of the original type, the
549 // value is converted to an int; otherwise, it is converted to an
550 // unsigned int. These are called the integer promotions. All
551 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000552
John McCall0ae287a2010-12-01 04:43:34 +0000553 QualType PTy = Context.isPromotableBitField(E);
554 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000555 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
556 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000557 }
558 if (Ty->isPromotableIntegerType()) {
559 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000560 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
561 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000562 }
Eli Friedman04e83572009-08-20 04:21:42 +0000563 }
John Wiegley429bb272011-04-08 18:41:53 +0000564 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000565}
566
Chris Lattner05faf172008-07-25 22:25:12 +0000567/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000568/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000569/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000570ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
571 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000572 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000573
John Wiegley429bb272011-04-08 18:41:53 +0000574 ExprResult Res = UsualUnaryConversions(E);
575 if (Res.isInvalid())
576 return Owned(E);
577 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000578
Chris Lattner05faf172008-07-25 22:25:12 +0000579 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000580 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000581 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
582
John McCall96a914a2011-08-27 22:06:17 +0000583 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000584 // promotion, even on class types, but note:
585 // C++11 [conv.lval]p2:
586 // When an lvalue-to-rvalue conversion occurs in an unevaluated
587 // operand or a subexpression thereof the value contained in the
588 // referenced object is not accessed. Otherwise, if the glvalue
589 // has a class type, the conversion copy-initializes a temporary
590 // of type T from the glvalue and the result of the conversion
591 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000592 // FIXME: add some way to gate this entire thing for correctness in
593 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000594 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000595 ExprResult Temp = PerformCopyInitialization(
596 InitializedEntity::InitializeTemporary(E->getType()),
597 E->getExprLoc(),
598 Owned(E));
599 if (Temp.isInvalid())
600 return ExprError();
601 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000602 }
603
John Wiegley429bb272011-04-08 18:41:53 +0000604 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000605}
606
Richard Smith831421f2012-06-25 20:30:08 +0000607/// Determine the degree of POD-ness for an expression.
608/// Incomplete types are considered POD, since this check can be performed
609/// when we're in an unevaluated context.
610Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000611 if (Ty->isIncompleteType()) {
612 if (Ty->isObjCObjectType())
613 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000614 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000615 }
616
617 if (Ty.isCXX98PODType(Context))
618 return VAK_Valid;
619
Richard Smith831421f2012-06-25 20:30:08 +0000620 // C++0x [expr.call]p7:
621 // Passing a potentially-evaluated argument of class type (Clause 9)
622 // having a non-trivial copy constructor, a non-trivial move constructor,
623 // or a non-trivial destructor, with no corresponding parameter,
624 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000625 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
626 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
627 if (Record->hasTrivialCopyConstructor() &&
628 Record->hasTrivialMoveConstructor() &&
629 Record->hasTrivialDestructor())
630 return VAK_ValidInCXX11;
631
632 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
633 return VAK_Valid;
634 return VAK_Invalid;
635}
636
637bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
638 // Don't allow one to pass an Objective-C interface to a vararg.
639 const QualType & Ty = E->getType();
640
641 // Complain about passing non-POD types through varargs.
642 switch (isValidVarArgType(Ty)) {
643 case VAK_Valid:
644 break;
645 case VAK_ValidInCXX11:
646 DiagRuntimeBehavior(E->getLocStart(), 0,
647 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
648 << E->getType() << CT);
649 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000650 case VAK_Invalid: {
651 if (Ty->isObjCObjectType())
652 return DiagRuntimeBehavior(E->getLocStart(), 0,
653 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
654 << Ty << CT);
655
Richard Smith831421f2012-06-25 20:30:08 +0000656 return DiagRuntimeBehavior(E->getLocStart(), 0,
657 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
658 << getLangOpts().CPlusPlus0x << Ty << CT);
659 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000660 }
Richard Smith831421f2012-06-25 20:30:08 +0000661 // c++ rules are enforced elsewhere.
662 return false;
663}
664
Chris Lattner312531a2009-04-12 08:11:20 +0000665/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000666/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000667ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000668 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000669 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000670 // Strip the unbridged-cast placeholder expression off, if applicable.
671 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
672 (CT == VariadicMethod ||
673 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
674 E = stripARCUnbridgedCast(E);
675
676 // Otherwise, do normal placeholder checking.
677 } else {
678 ExprResult ExprRes = CheckPlaceholderExpr(E);
679 if (ExprRes.isInvalid())
680 return ExprError();
681 E = ExprRes.take();
682 }
683 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000684
John McCall5acb0c92011-10-17 18:40:02 +0000685 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000686 if (ExprRes.isInvalid())
687 return ExprError();
688 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Richard Smith831421f2012-06-25 20:30:08 +0000690 // Diagnostics regarding non-POD argument types are
691 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000692 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000693 // Turn this into a trap.
694 CXXScopeSpec SS;
695 SourceLocation TemplateKWLoc;
696 UnqualifiedId Name;
697 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
698 E->getLocStart());
699 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
700 Name, true, false);
701 if (TrapFn.isInvalid())
702 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000703
Richard Smith831421f2012-06-25 20:30:08 +0000704 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
705 E->getLocStart(), MultiExprArg(),
706 E->getLocEnd());
707 if (Call.isInvalid())
708 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000709
Richard Smith831421f2012-06-25 20:30:08 +0000710 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
711 Call.get(), E);
712 if (Comma.isInvalid())
713 return ExprError();
714 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000715 }
Richard Smith831421f2012-06-25 20:30:08 +0000716
David Blaikie4e4d0842012-03-11 07:00:24 +0000717 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000718 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000719 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000720 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000721
John Wiegley429bb272011-04-08 18:41:53 +0000722 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000723}
724
Richard Trieu8289f492011-09-02 20:58:51 +0000725/// \brief Converts an integer to complex float type. Helper function of
726/// UsualArithmeticConversions()
727///
728/// \return false if the integer expression is an integer type and is
729/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000730static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
731 ExprResult &ComplexExpr,
732 QualType IntTy,
733 QualType ComplexTy,
734 bool SkipCast) {
735 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
736 if (SkipCast) return false;
737 if (IntTy->isIntegerType()) {
738 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
739 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
740 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000741 CK_FloatingRealToComplex);
742 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000743 assert(IntTy->isComplexIntegerType());
744 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000745 CK_IntegralComplexToFloatingComplex);
746 }
747 return false;
748}
749
750/// \brief Takes two complex float types and converts them to the same type.
751/// Helper function of UsualArithmeticConversions()
752static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000753handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
754 ExprResult &RHS, QualType LHSType,
755 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000756 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000757 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000758
759 if (order < 0) {
760 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000761 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000762 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
763 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000764 }
765 if (order > 0)
766 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000767 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
768 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000769}
770
771/// \brief Converts otherExpr to complex float and promotes complexExpr if
772/// necessary. Helper function of UsualArithmeticConversions()
773static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000774 ExprResult &ComplexExpr,
775 ExprResult &OtherExpr,
776 QualType ComplexTy,
777 QualType OtherTy,
778 bool ConvertComplexExpr,
779 bool ConvertOtherExpr) {
780 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000781
782 // If just the complexExpr is complex, the otherExpr needs to be converted,
783 // and the complexExpr might need to be promoted.
784 if (order > 0) { // complexExpr is wider
785 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000786 if (ConvertOtherExpr) {
787 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
788 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
789 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000790 CK_FloatingRealToComplex);
791 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000793 }
794
795 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000796 QualType result = (order == 0 ? ComplexTy :
797 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000798
799 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000800 if (ConvertOtherExpr)
801 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000802 CK_FloatingRealToComplex);
803
804 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000805 if (ConvertComplexExpr && order < 0)
806 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000807 CK_FloatingComplexCast);
808
809 return result;
810}
811
812/// \brief Handle arithmetic conversion with complex types. Helper function of
813/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000814static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
815 ExprResult &RHS, QualType LHSType,
816 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000817 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000818 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000819 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000820 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000821 return LHSType;
822 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000823 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000824 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000825
826 // This handles complex/complex, complex/float, or float/complex.
827 // When both operands are complex, the shorter operand is converted to the
828 // type of the longer, and that is the type of the result. This corresponds
829 // to what is done when combining two real floating-point operands.
830 // The fun begins when size promotion occur across type domains.
831 // From H&S 6.3.4: When one operand is complex and the other is a real
832 // floating-point type, the less precise type is converted, within it's
833 // real or complex domain, to the precision of the other type. For example,
834 // when combining a "long double" with a "double _Complex", the
835 // "double _Complex" is promoted to "long double _Complex".
836
Richard Trieucafd30b2011-09-06 18:25:09 +0000837 bool LHSComplexFloat = LHSType->isComplexType();
838 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000839
840 // If both are complex, just cast to the more precise type.
841 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000842 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
843 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000844 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000845
846 // If only one operand is complex, promote it if necessary and convert the
847 // other operand to complex.
848 if (LHSComplexFloat)
849 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000850 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000851 /*convertOtherExpr*/ true);
852
853 assert(RHSComplexFloat);
854 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000855 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000856 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000857}
858
859/// \brief Hande arithmetic conversion from integer to float. Helper function
860/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000861static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
862 ExprResult &IntExpr,
863 QualType FloatTy, QualType IntTy,
864 bool ConvertFloat, bool ConvertInt) {
865 if (IntTy->isIntegerType()) {
866 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000867 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000868 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000869 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000870 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000871 }
872
873 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000874 assert(IntTy->isComplexIntegerType());
875 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000876
877 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000878 if (ConvertInt)
879 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000880 CK_IntegralComplexToFloatingComplex);
881
882 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000883 if (ConvertFloat)
884 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000885 CK_FloatingRealToComplex);
886
887 return result;
888}
889
890/// \brief Handle arithmethic conversion with floating point types. Helper
891/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000892static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
893 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000894 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000895 bool LHSFloat = LHSType->isRealFloatingType();
896 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000897
898 // If we have two real floating types, convert the smaller operand
899 // to the bigger result.
900 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000901 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000902 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000903 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
904 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000905 }
906
907 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000909 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
910 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000911 }
912
913 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000914 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000915 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000916 /*convertInt=*/ true);
917 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000918 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000919 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000920 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000921}
922
923/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000924/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000925// FIXME: if the operands are (int, _Complex long), we currently
926// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000927static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
928 ExprResult &RHS, QualType LHSType,
929 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000930 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000931 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
932 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000933
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000934 if (LHSComplexInt && RHSComplexInt) {
935 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
936 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000937 assert(order && "inequal types with equal element ordering");
938 if (order > 0) {
939 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000940 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
941 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000942 }
943
Richard Trieuccd891a2011-09-09 01:45:06 +0000944 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000945 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
946 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000947 }
948
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000949 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000950 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000951 // FIXME: This needs to take integer ranks into account
952 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
953 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000954 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
955 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000956 }
957
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000958 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000959 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000960 // FIXME: This needs to take integer ranks into account
961 if (!IsCompAssign) {
962 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
963 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000964 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000965 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000966 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000967}
968
969/// \brief Handle integer arithmetic conversions. Helper function of
970/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000971static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
972 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000973 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000974 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000975 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
976 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
977 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
978 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000979 // Same signedness; use the higher-ranked type
980 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000981 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
982 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000983 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000984 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
985 return RHSType;
986 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000987 // The unsigned type has greater than or equal rank to the
988 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989 if (RHSSigned) {
990 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
991 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000992 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000993 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
994 return RHSType;
995 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000996 // The two types are different widths; if we are here, that
997 // means the signed type is larger than the unsigned type, so
998 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 if (LHSSigned) {
1000 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1001 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001002 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001003 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1004 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001005 } else {
1006 // The signed type is higher-ranked than the unsigned type,
1007 // but isn't actually any bigger (like unsigned int and long
1008 // on most 32-bit systems). Use the unsigned type corresponding
1009 // to the signed type.
1010 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001011 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1012 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001013 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001014 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001015 return result;
1016 }
1017}
1018
Chris Lattnere7a2e912008-07-25 21:10:04 +00001019/// UsualArithmeticConversions - Performs various conversions that are common to
1020/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001021/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001022/// responsible for emitting appropriate error diagnostics.
1023/// FIXME: verify the conversion rules for "complex int" are consistent with
1024/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001025QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001026 bool IsCompAssign) {
1027 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001028 LHS = UsualUnaryConversions(LHS.take());
1029 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001030 return QualType();
1031 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001032
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001033 RHS = UsualUnaryConversions(RHS.take());
1034 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001035 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001036
Mike Stump1eb44332009-09-09 15:08:12 +00001037 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001038 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001039 QualType LHSType =
1040 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1041 QualType RHSType =
1042 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001043
Eli Friedman860a3192012-06-16 02:19:17 +00001044 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1045 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1046 LHSType = AtomicLHS->getValueType();
1047
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001048 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001049 if (LHSType == RHSType)
1050 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001051
1052 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1053 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001054 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001055 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001056
John McCallcf33b242010-11-13 08:17:45 +00001057 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001058 QualType LHSUnpromotedType = LHSType;
1059 if (LHSType->isPromotableIntegerType())
1060 LHSType = Context.getPromotedIntegerType(LHSType);
1061 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001062 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001063 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001064 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001065 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001066
John McCallcf33b242010-11-13 08:17:45 +00001067 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001068 if (LHSType == RHSType)
1069 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001070
1071 // At this point, we have two different arithmetic types.
1072
1073 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001074 if (LHSType->isComplexType() || RHSType->isComplexType())
1075 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001076 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001077
1078 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001079 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1080 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001081 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001082
1083 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001084 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001085 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001086 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001087
1088 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001089 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001090 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001091}
1092
Chris Lattnere7a2e912008-07-25 21:10:04 +00001093//===----------------------------------------------------------------------===//
1094// Semantic Analysis for various Expression Types
1095//===----------------------------------------------------------------------===//
1096
1097
Peter Collingbournef111d932011-04-15 00:35:48 +00001098ExprResult
1099Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1100 SourceLocation DefaultLoc,
1101 SourceLocation RParenLoc,
1102 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001103 MultiTypeArg ArgTypes,
1104 MultiExprArg ArgExprs) {
1105 unsigned NumAssocs = ArgTypes.size();
1106 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001107
Benjamin Kramer5354e772012-08-23 23:38:35 +00001108 ParsedType *ParsedTypes = ArgTypes.data();
1109 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001110
1111 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1112 for (unsigned i = 0; i < NumAssocs; ++i) {
1113 if (ParsedTypes[i])
1114 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1115 else
1116 Types[i] = 0;
1117 }
1118
1119 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1120 ControllingExpr, Types, Exprs,
1121 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001122 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001123 return ER;
1124}
1125
1126ExprResult
1127Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1128 SourceLocation DefaultLoc,
1129 SourceLocation RParenLoc,
1130 Expr *ControllingExpr,
1131 TypeSourceInfo **Types,
1132 Expr **Exprs,
1133 unsigned NumAssocs) {
1134 bool TypeErrorFound = false,
1135 IsResultDependent = ControllingExpr->isTypeDependent(),
1136 ContainsUnexpandedParameterPack
1137 = ControllingExpr->containsUnexpandedParameterPack();
1138
1139 for (unsigned i = 0; i < NumAssocs; ++i) {
1140 if (Exprs[i]->containsUnexpandedParameterPack())
1141 ContainsUnexpandedParameterPack = true;
1142
1143 if (Types[i]) {
1144 if (Types[i]->getType()->containsUnexpandedParameterPack())
1145 ContainsUnexpandedParameterPack = true;
1146
1147 if (Types[i]->getType()->isDependentType()) {
1148 IsResultDependent = true;
1149 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001150 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001151 // complete object type other than a variably modified type."
1152 unsigned D = 0;
1153 if (Types[i]->getType()->isIncompleteType())
1154 D = diag::err_assoc_type_incomplete;
1155 else if (!Types[i]->getType()->isObjectType())
1156 D = diag::err_assoc_type_nonobject;
1157 else if (Types[i]->getType()->isVariablyModifiedType())
1158 D = diag::err_assoc_type_variably_modified;
1159
1160 if (D != 0) {
1161 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1162 << Types[i]->getTypeLoc().getSourceRange()
1163 << Types[i]->getType();
1164 TypeErrorFound = true;
1165 }
1166
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001167 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001168 // selection shall specify compatible types."
1169 for (unsigned j = i+1; j < NumAssocs; ++j)
1170 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1171 Context.typesAreCompatible(Types[i]->getType(),
1172 Types[j]->getType())) {
1173 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1174 diag::err_assoc_compatible_types)
1175 << Types[j]->getTypeLoc().getSourceRange()
1176 << Types[j]->getType()
1177 << Types[i]->getType();
1178 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1179 diag::note_compat_assoc)
1180 << Types[i]->getTypeLoc().getSourceRange()
1181 << Types[i]->getType();
1182 TypeErrorFound = true;
1183 }
1184 }
1185 }
1186 }
1187 if (TypeErrorFound)
1188 return ExprError();
1189
1190 // If we determined that the generic selection is result-dependent, don't
1191 // try to compute the result expression.
1192 if (IsResultDependent)
1193 return Owned(new (Context) GenericSelectionExpr(
1194 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001195 llvm::makeArrayRef(Types, NumAssocs),
1196 llvm::makeArrayRef(Exprs, NumAssocs),
1197 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001198
Chris Lattner5f9e2722011-07-23 10:55:15 +00001199 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001200 unsigned DefaultIndex = -1U;
1201 for (unsigned i = 0; i < NumAssocs; ++i) {
1202 if (!Types[i])
1203 DefaultIndex = i;
1204 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1205 Types[i]->getType()))
1206 CompatIndices.push_back(i);
1207 }
1208
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001209 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001210 // type compatible with at most one of the types named in its generic
1211 // association list."
1212 if (CompatIndices.size() > 1) {
1213 // We strip parens here because the controlling expression is typically
1214 // parenthesized in macro definitions.
1215 ControllingExpr = ControllingExpr->IgnoreParens();
1216 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1217 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1218 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001219 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001220 E = CompatIndices.end(); I != E; ++I) {
1221 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1222 diag::note_compat_assoc)
1223 << Types[*I]->getTypeLoc().getSourceRange()
1224 << Types[*I]->getType();
1225 }
1226 return ExprError();
1227 }
1228
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001229 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001230 // its controlling expression shall have type compatible with exactly one of
1231 // the types named in its generic association list."
1232 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1233 // We strip parens here because the controlling expression is typically
1234 // parenthesized in macro definitions.
1235 ControllingExpr = ControllingExpr->IgnoreParens();
1236 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1237 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1238 return ExprError();
1239 }
1240
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001241 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001242 // type name that is compatible with the type of the controlling expression,
1243 // then the result expression of the generic selection is the expression
1244 // in that generic association. Otherwise, the result expression of the
1245 // generic selection is the expression in the default generic association."
1246 unsigned ResultIndex =
1247 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1248
1249 return Owned(new (Context) GenericSelectionExpr(
1250 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001251 llvm::makeArrayRef(Types, NumAssocs),
1252 llvm::makeArrayRef(Exprs, NumAssocs),
1253 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001254 ResultIndex));
1255}
1256
Richard Smithdd66be72012-03-08 01:34:56 +00001257/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1258/// location of the token and the offset of the ud-suffix within it.
1259static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1260 unsigned Offset) {
1261 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001262 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001263}
1264
Richard Smith36f5cfe2012-03-09 08:00:36 +00001265/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1266/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1267static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1268 IdentifierInfo *UDSuffix,
1269 SourceLocation UDSuffixLoc,
1270 ArrayRef<Expr*> Args,
1271 SourceLocation LitEndLoc) {
1272 assert(Args.size() <= 2 && "too many arguments for literal operator");
1273
1274 QualType ArgTy[2];
1275 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1276 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1277 if (ArgTy[ArgIdx]->isArrayType())
1278 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1279 }
1280
1281 DeclarationName OpName =
1282 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1283 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1284 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1285
1286 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1287 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1288 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1289 return ExprError();
1290
1291 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1292}
1293
Steve Narofff69936d2007-09-16 03:34:24 +00001294/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001295/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1296/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1297/// multiple tokens. However, the common case is that StringToks points to one
1298/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001299///
John McCall60d7b3a2010-08-24 06:29:42 +00001300ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001301Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1302 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 assert(NumStringToks && "Must have at least one string!");
1304
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001305 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001307 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001308
Chris Lattner5f9e2722011-07-23 10:55:15 +00001309 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 for (unsigned i = 0; i != NumStringToks; ++i)
1311 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001312
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001313 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001314 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001315 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001316 else if (Literal.isUTF16())
1317 StrTy = Context.Char16Ty;
1318 else if (Literal.isUTF32())
1319 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001320 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001321 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001322
Douglas Gregor5cee1192011-07-27 05:40:30 +00001323 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1324 if (Literal.isWide())
1325 Kind = StringLiteral::Wide;
1326 else if (Literal.isUTF8())
1327 Kind = StringLiteral::UTF8;
1328 else if (Literal.isUTF16())
1329 Kind = StringLiteral::UTF16;
1330 else if (Literal.isUTF32())
1331 Kind = StringLiteral::UTF32;
1332
Douglas Gregor77a52232008-09-12 00:47:35 +00001333 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001334 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001335 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001336
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001337 // Get an array type for the string, according to C99 6.4.5. This includes
1338 // the nul terminator character as well as the string length for pascal
1339 // strings.
1340 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001341 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001342 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001345 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1346 Kind, Literal.Pascal, StrTy,
1347 &StringTokLocs[0],
1348 StringTokLocs.size());
1349 if (Literal.getUDSuffix().empty())
1350 return Owned(Lit);
1351
1352 // We're building a user-defined literal.
1353 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001354 SourceLocation UDSuffixLoc =
1355 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1356 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001357
Richard Smith36f5cfe2012-03-09 08:00:36 +00001358 // Make sure we're allowed user-defined literals here.
1359 if (!UDLScope)
1360 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1361
Richard Smith9fcce652012-03-07 08:35:16 +00001362 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1363 // operator "" X (str, len)
1364 QualType SizeType = Context.getSizeType();
1365 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1366 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1367 StringTokLocs[0]);
1368 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001369 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1370 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001371}
1372
John McCall60d7b3a2010-08-24 06:29:42 +00001373ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001374Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001375 SourceLocation Loc,
1376 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001377 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001378 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001379}
1380
John McCall76a40212011-02-09 01:13:10 +00001381/// BuildDeclRefExpr - Build an expression that references a
1382/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001383ExprResult
John McCall76a40212011-02-09 01:13:10 +00001384Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001385 const DeclarationNameInfo &NameInfo,
1386 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001387 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001388 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1389 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1390 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1391 CalleeTarget = IdentifyCUDATarget(Callee);
1392 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1393 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1394 << CalleeTarget << D->getIdentifier() << CallerTarget;
1395 Diag(D->getLocation(), diag::note_previous_decl)
1396 << D->getIdentifier();
1397 return ExprError();
1398 }
1399 }
1400
John McCallf4b88a42012-03-10 09:33:50 +00001401 bool refersToEnclosingScope =
1402 (CurContext != D->getDeclContext() &&
1403 D->getDeclContext()->isFunctionOrMethod());
1404
Eli Friedman5f2987c2012-02-02 03:46:19 +00001405 DeclRefExpr *E = DeclRefExpr::Create(Context,
1406 SS ? SS->getWithLocInContext(Context)
1407 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001408 SourceLocation(),
1409 D, refersToEnclosingScope,
1410 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Eli Friedman5f2987c2012-02-02 03:46:19 +00001412 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001413
1414 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001415 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1416 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001417 E->setObjectKind(OK_BitField);
1418
1419 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001420}
1421
Abramo Bagnara25777432010-08-11 22:01:17 +00001422/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001423/// possibly a list of template arguments.
1424///
1425/// If this produces template arguments, it is permitted to call
1426/// DecomposeTemplateName.
1427///
1428/// This actually loses a lot of source location information for
1429/// non-standard name kinds; we should consider preserving that in
1430/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001431void
1432Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1433 TemplateArgumentListInfo &Buffer,
1434 DeclarationNameInfo &NameInfo,
1435 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001436 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1437 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1438 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1439
Benjamin Kramer5354e772012-08-23 23:38:35 +00001440 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001441 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001442 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001443
John McCall2b5289b2010-08-23 07:28:44 +00001444 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001445 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001446 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001447 TemplateArgs = &Buffer;
1448 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001449 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001450 TemplateArgs = 0;
1451 }
1452}
1453
John McCall578b69b2009-12-16 08:11:27 +00001454/// Diagnose an empty lookup.
1455///
1456/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001457bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001458 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001459 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001460 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001461 DeclarationName Name = R.getLookupName();
1462
John McCall578b69b2009-12-16 08:11:27 +00001463 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001464 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001465 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1466 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001467 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001468 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001469 diagnostic_suggest = diag::err_undeclared_use_suggest;
1470 }
John McCall578b69b2009-12-16 08:11:27 +00001471
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001472 // If the original lookup was an unqualified lookup, fake an
1473 // unqualified lookup. This is useful when (for example) the
1474 // original lookup would not have found something because it was a
1475 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001476 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1477 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001478 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001479 if (isa<CXXRecordDecl>(DC)) {
1480 LookupQualifiedName(R, DC);
1481
1482 if (!R.empty()) {
1483 // Don't give errors about ambiguities in this lookup.
1484 R.suppressDiagnostics();
1485
Francois Pichete6226ae2011-11-17 03:44:24 +00001486 // During a default argument instantiation the CurContext points
1487 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1488 // function parameter list, hence add an explicit check.
1489 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1490 ActiveTemplateInstantiations.back().Kind ==
1491 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001492 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1493 bool isInstance = CurMethod &&
1494 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001495 DC == CurMethod->getParent() && !isDefaultArgument;
1496
John McCall578b69b2009-12-16 08:11:27 +00001497
1498 // Give a code modification hint to insert 'this->'.
1499 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1500 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001501 if (getLangOpts().MicrosoftMode)
1502 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001503 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001504 Diag(R.getNameLoc(), diagnostic) << Name
1505 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001506 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1507 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001508
1509
1510 CXXMethodDecl *DepMethod;
1511 if (CurMethod->getTemplatedKind() ==
1512 FunctionDecl::TK_FunctionTemplateSpecialization)
1513 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1514 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1515 else
1516 DepMethod = cast<CXXMethodDecl>(
1517 CurMethod->getInstantiatedFromMemberFunction());
1518 assert(DepMethod && "No template pattern found");
1519
1520 QualType DepThisType = DepMethod->getThisType(Context);
1521 CheckCXXThisCapture(R.getNameLoc());
1522 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1523 R.getNameLoc(), DepThisType, false);
1524 TemplateArgumentListInfo TList;
1525 if (ULE->hasExplicitTemplateArgs())
1526 ULE->copyTemplateArgumentsInto(TList);
1527
1528 CXXScopeSpec SS;
1529 SS.Adopt(ULE->getQualifierLoc());
1530 CXXDependentScopeMemberExpr *DepExpr =
1531 CXXDependentScopeMemberExpr::Create(
1532 Context, DepThis, DepThisType, true, SourceLocation(),
1533 SS.getWithLocInContext(Context),
1534 ULE->getTemplateKeywordLoc(), 0,
1535 R.getLookupNameInfo(),
1536 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1537 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001538 } else {
John McCall578b69b2009-12-16 08:11:27 +00001539 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001540 }
John McCall578b69b2009-12-16 08:11:27 +00001541
1542 // Do we really want to note all of these?
1543 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1544 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1545
Francois Pichete6226ae2011-11-17 03:44:24 +00001546 // Return true if we are inside a default argument instantiation
1547 // and the found name refers to an instance member function, otherwise
1548 // the function calling DiagnoseEmptyLookup will try to create an
1549 // implicit member call and this is wrong for default argument.
1550 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1551 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1552 return true;
1553 }
1554
John McCall578b69b2009-12-16 08:11:27 +00001555 // Tell the callee to try to recover.
1556 return false;
1557 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001558
1559 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001560 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001561
1562 // In Microsoft mode, if we are performing lookup from within a friend
1563 // function definition declared at class scope then we must set
1564 // DC to the lexical parent to be able to search into the parent
1565 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001566 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001567 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1568 DC->getLexicalParent()->isRecord())
1569 DC = DC->getLexicalParent();
1570 else
1571 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001572 }
1573
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001574 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001575 TypoCorrection Corrected;
1576 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001577 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001578 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1579 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001580 R.setLookupName(Corrected.getCorrection());
1581
Hans Wennborg701d1e72011-07-12 08:45:31 +00001582 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001583 if (Corrected.isOverloaded()) {
1584 OverloadCandidateSet OCS(R.getNameLoc());
1585 OverloadCandidateSet::iterator Best;
1586 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1587 CDEnd = Corrected.end();
1588 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001589 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001590 dyn_cast<FunctionTemplateDecl>(*CD))
1591 AddTemplateOverloadCandidate(
1592 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001593 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001594 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1595 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1596 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001597 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001598 }
1599 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1600 case OR_Success:
1601 ND = Best->Function;
1602 break;
1603 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001604 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001605 }
1606 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 R.addDecl(ND);
1608 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001609 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001610 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1611 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001612 else
1613 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001614 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001615 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001616 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1617 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001618 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001619 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001620
1621 // Tell the callee to try to recover.
1622 return false;
1623 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001624
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001625 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001626 // FIXME: If we ended up with a typo for a type name or
1627 // Objective-C class name, we're in trouble because the parser
1628 // is in the wrong place to recover. Suggest the typo
1629 // correction, but don't make it a fix-it since we're not going
1630 // to recover well anyway.
1631 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001632 Diag(R.getNameLoc(), diagnostic_suggest)
1633 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001634 else
1635 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001636 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001637 << SS.getRange();
1638
1639 // Don't try to recover; it won't work.
1640 return true;
1641 }
1642 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001643 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001644 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001645 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001646 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001647 else
Douglas Gregord203a162010-01-01 00:15:04 +00001648 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001649 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001650 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001651 return true;
1652 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001653 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001654 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001655
1656 // Emit a special diagnostic for failed member lookups.
1657 // FIXME: computing the declaration context might fail here (?)
1658 if (!SS.isEmpty()) {
1659 Diag(R.getNameLoc(), diag::err_no_member)
1660 << Name << computeDeclContext(SS, false)
1661 << SS.getRange();
1662 return true;
1663 }
1664
John McCall578b69b2009-12-16 08:11:27 +00001665 // Give up, we can't recover.
1666 Diag(R.getNameLoc(), diagnostic) << Name;
1667 return true;
1668}
1669
John McCall60d7b3a2010-08-24 06:29:42 +00001670ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001671 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001672 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001673 UnqualifiedId &Id,
1674 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001675 bool IsAddressOfOperand,
1676 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001677 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001678 "cannot be direct & operand and have a trailing lparen");
1679
1680 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001681 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001682
John McCall129e2df2009-11-30 22:42:35 +00001683 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001684
1685 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001686 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001687 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001688 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001689
Abramo Bagnara25777432010-08-11 22:01:17 +00001690 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001691 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001692 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001693
John McCallf7a1a742009-11-24 19:00:30 +00001694 // C++ [temp.dep.expr]p3:
1695 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001696 // -- an identifier that was declared with a dependent type,
1697 // (note: handled after lookup)
1698 // -- a template-id that is dependent,
1699 // (note: handled in BuildTemplateIdExpr)
1700 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001701 // -- a nested-name-specifier that contains a class-name that
1702 // names a dependent type.
1703 // Determine whether this is a member of an unknown specialization;
1704 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001705 bool DependentID = false;
1706 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1707 Name.getCXXNameType()->isDependentType()) {
1708 DependentID = true;
1709 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001710 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001711 if (RequireCompleteDeclContext(SS, DC))
1712 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001713 } else {
1714 DependentID = true;
1715 }
1716 }
1717
Chris Lattner337e5502011-02-18 01:27:55 +00001718 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001719 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1720 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001721
John McCallf7a1a742009-11-24 19:00:30 +00001722 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001723 LookupResult R(*this, NameInfo,
1724 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1725 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001726 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001727 // Lookup the template name again to correctly establish the context in
1728 // which it was found. This is really unfortunate as we already did the
1729 // lookup to determine that it was a template name in the first place. If
1730 // this becomes a performance hit, we can work harder to preserve those
1731 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001732 bool MemberOfUnknownSpecialization;
1733 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1734 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001735
1736 if (MemberOfUnknownSpecialization ||
1737 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1739 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001740 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001742 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001744 // If the result might be in a dependent base class, this is a dependent
1745 // id-expression.
1746 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748 IsAddressOfOperand, TemplateArgs);
1749
John McCallf7a1a742009-11-24 19:00:30 +00001750 // If this reference is in an Objective-C method, then we need to do
1751 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001752 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001753 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (E.isInvalid())
1755 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Chris Lattner337e5502011-02-18 01:27:55 +00001757 if (Expr *Ex = E.takeAs<Expr>())
1758 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001759 }
Chris Lattner8a934232008-03-31 00:36:02 +00001760 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001761
John McCallf7a1a742009-11-24 19:00:30 +00001762 if (R.isAmbiguous())
1763 return ExprError();
1764
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001765 // Determine whether this name might be a candidate for
1766 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001767 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001768
John McCallf7a1a742009-11-24 19:00:30 +00001769 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001771 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001772 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001773 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1774 if (D) R.addDecl(D);
1775 }
1776
1777 // If this name wasn't predeclared and if this is not a function
1778 // call, diagnose the problem.
1779 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001780
1781 // In Microsoft mode, if we are inside a template class member function
1782 // and we can't resolve an identifier then assume the identifier is type
1783 // dependent. The goal is to postpone name lookup to instantiation time
1784 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001785 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001786 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001787 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1788 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001789
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001790 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001791 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001792 return ExprError();
1793
1794 assert(!R.empty() &&
1795 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001796
1797 // If we found an Objective-C instance variable, let
1798 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001799 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001800 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1801 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001802 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001803 // In a hopelessly buggy code, Objective-C instance variable
1804 // lookup fails and no expression will be built to reference it.
1805 if (!E.isInvalid() && !E.get())
1806 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001807 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001808 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 }
1810 }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 // This is guaranteed from this point on.
1813 assert(!R.empty() || ADL);
1814
John McCallaa81e162009-12-01 22:10:20 +00001815 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001816 // C++ [class.mfct.non-static]p3:
1817 // When an id-expression that is not part of a class member access
1818 // syntax and not used to form a pointer to member is used in the
1819 // body of a non-static member function of class X, if name lookup
1820 // resolves the name in the id-expression to a non-static non-type
1821 // member of some class C, the id-expression is transformed into a
1822 // class member access expression using (*this) as the
1823 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001824 //
1825 // But we don't actually need to do this for '&' operands if R
1826 // resolved to a function or overloaded function set, because the
1827 // expression is ill-formed if it actually works out to be a
1828 // non-static member function:
1829 //
1830 // C++ [expr.ref]p4:
1831 // Otherwise, if E1.E2 refers to a non-static member function. . .
1832 // [t]he expression can be used only as the left-hand operand of a
1833 // member function call.
1834 //
1835 // There are other safeguards against such uses, but it's important
1836 // to get this right here so that we don't end up making a
1837 // spuriously dependent expression if we're inside a dependent
1838 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001839 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001840 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001841 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001842 MightBeImplicitMember = true;
1843 else if (!SS.isEmpty())
1844 MightBeImplicitMember = false;
1845 else if (R.isOverloadedResult())
1846 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001847 else if (R.isUnresolvableResult())
1848 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001849 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001850 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1851 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001852
1853 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001854 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1855 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001856 }
1857
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001858 if (TemplateArgs || TemplateKWLoc.isValid())
1859 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001860
John McCallf7a1a742009-11-24 19:00:30 +00001861 return BuildDeclarationNameExpr(SS, R, ADL);
1862}
1863
John McCall129e2df2009-11-30 22:42:35 +00001864/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1865/// declaration name, generally during template instantiation.
1866/// There's a large number of things which don't need to be done along
1867/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001868ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001869Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001870 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001871 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001872 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001873 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1874 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001875
John McCall77bb1aa2010-05-01 00:40:08 +00001876 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001877 return ExprError();
1878
Abramo Bagnara25777432010-08-11 22:01:17 +00001879 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001880 LookupQualifiedName(R, DC);
1881
1882 if (R.isAmbiguous())
1883 return ExprError();
1884
1885 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001886 Diag(NameInfo.getLoc(), diag::err_no_member)
1887 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001888 return ExprError();
1889 }
1890
1891 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1892}
1893
1894/// LookupInObjCMethod - The parser has read a name in, and Sema has
1895/// detected that we're currently inside an ObjC method. Perform some
1896/// additional lookup.
1897///
1898/// Ideally, most of this would be done by lookup, but there's
1899/// actually quite a lot of extra work involved.
1900///
1901/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001902ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001903Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001904 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001905 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001906 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001907
John McCallf7a1a742009-11-24 19:00:30 +00001908 // There are two cases to handle here. 1) scoped lookup could have failed,
1909 // in which case we should look for an ivar. 2) scoped lookup could have
1910 // found a decl, but that decl is outside the current instance method (i.e.
1911 // a global variable). In these two cases, we do a lookup for an ivar with
1912 // this name, if the lookup sucedes, we replace it our current decl.
1913
1914 // If we're in a class method, we don't normally want to look for
1915 // ivars. But if we don't find anything else, and there's an
1916 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001917 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001918
1919 bool LookForIvars;
1920 if (Lookup.empty())
1921 LookForIvars = true;
1922 else if (IsClassMethod)
1923 LookForIvars = false;
1924 else
1925 LookForIvars = (Lookup.isSingleResult() &&
1926 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001927 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001928 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001929 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001930 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001931 ObjCIvarDecl *IV = 0;
1932 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001933 // Diagnose using an ivar in a class method.
1934 if (IsClassMethod)
1935 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1936 << IV->getDeclName());
1937
1938 // If we're referencing an invalid decl, just return this as a silent
1939 // error node. The error diagnostic was already emitted on the decl.
1940 if (IV->isInvalidDecl())
1941 return ExprError();
1942
1943 // Check if referencing a field with __attribute__((deprecated)).
1944 if (DiagnoseUseOfDecl(IV, Loc))
1945 return ExprError();
1946
1947 // Diagnose the use of an ivar outside of the declaring class.
1948 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001949 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001950 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001951 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1952
1953 // FIXME: This should use a new expr for a direct reference, don't
1954 // turn this into Self->ivar, just return a BareIVarExpr or something.
1955 IdentifierInfo &II = Context.Idents.get("self");
1956 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001957 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001958 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001959 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001960 SourceLocation TemplateKWLoc;
1961 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001962 SelfName, false, false);
1963 if (SelfExpr.isInvalid())
1964 return ExprError();
1965
John Wiegley429bb272011-04-08 18:41:53 +00001966 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1967 if (SelfExpr.isInvalid())
1968 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001969
Eli Friedman5f2987c2012-02-02 03:46:19 +00001970 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001971
1972 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1973 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1974 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCallf7a1a742009-11-24 19:00:30 +00001975 return Owned(new (Context)
1976 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001977 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001978 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001979 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001980 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001981 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1982 ObjCInterfaceDecl *ClassDeclared;
1983 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1984 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001985 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001986 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1987 }
John McCallf7a1a742009-11-24 19:00:30 +00001988 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001989 } else if (Lookup.isSingleResult() &&
1990 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1991 // If accessing a stand-alone ivar in a class method, this is an error.
1992 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1993 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1994 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001995 }
1996
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001997 if (Lookup.empty() && II && AllowBuiltinCreation) {
1998 // FIXME. Consolidate this with similar code in LookupName.
1999 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002000 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002001 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2002 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2003 S, Lookup.isForRedeclaration(),
2004 Lookup.getNameLoc());
2005 if (D) Lookup.addDecl(D);
2006 }
2007 }
2008 }
John McCallf7a1a742009-11-24 19:00:30 +00002009 // Sentinel value saying that we didn't do anything special.
2010 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002011}
John McCallba135432009-11-21 08:51:07 +00002012
John McCall6bb80172010-03-30 21:47:33 +00002013/// \brief Cast a base object to a member's actual type.
2014///
2015/// Logically this happens in three phases:
2016///
2017/// * First we cast from the base type to the naming class.
2018/// The naming class is the class into which we were looking
2019/// when we found the member; it's the qualifier type if a
2020/// qualifier was provided, and otherwise it's the base type.
2021///
2022/// * Next we cast from the naming class to the declaring class.
2023/// If the member we found was brought into a class's scope by
2024/// a using declaration, this is that class; otherwise it's
2025/// the class declaring the member.
2026///
2027/// * Finally we cast from the declaring class to the "true"
2028/// declaring class of the member. This conversion does not
2029/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002030ExprResult
2031Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002032 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002033 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002034 NamedDecl *Member) {
2035 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2036 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002037 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002038
Douglas Gregor5fccd362010-03-03 23:55:11 +00002039 QualType DestRecordType;
2040 QualType DestType;
2041 QualType FromRecordType;
2042 QualType FromType = From->getType();
2043 bool PointerConversions = false;
2044 if (isa<FieldDecl>(Member)) {
2045 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002046
Douglas Gregor5fccd362010-03-03 23:55:11 +00002047 if (FromType->getAs<PointerType>()) {
2048 DestType = Context.getPointerType(DestRecordType);
2049 FromRecordType = FromType->getPointeeType();
2050 PointerConversions = true;
2051 } else {
2052 DestType = DestRecordType;
2053 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002054 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002055 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2056 if (Method->isStatic())
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 DestType = Method->getThisType(Context);
2060 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002061
Douglas Gregor5fccd362010-03-03 23:55:11 +00002062 if (FromType->getAs<PointerType>()) {
2063 FromRecordType = FromType->getPointeeType();
2064 PointerConversions = true;
2065 } else {
2066 FromRecordType = FromType;
2067 DestType = DestRecordType;
2068 }
2069 } else {
2070 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002071 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002072 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002073
Douglas Gregor5fccd362010-03-03 23:55:11 +00002074 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002075 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002076
Douglas Gregor5fccd362010-03-03 23:55:11 +00002077 // If the unqualified types are the same, no conversion is necessary.
2078 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002079 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002080
John McCall6bb80172010-03-30 21:47:33 +00002081 SourceRange FromRange = From->getSourceRange();
2082 SourceLocation FromLoc = FromRange.getBegin();
2083
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002084 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002085
Douglas Gregor5fccd362010-03-03 23:55:11 +00002086 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002087 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002088 // class name.
2089 //
2090 // If the member was a qualified name and the qualified referred to a
2091 // specific base subobject type, we'll cast to that intermediate type
2092 // first and then to the object in which the member is declared. That allows
2093 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2094 //
2095 // class Base { public: int x; };
2096 // class Derived1 : public Base { };
2097 // class Derived2 : public Base { };
2098 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2099 //
2100 // void VeryDerived::f() {
2101 // x = 17; // error: ambiguous base subobjects
2102 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2103 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002104 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002105 QualType QType = QualType(Qualifier->getAsType(), 0);
2106 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2107 assert(QType->isRecordType() && "lookup done with non-record type");
2108
2109 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2110
2111 // In C++98, the qualifier type doesn't actually have to be a base
2112 // type of the object type, in which case we just ignore it.
2113 // Otherwise build the appropriate casts.
2114 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002115 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002116 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002117 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002118 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002119
Douglas Gregor5fccd362010-03-03 23:55:11 +00002120 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002121 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002122 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2123 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002124
2125 FromType = QType;
2126 FromRecordType = QRecordType;
2127
2128 // If the qualifier type was the same as the destination type,
2129 // we're done.
2130 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002131 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002132 }
2133 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002134
John McCall6bb80172010-03-30 21:47:33 +00002135 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002136
John McCall6bb80172010-03-30 21:47:33 +00002137 // If we actually found the member through a using declaration, cast
2138 // down to the using declaration's type.
2139 //
2140 // Pointer equality is fine here because only one declaration of a
2141 // class ever has member declarations.
2142 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2143 assert(isa<UsingShadowDecl>(FoundDecl));
2144 QualType URecordType = Context.getTypeDeclType(
2145 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2146
2147 // We only need to do this if the naming-class to declaring-class
2148 // conversion is non-trivial.
2149 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2150 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002151 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002152 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002153 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002154 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002155
John McCall6bb80172010-03-30 21:47:33 +00002156 QualType UType = URecordType;
2157 if (PointerConversions)
2158 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002159 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2160 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002161 FromType = UType;
2162 FromRecordType = URecordType;
2163 }
2164
2165 // We don't do access control for the conversion from the
2166 // declaring class to the true declaring class.
2167 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002168 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002169
John McCallf871d0c2010-08-07 06:22:56 +00002170 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002171 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2172 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002173 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002174 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002175
John Wiegley429bb272011-04-08 18:41:53 +00002176 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2177 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002178}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002179
John McCallf7a1a742009-11-24 19:00:30 +00002180bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002181 const LookupResult &R,
2182 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002183 // Only when used directly as the postfix-expression of a call.
2184 if (!HasTrailingLParen)
2185 return false;
2186
2187 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002188 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002189 return false;
2190
2191 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002192 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002193 return false;
2194
2195 // Turn off ADL when we find certain kinds of declarations during
2196 // normal lookup:
2197 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2198 NamedDecl *D = *I;
2199
2200 // C++0x [basic.lookup.argdep]p3:
2201 // -- a declaration of a class member
2202 // Since using decls preserve this property, we check this on the
2203 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002204 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002205 return false;
2206
2207 // C++0x [basic.lookup.argdep]p3:
2208 // -- a block-scope function declaration that is not a
2209 // using-declaration
2210 // NOTE: we also trigger this for function templates (in fact, we
2211 // don't check the decl type at all, since all other decl types
2212 // turn off ADL anyway).
2213 if (isa<UsingShadowDecl>(D))
2214 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2215 else if (D->getDeclContext()->isFunctionOrMethod())
2216 return false;
2217
2218 // C++0x [basic.lookup.argdep]p3:
2219 // -- a declaration that is neither a function or a function
2220 // template
2221 // And also for builtin functions.
2222 if (isa<FunctionDecl>(D)) {
2223 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2224
2225 // But also builtin functions.
2226 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2227 return false;
2228 } else if (!isa<FunctionTemplateDecl>(D))
2229 return false;
2230 }
2231
2232 return true;
2233}
2234
2235
John McCallba135432009-11-21 08:51:07 +00002236/// Diagnoses obvious problems with the use of the given declaration
2237/// as an expression. This is only actually called for lookups that
2238/// were not overloaded, and it doesn't promise that the declaration
2239/// will in fact be used.
2240static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002241 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002242 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2243 return true;
2244 }
2245
2246 if (isa<ObjCInterfaceDecl>(D)) {
2247 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2248 return true;
2249 }
2250
2251 if (isa<NamespaceDecl>(D)) {
2252 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2253 return true;
2254 }
2255
2256 return false;
2257}
2258
John McCall60d7b3a2010-08-24 06:29:42 +00002259ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002260Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002261 LookupResult &R,
2262 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002263 // If this is a single, fully-resolved result and we don't need ADL,
2264 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002265 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002266 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2267 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002268
2269 // We only need to check the declaration if there's exactly one
2270 // result, because in the overloaded case the results can only be
2271 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002272 if (R.isSingleResult() &&
2273 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002274 return ExprError();
2275
John McCallc373d482010-01-27 01:50:18 +00002276 // Otherwise, just build an unresolved lookup expression. Suppress
2277 // any lookup-related diagnostics; we'll hash these out later, when
2278 // we've picked a target.
2279 R.suppressDiagnostics();
2280
John McCallba135432009-11-21 08:51:07 +00002281 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002282 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002283 SS.getWithLocInContext(Context),
2284 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002285 NeedsADL, R.isOverloadedResult(),
2286 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002287
2288 return Owned(ULE);
2289}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002290
John McCallba135432009-11-21 08:51:07 +00002291/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002292ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002293Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002294 const DeclarationNameInfo &NameInfo,
2295 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002296 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002297 assert(!isa<FunctionTemplateDecl>(D) &&
2298 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002299
Abramo Bagnara25777432010-08-11 22:01:17 +00002300 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002301 if (CheckDeclInExpr(*this, Loc, D))
2302 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002303
Douglas Gregor9af2f522009-12-01 16:58:18 +00002304 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2305 // Specifically diagnose references to class templates that are missing
2306 // a template argument list.
2307 Diag(Loc, diag::err_template_decl_ref)
2308 << Template << SS.getRange();
2309 Diag(Template->getLocation(), diag::note_template_decl_here);
2310 return ExprError();
2311 }
2312
2313 // Make sure that we're referring to a value.
2314 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2315 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002316 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002317 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002318 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002319 return ExprError();
2320 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002321
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002322 // Check whether this declaration can be used. Note that we suppress
2323 // this check when we're going to perform argument-dependent lookup
2324 // on this function name, because this might not be the function
2325 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002326 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002327 return ExprError();
2328
Steve Naroffdd972f22008-09-05 22:11:13 +00002329 // Only create DeclRefExpr's for valid Decl's.
2330 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002331 return ExprError();
2332
John McCall5808ce42011-02-03 08:15:49 +00002333 // Handle members of anonymous structs and unions. If we got here,
2334 // and the reference is to a class member indirect field, then this
2335 // must be the subject of a pointer-to-member expression.
2336 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2337 if (!indirectField->isCXXClassMember())
2338 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2339 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002340
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002341 {
John McCall76a40212011-02-09 01:13:10 +00002342 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002343 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002344
2345 switch (D->getKind()) {
2346 // Ignore all the non-ValueDecl kinds.
2347#define ABSTRACT_DECL(kind)
2348#define VALUE(type, base)
2349#define DECL(type, base) \
2350 case Decl::type:
2351#include "clang/AST/DeclNodes.inc"
2352 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002353
2354 // These shouldn't make it here.
2355 case Decl::ObjCAtDefsField:
2356 case Decl::ObjCIvar:
2357 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002358
2359 // Enum constants are always r-values and never references.
2360 // Unresolved using declarations are dependent.
2361 case Decl::EnumConstant:
2362 case Decl::UnresolvedUsingValue:
2363 valueKind = VK_RValue;
2364 break;
2365
2366 // Fields and indirect fields that got here must be for
2367 // pointer-to-member expressions; we just call them l-values for
2368 // internal consistency, because this subexpression doesn't really
2369 // exist in the high-level semantics.
2370 case Decl::Field:
2371 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002372 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002373 "building reference to field in C?");
2374
2375 // These can't have reference type in well-formed programs, but
2376 // for internal consistency we do this anyway.
2377 type = type.getNonReferenceType();
2378 valueKind = VK_LValue;
2379 break;
2380
2381 // Non-type template parameters are either l-values or r-values
2382 // depending on the type.
2383 case Decl::NonTypeTemplateParm: {
2384 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2385 type = reftype->getPointeeType();
2386 valueKind = VK_LValue; // even if the parameter is an r-value reference
2387 break;
2388 }
2389
2390 // For non-references, we need to strip qualifiers just in case
2391 // the template parameter was declared as 'const int' or whatever.
2392 valueKind = VK_RValue;
2393 type = type.getUnqualifiedType();
2394 break;
2395 }
2396
2397 case Decl::Var:
2398 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002399 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002400 !type.hasQualifiers() &&
2401 type->isVoidType()) {
2402 valueKind = VK_RValue;
2403 break;
2404 }
2405 // fallthrough
2406
2407 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002408 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002409 // These are always l-values.
2410 valueKind = VK_LValue;
2411 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002412
Douglas Gregor68932842012-02-18 05:51:20 +00002413 // FIXME: Does the addition of const really only apply in
2414 // potentially-evaluated contexts? Since the variable isn't actually
2415 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002416 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002417 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2418 if (!CapturedType.isNull())
2419 type = CapturedType;
2420 }
2421
John McCall76a40212011-02-09 01:13:10 +00002422 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002423 }
2424
John McCall76a40212011-02-09 01:13:10 +00002425 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002426 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2427 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2428 type = Context.BuiltinFnTy;
2429 valueKind = VK_RValue;
2430 break;
2431 }
2432 }
2433
John McCall755d8492011-04-12 00:42:48 +00002434 const FunctionType *fty = type->castAs<FunctionType>();
2435
2436 // If we're referring to a function with an __unknown_anytype
2437 // result type, make the entire expression __unknown_anytype.
2438 if (fty->getResultType() == Context.UnknownAnyTy) {
2439 type = Context.UnknownAnyTy;
2440 valueKind = VK_RValue;
2441 break;
2442 }
2443
John McCall76a40212011-02-09 01:13:10 +00002444 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002445 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002446 valueKind = VK_LValue;
2447 break;
2448 }
2449
2450 // C99 DR 316 says that, if a function type comes from a
2451 // function definition (without a prototype), that type is only
2452 // used for checking compatibility. Therefore, when referencing
2453 // the function, we pretend that we don't have the full function
2454 // type.
John McCall755d8492011-04-12 00:42:48 +00002455 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2456 isa<FunctionProtoType>(fty))
2457 type = Context.getFunctionNoProtoType(fty->getResultType(),
2458 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002459
2460 // Functions are r-values in C.
2461 valueKind = VK_RValue;
2462 break;
2463 }
2464
2465 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002466 // If we're referring to a method with an __unknown_anytype
2467 // result type, make the entire expression __unknown_anytype.
2468 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002469 if (const FunctionProtoType *proto
2470 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002471 if (proto->getResultType() == Context.UnknownAnyTy) {
2472 type = Context.UnknownAnyTy;
2473 valueKind = VK_RValue;
2474 break;
2475 }
2476
John McCall76a40212011-02-09 01:13:10 +00002477 // C++ methods are l-values if static, r-values if non-static.
2478 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2479 valueKind = VK_LValue;
2480 break;
2481 }
2482 // fallthrough
2483
2484 case Decl::CXXConversion:
2485 case Decl::CXXDestructor:
2486 case Decl::CXXConstructor:
2487 valueKind = VK_RValue;
2488 break;
2489 }
2490
2491 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2492 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002493}
2494
John McCall755d8492011-04-12 00:42:48 +00002495ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002496 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002497
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002499 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002500 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2501 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002502 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002505
Chris Lattnerfa28b302008-01-12 08:14:25 +00002506 // Pre-defined identifiers are of type char[x], where x is the length of the
2507 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Anders Carlsson3a082d82009-09-08 18:24:21 +00002509 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002510 if (!currentDecl && getCurBlock())
2511 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002512 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002513 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002514 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002515 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002516
Anders Carlsson773f3972009-09-11 01:22:35 +00002517 QualType ResTy;
2518 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2519 ResTy = Context.DependentTy;
2520 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002521 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002522
Anders Carlsson773f3972009-09-11 01:22:35 +00002523 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002524 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002525 ResTy = Context.WCharTy.withConst();
2526 else
2527 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002528 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2529 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002530 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002531}
2532
Richard Smith36f5cfe2012-03-09 08:00:36 +00002533ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002534 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002535 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002537 if (Invalid)
2538 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002539
Benjamin Kramerddeea562010-02-27 13:44:12 +00002540 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002541 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002543 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002544
Chris Lattnere8337df2009-12-30 21:19:39 +00002545 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002546 if (Literal.isWide())
2547 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002548 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002549 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002550 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002551 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002552 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002553 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002554 else
2555 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002556
Douglas Gregor5cee1192011-07-27 05:40:30 +00002557 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2558 if (Literal.isWide())
2559 Kind = CharacterLiteral::Wide;
2560 else if (Literal.isUTF16())
2561 Kind = CharacterLiteral::UTF16;
2562 else if (Literal.isUTF32())
2563 Kind = CharacterLiteral::UTF32;
2564
Richard Smithdd66be72012-03-08 01:34:56 +00002565 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2566 Tok.getLocation());
2567
2568 if (Literal.getUDSuffix().empty())
2569 return Owned(Lit);
2570
2571 // We're building a user-defined literal.
2572 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2573 SourceLocation UDSuffixLoc =
2574 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2575
Richard Smith36f5cfe2012-03-09 08:00:36 +00002576 // Make sure we're allowed user-defined literals here.
2577 if (!UDLScope)
2578 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2579
Richard Smithdd66be72012-03-08 01:34:56 +00002580 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2581 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002582 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2583 llvm::makeArrayRef(&Lit, 1),
2584 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002585}
2586
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002587ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2588 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2589 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2590 Context.IntTy, Loc));
2591}
2592
Richard Smithb453ad32012-03-08 08:45:32 +00002593static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2594 QualType Ty, SourceLocation Loc) {
2595 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2596
2597 using llvm::APFloat;
2598 APFloat Val(Format);
2599
2600 APFloat::opStatus result = Literal.GetFloatValue(Val);
2601
2602 // Overflow is always an error, but underflow is only an error if
2603 // we underflowed to zero (APFloat reports denormals as underflow).
2604 if ((result & APFloat::opOverflow) ||
2605 ((result & APFloat::opUnderflow) && Val.isZero())) {
2606 unsigned diagnostic;
2607 SmallString<20> buffer;
2608 if (result & APFloat::opOverflow) {
2609 diagnostic = diag::warn_float_overflow;
2610 APFloat::getLargest(Format).toString(buffer);
2611 } else {
2612 diagnostic = diag::warn_float_underflow;
2613 APFloat::getSmallest(Format).toString(buffer);
2614 }
2615
2616 S.Diag(Loc, diagnostic)
2617 << Ty
2618 << StringRef(buffer.data(), buffer.size());
2619 }
2620
2621 bool isExact = (result == APFloat::opOK);
2622 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2623}
2624
Richard Smith36f5cfe2012-03-09 08:00:36 +00002625ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002626 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002627 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002629 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002630 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 }
Ted Kremenek28396602009-01-13 23:19:12 +00002632
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002633 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002634 // Add padding so that NumericLiteralParser can overread by one character.
2635 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002639 bool Invalid = false;
2640 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2641 if (Invalid)
2642 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002643
Mike Stump1eb44332009-09-09 15:08:12 +00002644 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 Tok.getLocation(), PP);
2646 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002647 return ExprError();
2648
Richard Smithb453ad32012-03-08 08:45:32 +00002649 if (Literal.hasUDSuffix()) {
2650 // We're building a user-defined literal.
2651 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2652 SourceLocation UDSuffixLoc =
2653 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2654
Richard Smith36f5cfe2012-03-09 08:00:36 +00002655 // Make sure we're allowed user-defined literals here.
2656 if (!UDLScope)
2657 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002658
Richard Smith36f5cfe2012-03-09 08:00:36 +00002659 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002660 if (Literal.isFloatingLiteral()) {
2661 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2662 // long double, the literal is treated as a call of the form
2663 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002664 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002665 } else {
2666 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2667 // unsigned long long, the literal is treated as a call of the form
2668 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002669 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002670 }
2671
Richard Smith36f5cfe2012-03-09 08:00:36 +00002672 DeclarationName OpName =
2673 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2674 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2675 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2676
2677 // Perform literal operator lookup to determine if we're building a raw
2678 // literal or a cooked one.
2679 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2680 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2681 /*AllowRawAndTemplate*/true)) {
2682 case LOLR_Error:
2683 return ExprError();
2684
2685 case LOLR_Cooked: {
2686 Expr *Lit;
2687 if (Literal.isFloatingLiteral()) {
2688 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2689 } else {
2690 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2691 if (Literal.GetIntegerValue(ResultVal))
2692 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2693 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2694 Tok.getLocation());
2695 }
2696 return BuildLiteralOperatorCall(R, OpNameInfo,
2697 llvm::makeArrayRef(&Lit, 1),
2698 Tok.getLocation());
2699 }
2700
2701 case LOLR_Raw: {
2702 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2703 // literal is treated as a call of the form
2704 // operator "" X ("n")
2705 SourceLocation TokLoc = Tok.getLocation();
2706 unsigned Length = Literal.getUDSuffixOffset();
2707 QualType StrTy = Context.getConstantArrayType(
2708 Context.CharTy, llvm::APInt(32, Length + 1),
2709 ArrayType::Normal, 0);
2710 Expr *Lit = StringLiteral::Create(
2711 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2712 /*Pascal*/false, StrTy, &TokLoc, 1);
2713 return BuildLiteralOperatorCall(R, OpNameInfo,
2714 llvm::makeArrayRef(&Lit, 1), TokLoc);
2715 }
2716
2717 case LOLR_Template:
2718 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2719 // template), L is treated as a call fo the form
2720 // operator "" X <'c1', 'c2', ... 'ck'>()
2721 // where n is the source character sequence c1 c2 ... ck.
2722 TemplateArgumentListInfo ExplicitArgs;
2723 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2724 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2725 llvm::APSInt Value(CharBits, CharIsUnsigned);
2726 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2727 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002728 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002729 TemplateArgumentLocInfo ArgInfo;
2730 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2731 }
2732 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2733 Tok.getLocation(), &ExplicitArgs);
2734 }
2735
2736 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002737 }
2738
Chris Lattner5d661452007-08-26 03:42:43 +00002739 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002740
Chris Lattner5d661452007-08-26 03:42:43 +00002741 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002742 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002743 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002744 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002745 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002746 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002747 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002748 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002749
Richard Smithb453ad32012-03-08 08:45:32 +00002750 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002751
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002752 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002753 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002754 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002755 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002756 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002757 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002758 }
2759 }
Chris Lattner5d661452007-08-26 03:42:43 +00002760 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002761 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002762 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002763 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002764
Neil Boothb9449512007-08-29 22:00:19 +00002765 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002766 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002767 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002768 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002769 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002770
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002772 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2773 // The microsoft literal suffix extensions support 128-bit literals, which
2774 // may be wider than [u]intmax_t.
2775 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2776 MaxWidth = 128;
2777 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002778
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 if (Literal.GetIntegerValue(ResultVal)) {
2780 // If this value didn't fit into uintmax_t, warn and force to ull.
2781 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002782 Ty = Context.UnsignedLongLongTy;
2783 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002784 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 } else {
2786 // If this value fits into a ULL, try to figure out what else it fits into
2787 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002788
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2790 // be an unsigned int.
2791 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2792
2793 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002794 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002795 if (!Literal.isLong && !Literal.isLongLong) {
2796 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002797 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002798
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // Does it fit in a unsigned int?
2800 if (ResultVal.isIntN(IntSize)) {
2801 // Does it fit in a signed int?
2802 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002805 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002806 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002809
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002811 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002812 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002813
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 // Does it fit in a unsigned long?
2815 if (ResultVal.isIntN(LongSize)) {
2816 // Does it fit in a signed long?
2817 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002818 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002820 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002821 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002823 }
2824
Stephen Canonb9e05f12012-05-03 22:49:43 +00002825 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002826 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002827 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002828
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 // Does it fit in a unsigned long long?
2830 if (ResultVal.isIntN(LongLongSize)) {
2831 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002832 // To be compatible with MSVC, hex integer literals ending with the
2833 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002834 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002835 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002836 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002838 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002839 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 }
2841 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002842
2843 // If it doesn't fit in unsigned long long, and we're using Microsoft
2844 // extensions, then its a 128-bit integer literal.
2845 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2846 if (Literal.isUnsigned)
2847 Ty = Context.UnsignedInt128Ty;
2848 else
2849 Ty = Context.Int128Ty;
2850 Width = 128;
2851 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002852
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 // If we still couldn't decide a type, we probably have something that
2854 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002855 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002857 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002858 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002860
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002861 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002862 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002864 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002865 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002866
Chris Lattner5d661452007-08-26 03:42:43 +00002867 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2868 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002869 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002870 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002871
2872 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
Richard Trieuccd891a2011-09-09 01:45:06 +00002875ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002876 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002877 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002878}
2879
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002880static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2881 SourceLocation Loc,
2882 SourceRange ArgRange) {
2883 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2884 // scalar or vector data type argument..."
2885 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2886 // type (C99 6.2.5p18) or void.
2887 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2888 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2889 << T << ArgRange;
2890 return true;
2891 }
2892
2893 assert((T->isVoidType() || !T->isIncompleteType()) &&
2894 "Scalar types should always be complete");
2895 return false;
2896}
2897
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002898static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2899 SourceLocation Loc,
2900 SourceRange ArgRange,
2901 UnaryExprOrTypeTrait TraitKind) {
2902 // C99 6.5.3.4p1:
2903 if (T->isFunctionType()) {
2904 // alignof(function) is allowed as an extension.
2905 if (TraitKind == UETT_SizeOf)
2906 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2907 return false;
2908 }
2909
2910 // Allow sizeof(void)/alignof(void) as an extension.
2911 if (T->isVoidType()) {
2912 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2913 return false;
2914 }
2915
2916 return true;
2917}
2918
2919static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2920 SourceLocation Loc,
2921 SourceRange ArgRange,
2922 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002923 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2924 // runtime doesn't allow it.
2925 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002926 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2927 << T << (TraitKind == UETT_SizeOf)
2928 << ArgRange;
2929 return true;
2930 }
2931
2932 return false;
2933}
2934
Chandler Carruth9d342d02011-05-26 08:53:10 +00002935/// \brief Check the constrains on expression operands to unary type expression
2936/// and type traits.
2937///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002938/// Completes any types necessary and validates the constraints on the operand
2939/// expression. The logic mostly mirrors the type-based overload, but may modify
2940/// the expression as it completes the type for that expression through template
2941/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002942bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002943 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002944 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002945
2946 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2947 // the result is the size of the referenced type."
2948 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2949 // result shall be the alignment of the referenced type."
2950 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2951 ExprTy = Ref->getPointeeType();
2952
2953 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002954 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2955 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002956
2957 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002958 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2959 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002960 return false;
2961
Richard Trieuccd891a2011-09-09 01:45:06 +00002962 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002963 diag::err_sizeof_alignof_incomplete_type,
2964 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002965 return true;
2966
2967 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002968 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002969 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2970 ExprTy = Ref->getPointeeType();
2971
Richard Trieuccd891a2011-09-09 01:45:06 +00002972 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2973 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002974 return true;
2975
Nico Webercf739922011-06-15 02:47:03 +00002976 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002977 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002978 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2979 QualType OType = PVD->getOriginalType();
2980 QualType Type = PVD->getType();
2981 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002982 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002983 << Type << OType;
2984 Diag(PVD->getLocation(), diag::note_declared_at);
2985 }
2986 }
2987 }
2988 }
2989
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002990 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002991}
2992
2993/// \brief Check the constraints on operands to unary expression and type
2994/// traits.
2995///
2996/// This will complete any types necessary, and validate the various constraints
2997/// on those operands.
2998///
Reid Spencer5f016e22007-07-11 17:01:13 +00002999/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003000/// C99 6.3.2.1p[2-4] all state:
3001/// Except when it is the operand of the sizeof operator ...
3002///
3003/// C++ [expr.sizeof]p4
3004/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3005/// standard conversions are not applied to the operand of sizeof.
3006///
3007/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003008bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003009 SourceLocation OpLoc,
3010 SourceRange ExprRange,
3011 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003012 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003013 return false;
3014
Sebastian Redl5d484e82009-11-23 17:18:46 +00003015 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3016 // the result is the size of the referenced type."
3017 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3018 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003019 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3020 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003021
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003022 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003023 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003024
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003025 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003026 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003027 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003028 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Richard Trieuccd891a2011-09-09 01:45:06 +00003030 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003031 diag::err_sizeof_alignof_incomplete_type,
3032 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003033 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Richard Trieuccd891a2011-09-09 01:45:06 +00003035 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003036 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003037 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Chris Lattner1efaa952009-04-24 00:30:45 +00003039 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003040}
3041
Chandler Carruth9d342d02011-05-26 08:53:10 +00003042static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003043 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003044
Mike Stump1eb44332009-09-09 15:08:12 +00003045 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003046 if (isa<DeclRefExpr>(E))
3047 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003048
3049 // Cannot know anything else if the expression is dependent.
3050 if (E->isTypeDependent())
3051 return false;
3052
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003053 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003054 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3055 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003056 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003057 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003058
3059 // Alignment of a field access is always okay, so long as it isn't a
3060 // bit-field.
3061 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003062 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003063 return false;
3064
Chandler Carruth9d342d02011-05-26 08:53:10 +00003065 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003066}
3067
Chandler Carruth9d342d02011-05-26 08:53:10 +00003068bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003069 E = E->IgnoreParens();
3070
3071 // Cannot know anything else if the expression is dependent.
3072 if (E->isTypeDependent())
3073 return false;
3074
Chandler Carruth9d342d02011-05-26 08:53:10 +00003075 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003076}
3077
Douglas Gregorba498172009-03-13 21:01:28 +00003078/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003079ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003080Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3081 SourceLocation OpLoc,
3082 UnaryExprOrTypeTrait ExprKind,
3083 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003084 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003085 return ExprError();
3086
John McCalla93c9342009-12-07 02:54:59 +00003087 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003088
Douglas Gregorba498172009-03-13 21:01:28 +00003089 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003090 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003091 return ExprError();
3092
3093 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003094 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3095 Context.getSizeType(),
3096 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003097}
3098
3099/// \brief Build a sizeof or alignof expression given an expression
3100/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003101ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003102Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3103 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003104 ExprResult PE = CheckPlaceholderExpr(E);
3105 if (PE.isInvalid())
3106 return ExprError();
3107
3108 E = PE.get();
3109
Douglas Gregorba498172009-03-13 21:01:28 +00003110 // Verify that the operand is valid.
3111 bool isInvalid = false;
3112 if (E->isTypeDependent()) {
3113 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003114 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003115 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003116 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003117 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003118 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003119 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003120 isInvalid = true;
3121 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003122 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003123 }
3124
3125 if (isInvalid)
3126 return ExprError();
3127
Eli Friedman71b8fb52012-01-21 01:01:51 +00003128 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3129 PE = TranformToPotentiallyEvaluated(E);
3130 if (PE.isInvalid()) return ExprError();
3131 E = PE.take();
3132 }
3133
Douglas Gregorba498172009-03-13 21:01:28 +00003134 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003135 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003136 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003137 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003138}
3139
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003140/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3141/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003142/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003143ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003144Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003145 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003146 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003148 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003149
Richard Trieuccd891a2011-09-09 01:45:06 +00003150 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003151 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003152 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003153 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003154 }
Sebastian Redl05189992008-11-11 17:56:53 +00003155
Douglas Gregorba498172009-03-13 21:01:28 +00003156 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003157 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003158 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003159}
3160
John Wiegley429bb272011-04-08 18:41:53 +00003161static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003162 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003163 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003164 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003165
John McCallf6a16482010-12-04 03:47:34 +00003166 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003167 if (V.get()->getObjectKind() != OK_Ordinary) {
3168 V = S.DefaultLvalueConversion(V.take());
3169 if (V.isInvalid())
3170 return QualType();
3171 }
John McCallf6a16482010-12-04 03:47:34 +00003172
Chris Lattnercc26ed72007-08-26 05:39:26 +00003173 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003174 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003175 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Chris Lattnercc26ed72007-08-26 05:39:26 +00003177 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003178 if (V.get()->getType()->isArithmeticType())
3179 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
John McCall2cd11fe2010-10-12 02:09:17 +00003181 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003182 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003183 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003184 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003185 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003186 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003187 }
3188
Chris Lattnercc26ed72007-08-26 05:39:26 +00003189 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003190 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003191 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003192 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003193}
3194
3195
Reid Spencer5f016e22007-07-11 17:01:13 +00003196
John McCall60d7b3a2010-08-24 06:29:42 +00003197ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003198Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003199 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003200 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003201 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003202 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003203 case tok::plusplus: Opc = UO_PostInc; break;
3204 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003205 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003206
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003207 // Since this might is a postfix expression, get rid of ParenListExprs.
3208 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3209 if (Result.isInvalid()) return ExprError();
3210 Input = Result.take();
3211
John McCall9ae2f072010-08-23 23:25:46 +00003212 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003213}
3214
John McCall1503f0d2012-07-31 05:14:30 +00003215/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3216///
3217/// \return true on error
3218static bool checkArithmeticOnObjCPointer(Sema &S,
3219 SourceLocation opLoc,
3220 Expr *op) {
3221 assert(op->getType()->isObjCObjectPointerType());
3222 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3223 return false;
3224
3225 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3226 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3227 << op->getSourceRange();
3228 return true;
3229}
3230
John McCall60d7b3a2010-08-24 06:29:42 +00003231ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003232Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3233 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003234 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003235 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003236 if (Result.isInvalid()) return ExprError();
3237 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003238
John McCall9ae2f072010-08-23 23:25:46 +00003239 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003240
David Blaikie4e4d0842012-03-11 07:00:24 +00003241 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003242 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003243 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003244 Context.DependentTy,
3245 VK_LValue, OK_Ordinary,
3246 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003247 }
3248
David Blaikie4e4d0842012-03-11 07:00:24 +00003249 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003250 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003251 LHSExp->getType()->isEnumeralType() ||
3252 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003253 RHSExp->getType()->isEnumeralType()) &&
3254 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003255 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003256 }
3257
John McCall9ae2f072010-08-23 23:25:46 +00003258 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003259}
3260
John McCall60d7b3a2010-08-24 06:29:42 +00003261ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003262Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003263 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003264 Expr *LHSExp = Base;
3265 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003266
Chris Lattner12d9ff62007-07-16 00:14:47 +00003267 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003268 if (!LHSExp->getType()->getAs<VectorType>()) {
3269 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3270 if (Result.isInvalid())
3271 return ExprError();
3272 LHSExp = Result.take();
3273 }
3274 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3275 if (Result.isInvalid())
3276 return ExprError();
3277 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003278
Chris Lattner12d9ff62007-07-16 00:14:47 +00003279 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003280 ExprValueKind VK = VK_LValue;
3281 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003282
Reid Spencer5f016e22007-07-11 17:01:13 +00003283 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003284 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003285 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003286 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003287 Expr *BaseExpr, *IndexExpr;
3288 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003289 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3290 BaseExpr = LHSExp;
3291 IndexExpr = RHSExp;
3292 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003293 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003294 BaseExpr = LHSExp;
3295 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003296 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003297 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003298 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003299 BaseExpr = LHSExp;
3300 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003301
3302 // Use custom logic if this should be the pseudo-object subscript
3303 // expression.
3304 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3305 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3306
Steve Naroff14108da2009-07-10 23:34:53 +00003307 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003308 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3309 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3310 << ResultType << BaseExpr->getSourceRange();
3311 return ExprError();
3312 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003313 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3314 // Handle the uncommon case of "123[Ptr]".
3315 BaseExpr = RHSExp;
3316 IndexExpr = LHSExp;
3317 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003318 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003319 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003320 // Handle the uncommon case of "123[Ptr]".
3321 BaseExpr = RHSExp;
3322 IndexExpr = LHSExp;
3323 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003324 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3325 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3326 << ResultType << BaseExpr->getSourceRange();
3327 return ExprError();
3328 }
John McCall183700f2009-09-21 23:43:11 +00003329 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003330 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003331 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003332 VK = LHSExp->getValueKind();
3333 if (VK != VK_RValue)
3334 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003335
Chris Lattner12d9ff62007-07-16 00:14:47 +00003336 // FIXME: need to deal with const...
3337 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003338 } else if (LHSTy->isArrayType()) {
3339 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003340 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003341 // wasn't promoted because of the C90 rule that doesn't
3342 // allow promoting non-lvalue arrays. Warn, then
3343 // force the promotion here.
3344 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3345 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003346 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3347 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003348 LHSTy = LHSExp->getType();
3349
3350 BaseExpr = LHSExp;
3351 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003353 } else if (RHSTy->isArrayType()) {
3354 // Same as previous, except for 123[f().a] case
3355 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3356 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003357 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3358 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003359 RHSTy = RHSExp->getType();
3360
3361 BaseExpr = RHSExp;
3362 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003363 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003364 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003365 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3366 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003367 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003368 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003369 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003370 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3371 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003372
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003373 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003374 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3375 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003376 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3377
Douglas Gregore7450f52009-03-24 19:52:54 +00003378 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003379 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3380 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003381 // incomplete types are not object types.
3382 if (ResultType->isFunctionType()) {
3383 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3384 << ResultType << BaseExpr->getSourceRange();
3385 return ExprError();
3386 }
Mike Stump1eb44332009-09-09 15:08:12 +00003387
David Blaikie4e4d0842012-03-11 07:00:24 +00003388 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003389 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003390 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3391 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003392
3393 // C forbids expressions of unqualified void type from being l-values.
3394 // See IsCForbiddenLValueType.
3395 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003396 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003397 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003398 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003399 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003400
John McCall09431682010-11-18 19:01:18 +00003401 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003402 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003403
Mike Stumpeed9cac2009-02-19 03:04:26 +00003404 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003405 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003406}
3407
John McCall60d7b3a2010-08-24 06:29:42 +00003408ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003409 FunctionDecl *FD,
3410 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003411 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003412 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003413 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003414 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003415 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003416 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003417 return ExprError();
3418 }
3419
3420 if (Param->hasUninstantiatedDefaultArg()) {
3421 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003422
Richard Smithadb1d4c2012-07-22 23:45:10 +00003423 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3424 Param);
3425
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003426 // Instantiate the expression.
3427 MultiLevelTemplateArgumentList ArgList
3428 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003429
Nico Weber08e41a62010-11-29 18:19:25 +00003430 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003431 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003432 InstantiatingTemplate Inst(*this, CallLoc, Param,
3433 ArrayRef<TemplateArgument>(Innermost.first,
3434 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003435 if (Inst)
3436 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003437
Nico Weber08e41a62010-11-29 18:19:25 +00003438 ExprResult Result;
3439 {
3440 // C++ [dcl.fct.default]p5:
3441 // The names in the [default argument] expression are bound, and
3442 // the semantic constraints are checked, at the point where the
3443 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003444 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003445 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003446 Result = SubstExpr(UninstExpr, ArgList);
3447 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003448 if (Result.isInvalid())
3449 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003451 // Check the expression as an initializer for the parameter.
3452 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003453 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003454 InitializationKind Kind
3455 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003456 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003457 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003458
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003459 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003460 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003461 if (Result.isInvalid())
3462 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003463
David Blaikiec1c07252012-04-30 18:21:31 +00003464 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003465 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003466 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003467 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003468 }
3469
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003470 // If the default expression creates temporaries, we need to
3471 // push them to the current stack of expression temporaries so they'll
3472 // be properly destroyed.
3473 // FIXME: We should really be rebuilding the default argument with new
3474 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003475 // We don't need to do that with block decls, though, because
3476 // blocks in default argument expression can never capture anything.
3477 if (isa<ExprWithCleanups>(Param->getInit())) {
3478 // Set the "needs cleanups" bit regardless of whether there are
3479 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003480 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003481
3482 // Append all the objects to the cleanup list. Right now, this
3483 // should always be a no-op, because blocks in default argument
3484 // expressions should never be able to capture anything.
3485 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3486 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003487 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003488
3489 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003490 // Just mark all of the declarations in this potentially-evaluated expression
3491 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003492 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3493 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003494 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003495}
3496
Richard Smith831421f2012-06-25 20:30:08 +00003497
3498Sema::VariadicCallType
3499Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3500 Expr *Fn) {
3501 if (Proto && Proto->isVariadic()) {
3502 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3503 return VariadicConstructor;
3504 else if (Fn && Fn->getType()->isBlockPointerType())
3505 return VariadicBlock;
3506 else if (FDecl) {
3507 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3508 if (Method->isInstance())
3509 return VariadicMethod;
3510 }
3511 return VariadicFunction;
3512 }
3513 return VariadicDoesNotApply;
3514}
3515
Douglas Gregor88a35142008-12-22 05:46:06 +00003516/// ConvertArgumentsForCall - Converts the arguments specified in
3517/// Args/NumArgs to the parameter types of the function FDecl with
3518/// function prototype Proto. Call is the call expression itself, and
3519/// Fn is the function expression. For a C++ member function, this
3520/// routine does not attempt to convert the object argument. Returns
3521/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003522bool
3523Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003524 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003525 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003526 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003527 SourceLocation RParenLoc,
3528 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003529 // Bail out early if calling a builtin with custom typechecking.
3530 // We don't need to do this in the
3531 if (FDecl)
3532 if (unsigned ID = FDecl->getBuiltinID())
3533 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3534 return false;
3535
Mike Stumpeed9cac2009-02-19 03:04:26 +00003536 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003537 // assignment, to the types of the corresponding parameter, ...
3538 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003539 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003540 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003541 unsigned FnKind = Fn->getType()->isBlockPointerType()
3542 ? 1 /* block */
3543 : (IsExecConfig ? 3 /* kernel function (exec config) */
3544 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003545
Douglas Gregor88a35142008-12-22 05:46:06 +00003546 // If too few arguments are available (and we don't have default
3547 // arguments for the remaining parameters), don't make the call.
3548 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003549 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003550 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3551 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3552 ? diag::err_typecheck_call_too_few_args_one
3553 : diag::err_typecheck_call_too_few_args_at_least_one)
3554 << FnKind
3555 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3556 else
3557 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3558 ? diag::err_typecheck_call_too_few_args
3559 : diag::err_typecheck_call_too_few_args_at_least)
3560 << FnKind
3561 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003562
3563 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003564 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003565 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3566 << FDecl;
3567
3568 return true;
3569 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003570 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003571 }
3572
3573 // If too many are passed and not variadic, error on the extras and drop
3574 // them.
3575 if (NumArgs > NumArgsInProto) {
3576 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003577 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3578 Diag(Args[NumArgsInProto]->getLocStart(),
3579 MinArgs == NumArgsInProto
3580 ? diag::err_typecheck_call_too_many_args_one
3581 : diag::err_typecheck_call_too_many_args_at_most_one)
3582 << FnKind
3583 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3584 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3585 Args[NumArgs-1]->getLocEnd());
3586 else
3587 Diag(Args[NumArgsInProto]->getLocStart(),
3588 MinArgs == NumArgsInProto
3589 ? diag::err_typecheck_call_too_many_args
3590 : diag::err_typecheck_call_too_many_args_at_most)
3591 << FnKind
3592 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3593 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3594 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003595
3596 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003597 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003598 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3599 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003600
Douglas Gregor88a35142008-12-22 05:46:06 +00003601 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003602 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003603 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003604 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003605 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003606 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003607 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3608
Daniel Dunbar96a00142012-03-09 18:35:03 +00003609 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003610 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003611 if (Invalid)
3612 return true;
3613 unsigned TotalNumArgs = AllArgs.size();
3614 for (unsigned i = 0; i < TotalNumArgs; ++i)
3615 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003616
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003617 return false;
3618}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003619
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003620bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3621 FunctionDecl *FDecl,
3622 const FunctionProtoType *Proto,
3623 unsigned FirstProtoArg,
3624 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003625 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003626 VariadicCallType CallType,
3627 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003628 unsigned NumArgsInProto = Proto->getNumArgs();
3629 unsigned NumArgsToCheck = NumArgs;
3630 bool Invalid = false;
3631 if (NumArgs != NumArgsInProto)
3632 // Use default arguments for missing arguments
3633 NumArgsToCheck = NumArgsInProto;
3634 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003635 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003636 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003637 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003638
Douglas Gregor88a35142008-12-22 05:46:06 +00003639 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003640 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003641 if (ArgIx < NumArgs) {
3642 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003643
Daniel Dunbar96a00142012-03-09 18:35:03 +00003644 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003645 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003646 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003647 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003648
Douglas Gregora188ff22009-12-22 16:09:06 +00003649 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003650 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003651 if (FDecl && i < FDecl->getNumParams())
3652 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003653
John McCall5acb0c92011-10-17 18:40:02 +00003654 // Strip the unbridged-cast placeholder expression off, if applicable.
3655 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3656 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3657 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3658 Arg = stripARCUnbridgedCast(Arg);
3659
Douglas Gregora188ff22009-12-22 16:09:06 +00003660 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003661 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003662 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3663 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003664 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003665 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003666 Owned(Arg),
3667 /*TopLevelOfInitList=*/false,
3668 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003669 if (ArgE.isInvalid())
3670 return true;
3671
3672 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003673 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003674 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003675
John McCall60d7b3a2010-08-24 06:29:42 +00003676 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003677 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003678 if (ArgExpr.isInvalid())
3679 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003680
Anders Carlsson56c5e332009-08-25 03:49:14 +00003681 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003682 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003683
3684 // Check for array bounds violations for each argument to the call. This
3685 // check only triggers warnings when the argument isn't a more complex Expr
3686 // with its own checking, such as a BinaryOperator.
3687 CheckArrayAccess(Arg);
3688
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003689 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3690 CheckStaticArrayArgument(CallLoc, Param, Arg);
3691
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003692 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003693 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003694
Douglas Gregor88a35142008-12-22 05:46:06 +00003695 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003696 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003697 // Assume that extern "C" functions with variadic arguments that
3698 // return __unknown_anytype aren't *really* variadic.
3699 if (Proto->getResultType() == Context.UnknownAnyTy &&
3700 FDecl && FDecl->isExternC()) {
3701 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3702 ExprResult arg;
3703 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3704 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3705 else
3706 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3707 Invalid |= arg.isInvalid();
3708 AllArgs.push_back(arg.take());
3709 }
3710
3711 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3712 } else {
3713 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003714 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3715 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003716 Invalid |= Arg.isInvalid();
3717 AllArgs.push_back(Arg.take());
3718 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003719 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003720
3721 // Check for array bounds violations.
3722 for (unsigned i = ArgIx; i != NumArgs; ++i)
3723 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003724 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003725 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003726}
3727
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003728static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3729 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3730 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3731 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3732 << ATL->getLocalSourceRange();
3733}
3734
3735/// CheckStaticArrayArgument - If the given argument corresponds to a static
3736/// array parameter, check that it is non-null, and that if it is formed by
3737/// array-to-pointer decay, the underlying array is sufficiently large.
3738///
3739/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3740/// array type derivation, then for each call to the function, the value of the
3741/// corresponding actual argument shall provide access to the first element of
3742/// an array with at least as many elements as specified by the size expression.
3743void
3744Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3745 ParmVarDecl *Param,
3746 const Expr *ArgExpr) {
3747 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003748 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003749 return;
3750
3751 QualType OrigTy = Param->getOriginalType();
3752
3753 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3754 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3755 return;
3756
3757 if (ArgExpr->isNullPointerConstant(Context,
3758 Expr::NPC_NeverValueDependent)) {
3759 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3760 DiagnoseCalleeStaticArrayParam(*this, Param);
3761 return;
3762 }
3763
3764 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3765 if (!CAT)
3766 return;
3767
3768 const ConstantArrayType *ArgCAT =
3769 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3770 if (!ArgCAT)
3771 return;
3772
3773 if (ArgCAT->getSize().ult(CAT->getSize())) {
3774 Diag(CallLoc, diag::warn_static_array_too_small)
3775 << ArgExpr->getSourceRange()
3776 << (unsigned) ArgCAT->getSize().getZExtValue()
3777 << (unsigned) CAT->getSize().getZExtValue();
3778 DiagnoseCalleeStaticArrayParam(*this, Param);
3779 }
3780}
3781
John McCall755d8492011-04-12 00:42:48 +00003782/// Given a function expression of unknown-any type, try to rebuild it
3783/// to have a function type.
3784static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3785
Steve Narofff69936d2007-09-16 03:34:24 +00003786/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003787/// This provides the location of the left/right parens and a list of comma
3788/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003789ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003790Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003791 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003792 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003793 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003794 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003795 if (Result.isInvalid()) return ExprError();
3796 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003797
David Blaikie4e4d0842012-03-11 07:00:24 +00003798 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003799 // If this is a pseudo-destructor expression, build the call immediately.
3800 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003801 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003802 // Pseudo-destructor calls should not have any arguments.
3803 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003804 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003805 SourceRange(ArgExprs[0]->getLocStart(),
3806 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003809 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3810 Context.VoidTy, VK_RValue,
3811 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003812 }
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Douglas Gregor17330012009-02-04 15:01:18 +00003814 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003815 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003816 // FIXME: Will need to cache the results of name lookup (including ADL) in
3817 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003818 bool Dependent = false;
3819 if (Fn->isTypeDependent())
3820 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003821 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003822 Dependent = true;
3823
Peter Collingbournee08ce652011-02-09 21:07:24 +00003824 if (Dependent) {
3825 if (ExecConfig) {
3826 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003827 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003828 Context.DependentTy, VK_RValue, RParenLoc));
3829 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003830 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003831 Context.DependentTy, VK_RValue,
3832 RParenLoc));
3833 }
3834 }
Douglas Gregor17330012009-02-04 15:01:18 +00003835
3836 // Determine whether this is a call to an object (C++ [over.call.object]).
3837 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003838 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3839 ArgExprs.data(),
3840 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003841
John McCall755d8492011-04-12 00:42:48 +00003842 if (Fn->getType() == Context.UnknownAnyTy) {
3843 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3844 if (result.isInvalid()) return ExprError();
3845 Fn = result.take();
3846 }
3847
John McCall864c0412011-04-26 20:42:42 +00003848 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003849 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3850 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003851 }
John McCall864c0412011-04-26 20:42:42 +00003852 }
John McCall129e2df2009-11-30 22:42:35 +00003853
John McCall864c0412011-04-26 20:42:42 +00003854 // Check for overloaded calls. This can happen even in C due to extensions.
3855 if (Fn->getType() == Context.OverloadTy) {
3856 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3857
Douglas Gregoree697e62011-10-13 18:10:35 +00003858 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003859 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003860 OverloadExpr *ovl = find.Expression;
3861 if (isa<UnresolvedLookupExpr>(ovl)) {
3862 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003863 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3864 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003865 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003866 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3867 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003868 }
3869 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003870 }
3871
Douglas Gregorfa047642009-02-04 00:32:51 +00003872 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003873 if (Fn->getType() == Context.UnknownAnyTy) {
3874 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3875 if (result.isInvalid()) return ExprError();
3876 Fn = result.take();
3877 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003878
Eli Friedmanefa42f72009-12-26 03:35:45 +00003879 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003880
John McCall3b4294e2009-12-16 12:17:52 +00003881 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003882 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3883 if (UnOp->getOpcode() == UO_AddrOf)
3884 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3885
John McCall3b4294e2009-12-16 12:17:52 +00003886 if (isa<DeclRefExpr>(NakedFn))
3887 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003888 else if (isa<MemberExpr>(NakedFn))
3889 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003890
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003891 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3892 ArgExprs.size(), RParenLoc, ExecConfig,
3893 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003894}
3895
3896ExprResult
3897Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003898 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003899 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3900 if (!ConfigDecl)
3901 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3902 << "cudaConfigureCall");
3903 QualType ConfigQTy = ConfigDecl->getType();
3904
3905 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003906 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003907 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003908
Peter Collingbourne1f240762011-10-02 23:49:29 +00003909 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3910 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003911}
3912
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003913/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3914///
3915/// __builtin_astype( value, dst type )
3916///
Richard Trieuccd891a2011-09-09 01:45:06 +00003917ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003918 SourceLocation BuiltinLoc,
3919 SourceLocation RParenLoc) {
3920 ExprValueKind VK = VK_RValue;
3921 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003922 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3923 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003924 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3925 return ExprError(Diag(BuiltinLoc,
3926 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003927 << DstTy
3928 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003929 << E->getSourceRange());
3930 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003931 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003932}
3933
John McCall3b4294e2009-12-16 12:17:52 +00003934/// BuildResolvedCallExpr - Build a call to a resolved expression,
3935/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003936/// unary-convert to an expression of function-pointer or
3937/// block-pointer type.
3938///
3939/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003940ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003941Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3942 SourceLocation LParenLoc,
3943 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003944 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003945 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003946 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003947 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00003948
Chris Lattner04421082008-04-08 04:40:51 +00003949 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003950 // We special-case function promotion here because we only allow promoting
3951 // builtin functions to function pointers in the callee of a call.
3952 ExprResult Result;
3953 if (BuiltinID &&
3954 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3955 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3956 CK_BuiltinFnToFnPtr).take();
3957 } else {
3958 Result = UsualUnaryConversions(Fn);
3959 }
John Wiegley429bb272011-04-08 18:41:53 +00003960 if (Result.isInvalid())
3961 return ExprError();
3962 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003963
Chris Lattner925e60d2007-12-28 05:29:59 +00003964 // Make the call expr early, before semantic checks. This guarantees cleanup
3965 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003966 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003967 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003968 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3969 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003970 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00003971 Context.BoolTy,
3972 VK_RValue,
3973 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003974 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003975 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003976 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00003977 Context.BoolTy,
3978 VK_RValue,
3979 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003980
John McCall8e10f3b2011-02-26 05:39:39 +00003981 // Bail out early if calling a builtin with custom typechecking.
3982 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3983 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3984
John McCall1de4d4e2011-04-07 08:22:57 +00003985 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003986 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003987 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003988 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3989 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003990 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003991 if (FuncT == 0)
3992 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3993 << Fn->getType() << Fn->getSourceRange());
3994 } else if (const BlockPointerType *BPT =
3995 Fn->getType()->getAs<BlockPointerType>()) {
3996 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3997 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003998 // Handle calls to expressions of unknown-any type.
3999 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004000 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004001 if (rewrite.isInvalid()) return ExprError();
4002 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004003 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004004 goto retry;
4005 }
4006
Sebastian Redl0eb23302009-01-19 00:08:26 +00004007 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4008 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004009 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004010
David Blaikie4e4d0842012-03-11 07:00:24 +00004011 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004012 if (Config) {
4013 // CUDA: Kernel calls must be to global functions
4014 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4015 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4016 << FDecl->getName() << Fn->getSourceRange());
4017
4018 // CUDA: Kernel function must have 'void' return type
4019 if (!FuncT->getResultType()->isVoidType())
4020 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4021 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004022 } else {
4023 // CUDA: Calls to global functions must be configured
4024 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4025 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4026 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004027 }
4028 }
4029
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004030 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004031 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004032 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004033 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004034 return ExprError();
4035
Chris Lattner925e60d2007-12-28 05:29:59 +00004036 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004037 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004038 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004039
Richard Smith831421f2012-06-25 20:30:08 +00004040 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4041 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004042 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004043 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004044 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004045 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004046 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004047
Douglas Gregor74734d52009-04-02 15:37:10 +00004048 if (FDecl) {
4049 // Check if we have too few/too many template arguments, based
4050 // on our knowledge of the function definition.
4051 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004052 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004053 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004054 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004055 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4056 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004057 }
Douglas Gregor46542412010-10-25 20:39:23 +00004058
4059 // If the function we're calling isn't a function prototype, but we have
4060 // a function prototype from a prior declaratiom, use that prototype.
4061 if (!FDecl->hasPrototype())
4062 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004063 }
4064
Steve Naroffb291ab62007-08-28 23:30:39 +00004065 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004066 for (unsigned i = 0; i != NumArgs; i++) {
4067 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004068
4069 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004070 InitializedEntity Entity
4071 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004072 Proto->getArgType(i),
4073 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004074 ExprResult ArgE = PerformCopyInitialization(Entity,
4075 SourceLocation(),
4076 Owned(Arg));
4077 if (ArgE.isInvalid())
4078 return true;
4079
4080 Arg = ArgE.takeAs<Expr>();
4081
4082 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004083 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4084
4085 if (ArgE.isInvalid())
4086 return true;
4087
4088 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004089 }
4090
Daniel Dunbar96a00142012-03-09 18:35:03 +00004091 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004092 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004093 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004094 return ExprError();
4095
Chris Lattner925e60d2007-12-28 05:29:59 +00004096 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004098 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004099
Douglas Gregor88a35142008-12-22 05:46:06 +00004100 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4101 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004102 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4103 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004104
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004105 // Check for sentinels
4106 if (NDecl)
4107 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Chris Lattner59907c42007-08-10 20:18:51 +00004109 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004110 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004111 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004112 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004113
John McCall8e10f3b2011-02-26 05:39:39 +00004114 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004115 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004116 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004117 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004118 return ExprError();
4119 }
Chris Lattner59907c42007-08-10 20:18:51 +00004120
John McCall9ae2f072010-08-23 23:25:46 +00004121 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004122}
4123
John McCall60d7b3a2010-08-24 06:29:42 +00004124ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004125Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004126 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004127 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004128 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004129 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004130
4131 TypeSourceInfo *TInfo;
4132 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4133 if (!TInfo)
4134 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4135
John McCall9ae2f072010-08-23 23:25:46 +00004136 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004137}
4138
John McCall60d7b3a2010-08-24 06:29:42 +00004139ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004140Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004141 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004142 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004143
Eli Friedman6223c222008-05-20 05:22:08 +00004144 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004145 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004146 diag::err_illegal_decl_array_incomplete_type,
4147 SourceRange(LParenLoc,
4148 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004149 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004150 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004151 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004152 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004153 } else if (!literalType->isDependentType() &&
4154 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004155 diag::err_typecheck_decl_incomplete_type,
4156 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004157 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004158
Douglas Gregor99a2e602009-12-16 01:38:02 +00004159 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004160 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004161 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004162 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004163 SourceRange(LParenLoc, RParenLoc),
4164 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004165 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004166 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4167 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004168 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004169 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004170 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004171
Chris Lattner371f2582008-12-04 23:50:19 +00004172 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004173 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004174 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004175 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004176 }
Eli Friedman08544622009-12-22 02:35:53 +00004177
John McCallf89e55a2010-11-18 06:31:45 +00004178 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004179 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004180
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004181 return MaybeBindToTemporary(
4182 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004183 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004184}
4185
John McCall60d7b3a2010-08-24 06:29:42 +00004186ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004187Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004188 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004189 // Immediately handle non-overload placeholders. Overloads can be
4190 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004191 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4192 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4193 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004194
4195 // Ignore failures; dropping the entire initializer list because
4196 // of one failure would be terrible for indexing/etc.
4197 if (result.isInvalid()) continue;
4198
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004199 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004200 }
4201 }
4202
Steve Naroff08d92e42007-09-15 18:49:24 +00004203 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004204 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004205
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004206 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4207 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004208 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004209 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004210}
4211
John McCalldc05b112011-09-10 01:16:55 +00004212/// Do an explicit extend of the given block pointer if we're in ARC.
4213static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4214 assert(E.get()->getType()->isBlockPointerType());
4215 assert(E.get()->isRValue());
4216
4217 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004218 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004219
4220 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004221 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004222 /*base path*/ 0, VK_RValue);
4223 S.ExprNeedsCleanups = true;
4224}
4225
4226/// Prepare a conversion of the given expression to an ObjC object
4227/// pointer type.
4228CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4229 QualType type = E.get()->getType();
4230 if (type->isObjCObjectPointerType()) {
4231 return CK_BitCast;
4232 } else if (type->isBlockPointerType()) {
4233 maybeExtendBlockObject(*this, E);
4234 return CK_BlockPointerToObjCPointerCast;
4235 } else {
4236 assert(type->isPointerType());
4237 return CK_CPointerToObjCPointerCast;
4238 }
4239}
4240
John McCallf3ea8cf2010-11-14 08:17:51 +00004241/// Prepares for a scalar cast, performing all the necessary stages
4242/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004243CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004244 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4245 // Also, callers should have filtered out the invalid cases with
4246 // pointers. Everything else should be possible.
4247
John Wiegley429bb272011-04-08 18:41:53 +00004248 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004249 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004250 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004251
John McCall1d9b3b22011-09-09 05:25:32 +00004252 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004253 case Type::STK_MemberPointer:
4254 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004255
John McCall1d9b3b22011-09-09 05:25:32 +00004256 case Type::STK_CPointer:
4257 case Type::STK_BlockPointer:
4258 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004259 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004260 case Type::STK_CPointer:
4261 return CK_BitCast;
4262 case Type::STK_BlockPointer:
4263 return (SrcKind == Type::STK_BlockPointer
4264 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4265 case Type::STK_ObjCObjectPointer:
4266 if (SrcKind == Type::STK_ObjCObjectPointer)
4267 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004268 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004269 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004270 maybeExtendBlockObject(*this, Src);
4271 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004272 case Type::STK_Bool:
4273 return CK_PointerToBoolean;
4274 case Type::STK_Integral:
4275 return CK_PointerToIntegral;
4276 case Type::STK_Floating:
4277 case Type::STK_FloatingComplex:
4278 case Type::STK_IntegralComplex:
4279 case Type::STK_MemberPointer:
4280 llvm_unreachable("illegal cast from pointer");
4281 }
David Blaikie7530c032012-01-17 06:56:22 +00004282 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004283
John McCalldaa8e4e2010-11-15 09:13:47 +00004284 case Type::STK_Bool: // casting from bool is like casting from an integer
4285 case Type::STK_Integral:
4286 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004287 case Type::STK_CPointer:
4288 case Type::STK_ObjCObjectPointer:
4289 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004290 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004291 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004292 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004293 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004294 case Type::STK_Bool:
4295 return CK_IntegralToBoolean;
4296 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004297 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004298 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004299 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004300 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004301 Src = ImpCastExprToType(Src.take(),
4302 DestTy->castAs<ComplexType>()->getElementType(),
4303 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004304 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004305 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004306 Src = ImpCastExprToType(Src.take(),
4307 DestTy->castAs<ComplexType>()->getElementType(),
4308 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004309 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004310 case Type::STK_MemberPointer:
4311 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004312 }
David Blaikie7530c032012-01-17 06:56:22 +00004313 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004314
John McCalldaa8e4e2010-11-15 09:13:47 +00004315 case Type::STK_Floating:
4316 switch (DestTy->getScalarTypeKind()) {
4317 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004318 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004319 case Type::STK_Bool:
4320 return CK_FloatingToBoolean;
4321 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004322 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004323 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004324 Src = ImpCastExprToType(Src.take(),
4325 DestTy->castAs<ComplexType>()->getElementType(),
4326 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004327 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004328 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004329 Src = ImpCastExprToType(Src.take(),
4330 DestTy->castAs<ComplexType>()->getElementType(),
4331 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004332 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004333 case Type::STK_CPointer:
4334 case Type::STK_ObjCObjectPointer:
4335 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004336 llvm_unreachable("valid float->pointer cast?");
4337 case Type::STK_MemberPointer:
4338 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004339 }
David Blaikie7530c032012-01-17 06:56:22 +00004340 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004341
John McCalldaa8e4e2010-11-15 09:13:47 +00004342 case Type::STK_FloatingComplex:
4343 switch (DestTy->getScalarTypeKind()) {
4344 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004345 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004346 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004347 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004348 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004349 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4350 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004351 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004352 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004353 return CK_FloatingCast;
4354 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004355 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004356 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004357 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004358 Src = ImpCastExprToType(Src.take(),
4359 SrcTy->castAs<ComplexType>()->getElementType(),
4360 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004361 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004362 case Type::STK_CPointer:
4363 case Type::STK_ObjCObjectPointer:
4364 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004365 llvm_unreachable("valid complex float->pointer cast?");
4366 case Type::STK_MemberPointer:
4367 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004368 }
David Blaikie7530c032012-01-17 06:56:22 +00004369 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004370
John McCalldaa8e4e2010-11-15 09:13:47 +00004371 case Type::STK_IntegralComplex:
4372 switch (DestTy->getScalarTypeKind()) {
4373 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004374 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004375 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004376 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004377 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004378 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4379 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004380 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004381 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004382 return CK_IntegralCast;
4383 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004384 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004385 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004386 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004387 Src = ImpCastExprToType(Src.take(),
4388 SrcTy->castAs<ComplexType>()->getElementType(),
4389 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004390 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004391 case Type::STK_CPointer:
4392 case Type::STK_ObjCObjectPointer:
4393 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004394 llvm_unreachable("valid complex int->pointer cast?");
4395 case Type::STK_MemberPointer:
4396 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004397 }
David Blaikie7530c032012-01-17 06:56:22 +00004398 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004399 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004400
John McCallf3ea8cf2010-11-14 08:17:51 +00004401 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004402}
4403
Anders Carlssonc3516322009-10-16 02:48:28 +00004404bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004405 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004406 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004407
Anders Carlssona64db8f2007-11-27 05:51:55 +00004408 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004409 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004410 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004411 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004412 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004413 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004414 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004415 } else
4416 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004417 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004418 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004419
John McCall2de56d12010-08-25 11:45:40 +00004420 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004421 return false;
4422}
4423
John Wiegley429bb272011-04-08 18:41:53 +00004424ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4425 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004426 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004427
Anders Carlsson16a89042009-10-16 05:23:41 +00004428 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004429
Nate Begeman9b10da62009-06-27 22:05:55 +00004430 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4431 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004432 // In OpenCL, casts between vectors of different types are not allowed.
4433 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004434 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004435 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004436 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004437 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004438 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004439 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004440 return ExprError();
4441 }
John McCall2de56d12010-08-25 11:45:40 +00004442 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004443 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004444 }
4445
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004446 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004447 // conversion will take place first from scalar to elt type, and then
4448 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004449 if (SrcTy->isPointerType())
4450 return Diag(R.getBegin(),
4451 diag::err_invalid_conversion_between_vector_and_scalar)
4452 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004453
4454 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004455 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004456 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004457 if (CastExprRes.isInvalid())
4458 return ExprError();
4459 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004460
John McCall2de56d12010-08-25 11:45:40 +00004461 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004462 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004463}
4464
John McCall60d7b3a2010-08-24 06:29:42 +00004465ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004466Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4467 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004468 SourceLocation RParenLoc, Expr *CastExpr) {
4469 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004470 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004471
Richard Trieuccd891a2011-09-09 01:45:06 +00004472 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004473 if (D.isInvalidType())
4474 return ExprError();
4475
David Blaikie4e4d0842012-03-11 07:00:24 +00004476 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004477 // Check that there are no default arguments (C++ only).
4478 CheckExtraCXXDefaultArguments(D);
4479 }
4480
John McCalle82247a2011-10-01 05:17:03 +00004481 checkUnusedDeclAttributes(D);
4482
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004483 QualType castType = castTInfo->getType();
4484 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004485
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004486 bool isVectorLiteral = false;
4487
4488 // Check for an altivec or OpenCL literal,
4489 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004490 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4491 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004492 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004493 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004494 if (PLE && PLE->getNumExprs() == 0) {
4495 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4496 return ExprError();
4497 }
4498 if (PE || PLE->getNumExprs() == 1) {
4499 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4500 if (!E->getType()->isVectorType())
4501 isVectorLiteral = true;
4502 }
4503 else
4504 isVectorLiteral = true;
4505 }
4506
4507 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4508 // then handle it as such.
4509 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004510 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004511
Nate Begeman2ef13e52009-08-10 23:49:36 +00004512 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004513 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4514 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004515 if (isa<ParenListExpr>(CastExpr)) {
4516 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004517 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004518 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004519 }
John McCallb042fdf2010-01-15 18:56:44 +00004520
Richard Trieuccd891a2011-09-09 01:45:06 +00004521 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004522}
4523
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004524ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4525 SourceLocation RParenLoc, Expr *E,
4526 TypeSourceInfo *TInfo) {
4527 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4528 "Expected paren or paren list expression");
4529
4530 Expr **exprs;
4531 unsigned numExprs;
4532 Expr *subExpr;
4533 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4534 exprs = PE->getExprs();
4535 numExprs = PE->getNumExprs();
4536 } else {
4537 subExpr = cast<ParenExpr>(E)->getSubExpr();
4538 exprs = &subExpr;
4539 numExprs = 1;
4540 }
4541
4542 QualType Ty = TInfo->getType();
4543 assert(Ty->isVectorType() && "Expected vector type");
4544
Chris Lattner5f9e2722011-07-23 10:55:15 +00004545 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004546 const VectorType *VTy = Ty->getAs<VectorType>();
4547 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4548
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004549 // '(...)' form of vector initialization in AltiVec: the number of
4550 // initializers must be one or must match the size of the vector.
4551 // If a single value is specified in the initializer then it will be
4552 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004553 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004554 // The number of initializers must be one or must match the size of the
4555 // vector. If a single value is specified in the initializer then it will
4556 // be replicated to all the components of the vector
4557 if (numExprs == 1) {
4558 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004559 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4560 if (Literal.isInvalid())
4561 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004562 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004563 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004564 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4565 }
4566 else if (numExprs < numElems) {
4567 Diag(E->getExprLoc(),
4568 diag::err_incorrect_number_of_vector_initializers);
4569 return ExprError();
4570 }
4571 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004572 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004573 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004574 else {
4575 // For OpenCL, when the number of initializers is a single value,
4576 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004577 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004578 VTy->getVectorKind() == VectorType::GenericVector &&
4579 numExprs == 1) {
4580 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004581 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4582 if (Literal.isInvalid())
4583 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004584 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004585 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004586 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4587 }
4588
Benjamin Kramer14c59822012-02-14 12:06:21 +00004589 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004590 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004591 // FIXME: This means that pretty-printing the final AST will produce curly
4592 // braces instead of the original commas.
4593 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004594 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004595 initE->setType(Ty);
4596 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4597}
4598
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004599/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4600/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004601ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004602Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4603 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004604 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004605 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004606
John McCall60d7b3a2010-08-24 06:29:42 +00004607 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Nate Begeman2ef13e52009-08-10 23:49:36 +00004609 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004610 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4611 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004612
John McCall9ae2f072010-08-23 23:25:46 +00004613 if (Result.isInvalid()) return ExprError();
4614
4615 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004616}
4617
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004618ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4619 SourceLocation R,
4620 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004621 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4622 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004623 return Owned(expr);
4624}
4625
Chandler Carruth82214a82011-02-18 23:54:50 +00004626/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004627/// constant and the other is not a pointer. Returns true if a diagnostic is
4628/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004629bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004630 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004631 Expr *NullExpr = LHSExpr;
4632 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004633 Expr::NullPointerConstantKind NullKind =
4634 NullExpr->isNullPointerConstant(Context,
4635 Expr::NPC_ValueDependentIsNotNull);
4636
4637 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004638 NullExpr = RHSExpr;
4639 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004640 NullKind =
4641 NullExpr->isNullPointerConstant(Context,
4642 Expr::NPC_ValueDependentIsNotNull);
4643 }
4644
4645 if (NullKind == Expr::NPCK_NotNull)
4646 return false;
4647
David Blaikie50800fc2012-08-08 17:33:31 +00004648 if (NullKind == Expr::NPCK_ZeroExpression)
4649 return false;
4650
4651 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004652 // In this case, check to make sure that we got here from a "NULL"
4653 // string in the source code.
4654 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004655 SourceLocation loc = NullExpr->getExprLoc();
4656 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004657 return false;
4658 }
4659
4660 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4661 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4662 << NonPointerExpr->getType() << DiagType
4663 << NonPointerExpr->getSourceRange();
4664 return true;
4665}
4666
Richard Trieu26f96072011-09-02 01:51:02 +00004667/// \brief Return false if the condition expression is valid, true otherwise.
4668static bool checkCondition(Sema &S, Expr *Cond) {
4669 QualType CondTy = Cond->getType();
4670
4671 // C99 6.5.15p2
4672 if (CondTy->isScalarType()) return false;
4673
4674 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004675 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004676 return false;
4677
4678 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004679 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004680 diag::err_typecheck_cond_expect_scalar :
4681 diag::err_typecheck_cond_expect_scalar_or_vector)
4682 << CondTy;
4683 return true;
4684}
4685
4686/// \brief Return false if the two expressions can be converted to a vector,
4687/// true otherwise
4688static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4689 ExprResult &RHS,
4690 QualType CondTy) {
4691 // Both operands should be of scalar type.
4692 if (!LHS.get()->getType()->isScalarType()) {
4693 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4694 << CondTy;
4695 return true;
4696 }
4697 if (!RHS.get()->getType()->isScalarType()) {
4698 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4699 << CondTy;
4700 return true;
4701 }
4702
4703 // Implicity convert these scalars to the type of the condition.
4704 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4705 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4706 return false;
4707}
4708
4709/// \brief Handle when one or both operands are void type.
4710static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4711 ExprResult &RHS) {
4712 Expr *LHSExpr = LHS.get();
4713 Expr *RHSExpr = RHS.get();
4714
4715 if (!LHSExpr->getType()->isVoidType())
4716 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4717 << RHSExpr->getSourceRange();
4718 if (!RHSExpr->getType()->isVoidType())
4719 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4720 << LHSExpr->getSourceRange();
4721 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4722 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4723 return S.Context.VoidTy;
4724}
4725
4726/// \brief Return false if the NullExpr can be promoted to PointerTy,
4727/// true otherwise.
4728static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4729 QualType PointerTy) {
4730 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4731 !NullExpr.get()->isNullPointerConstant(S.Context,
4732 Expr::NPC_ValueDependentIsNull))
4733 return true;
4734
4735 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4736 return false;
4737}
4738
4739/// \brief Checks compatibility between two pointers and return the resulting
4740/// type.
4741static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4742 ExprResult &RHS,
4743 SourceLocation Loc) {
4744 QualType LHSTy = LHS.get()->getType();
4745 QualType RHSTy = RHS.get()->getType();
4746
4747 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4748 // Two identical pointers types are always compatible.
4749 return LHSTy;
4750 }
4751
4752 QualType lhptee, rhptee;
4753
4754 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004755 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4756 lhptee = LHSBTy->getPointeeType();
4757 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004758 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004759 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4760 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004761 }
4762
Eli Friedmanae916a12012-04-05 22:30:04 +00004763 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4764 // differently qualified versions of compatible types, the result type is
4765 // a pointer to an appropriately qualified version of the composite
4766 // type.
4767
4768 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4769 // clause doesn't make sense for our extensions. E.g. address space 2 should
4770 // be incompatible with address space 3: they may live on different devices or
4771 // anything.
4772 Qualifiers lhQual = lhptee.getQualifiers();
4773 Qualifiers rhQual = rhptee.getQualifiers();
4774
4775 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4776 lhQual.removeCVRQualifiers();
4777 rhQual.removeCVRQualifiers();
4778
4779 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4780 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4781
4782 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4783
4784 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004785 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4786 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4787 << RHS.get()->getSourceRange();
4788 // In this situation, we assume void* type. No especially good
4789 // reason, but this is what gcc does, and we do have to pick
4790 // to get a consistent AST.
4791 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4792 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4793 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4794 return incompatTy;
4795 }
4796
4797 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004798 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4799 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004800
Eli Friedmanae916a12012-04-05 22:30:04 +00004801 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4802 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4803 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004804}
4805
4806/// \brief Return the resulting type when the operands are both block pointers.
4807static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4808 ExprResult &LHS,
4809 ExprResult &RHS,
4810 SourceLocation Loc) {
4811 QualType LHSTy = LHS.get()->getType();
4812 QualType RHSTy = RHS.get()->getType();
4813
4814 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4815 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4816 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4817 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4818 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4819 return destType;
4820 }
4821 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4822 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4823 << RHS.get()->getSourceRange();
4824 return QualType();
4825 }
4826
4827 // We have 2 block pointer types.
4828 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4829}
4830
4831/// \brief Return the resulting type when the operands are both pointers.
4832static QualType
4833checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4834 ExprResult &RHS,
4835 SourceLocation Loc) {
4836 // get the pointer types
4837 QualType LHSTy = LHS.get()->getType();
4838 QualType RHSTy = RHS.get()->getType();
4839
4840 // get the "pointed to" types
4841 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4842 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4843
4844 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4845 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4846 // Figure out necessary qualifiers (C99 6.5.15p6)
4847 QualType destPointee
4848 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4849 QualType destType = S.Context.getPointerType(destPointee);
4850 // Add qualifiers if necessary.
4851 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4852 // Promote to void*.
4853 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4854 return destType;
4855 }
4856 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4857 QualType destPointee
4858 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4859 QualType destType = S.Context.getPointerType(destPointee);
4860 // Add qualifiers if necessary.
4861 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4862 // Promote to void*.
4863 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4864 return destType;
4865 }
4866
4867 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4868}
4869
4870/// \brief Return false if the first expression is not an integer and the second
4871/// expression is not a pointer, true otherwise.
4872static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4873 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004874 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004875 if (!PointerExpr->getType()->isPointerType() ||
4876 !Int.get()->getType()->isIntegerType())
4877 return false;
4878
Richard Trieuccd891a2011-09-09 01:45:06 +00004879 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4880 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004881
4882 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4883 << Expr1->getType() << Expr2->getType()
4884 << Expr1->getSourceRange() << Expr2->getSourceRange();
4885 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4886 CK_IntegralToPointer);
4887 return true;
4888}
4889
Richard Trieu33fc7572011-09-06 20:06:39 +00004890/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4891/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004892/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004893QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4894 ExprResult &RHS, ExprValueKind &VK,
4895 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004896 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004897
Richard Trieu33fc7572011-09-06 20:06:39 +00004898 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4899 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004900 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004901
Richard Trieu33fc7572011-09-06 20:06:39 +00004902 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4903 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004904 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004905
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004906 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004907 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004908 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004909
4910 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004911 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004912
John Wiegley429bb272011-04-08 18:41:53 +00004913 Cond = UsualUnaryConversions(Cond.take());
4914 if (Cond.isInvalid())
4915 return QualType();
4916 LHS = UsualUnaryConversions(LHS.take());
4917 if (LHS.isInvalid())
4918 return QualType();
4919 RHS = UsualUnaryConversions(RHS.take());
4920 if (RHS.isInvalid())
4921 return QualType();
4922
4923 QualType CondTy = Cond.get()->getType();
4924 QualType LHSTy = LHS.get()->getType();
4925 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004926
Reid Spencer5f016e22007-07-11 17:01:13 +00004927 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004928 if (checkCondition(*this, Cond.get()))
4929 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004930
Chris Lattner70d67a92008-01-06 22:42:25 +00004931 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004932 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004933 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004934
Nate Begeman6155d732010-09-20 22:41:17 +00004935 // OpenCL: If the condition is a vector, and both operands are scalar,
4936 // attempt to implicity convert them to the vector type to act like the
4937 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004938 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004939 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004940 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004941
Chris Lattner70d67a92008-01-06 22:42:25 +00004942 // If both operands have arithmetic type, do the usual arithmetic conversions
4943 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004944 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4945 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004946 if (LHS.isInvalid() || RHS.isInvalid())
4947 return QualType();
4948 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004949 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004950
Chris Lattner70d67a92008-01-06 22:42:25 +00004951 // If both operands are the same structure or union type, the result is that
4952 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004953 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4954 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004955 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004956 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004957 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004958 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004959 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004960 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004961
Chris Lattner70d67a92008-01-06 22:42:25 +00004962 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004963 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004964 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004965 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004966 }
Richard Trieu26f96072011-09-02 01:51:02 +00004967
Steve Naroffb6d54e52008-01-08 01:11:38 +00004968 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4969 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004970 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4971 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004972
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004973 // All objective-c pointer type analysis is done here.
4974 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4975 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004976 if (LHS.isInvalid() || RHS.isInvalid())
4977 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004978 if (!compositeType.isNull())
4979 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004980
4981
Steve Naroff7154a772009-07-01 14:36:47 +00004982 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004983 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4984 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4985 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004986
Steve Naroff7154a772009-07-01 14:36:47 +00004987 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004988 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4989 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4990 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004991
John McCall404cd162010-11-13 01:35:44 +00004992 // GCC compatibility: soften pointer/integer mismatch. Note that
4993 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004994 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4995 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004996 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004997 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4998 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004999 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005000
Chandler Carruth82214a82011-02-18 23:54:50 +00005001 // Emit a better diagnostic if one of the expressions is a null pointer
5002 // constant and the other is not a pointer type. In this case, the user most
5003 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005004 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005005 return QualType();
5006
Chris Lattner70d67a92008-01-06 22:42:25 +00005007 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005008 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005009 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5010 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005011 return QualType();
5012}
5013
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005014/// FindCompositeObjCPointerType - Helper method to find composite type of
5015/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005016QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005017 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005018 QualType LHSTy = LHS.get()->getType();
5019 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005020
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005021 // Handle things like Class and struct objc_class*. Here we case the result
5022 // to the pseudo-builtin, because that will be implicitly cast back to the
5023 // redefinition type if an attempt is made to access its fields.
5024 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005025 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005026 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005027 return LHSTy;
5028 }
5029 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005030 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005031 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005032 return RHSTy;
5033 }
5034 // And the same for struct objc_object* / id
5035 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005036 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005037 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005038 return LHSTy;
5039 }
5040 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005041 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005042 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005043 return RHSTy;
5044 }
5045 // And the same for struct objc_selector* / SEL
5046 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005047 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005048 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005049 return LHSTy;
5050 }
5051 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005052 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005053 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005054 return RHSTy;
5055 }
5056 // Check constraints for Objective-C object pointers types.
5057 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005058
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005059 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5060 // Two identical object pointer types are always compatible.
5061 return LHSTy;
5062 }
John McCall1d9b3b22011-09-09 05:25:32 +00005063 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5064 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005065 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005066
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005067 // If both operands are interfaces and either operand can be
5068 // assigned to the other, use that type as the composite
5069 // type. This allows
5070 // xxx ? (A*) a : (B*) b
5071 // where B is a subclass of A.
5072 //
5073 // Additionally, as for assignment, if either type is 'id'
5074 // allow silent coercion. Finally, if the types are
5075 // incompatible then make sure to use 'id' as the composite
5076 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005077
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005078 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5079 // It could return the composite type.
5080 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5081 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5082 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5083 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5084 } else if ((LHSTy->isObjCQualifiedIdType() ||
5085 RHSTy->isObjCQualifiedIdType()) &&
5086 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5087 // Need to handle "id<xx>" explicitly.
5088 // GCC allows qualified id and any Objective-C type to devolve to
5089 // id. Currently localizing to here until clear this should be
5090 // part of ObjCQualifiedIdTypesAreCompatible.
5091 compositeType = Context.getObjCIdType();
5092 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5093 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005094 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005095 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5096 ;
5097 else {
5098 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5099 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005100 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005101 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005102 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5103 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005104 return incompatTy;
5105 }
5106 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005107 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5108 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005109 return compositeType;
5110 }
5111 // Check Objective-C object pointer types and 'void *'
5112 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005113 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005114 // ARC forbids the implicit conversion of object pointers to 'void *',
5115 // so these types are not compatible.
5116 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5117 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5118 LHS = RHS = true;
5119 return QualType();
5120 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005121 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5122 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5123 QualType destPointee
5124 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5125 QualType destType = Context.getPointerType(destPointee);
5126 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005127 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005128 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005129 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005130 return destType;
5131 }
5132 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005133 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005134 // ARC forbids the implicit conversion of object pointers to 'void *',
5135 // so these types are not compatible.
5136 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5138 LHS = RHS = true;
5139 return QualType();
5140 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005141 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5142 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5143 QualType destPointee
5144 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5145 QualType destType = Context.getPointerType(destPointee);
5146 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005147 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005148 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005149 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005150 return destType;
5151 }
5152 return QualType();
5153}
5154
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005155/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005156/// ParenRange in parentheses.
5157static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005158 const PartialDiagnostic &Note,
5159 SourceRange ParenRange) {
5160 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5161 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5162 EndLoc.isValid()) {
5163 Self.Diag(Loc, Note)
5164 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5165 << FixItHint::CreateInsertion(EndLoc, ")");
5166 } else {
5167 // We can't display the parentheses, so just show the bare note.
5168 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005169 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005170}
5171
5172static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5173 return Opc >= BO_Mul && Opc <= BO_Shr;
5174}
5175
Hans Wennborg2f072b42011-06-09 17:06:51 +00005176/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5177/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005178/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5179/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005180static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005181 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005182 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5183 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005184 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005185 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005186
5187 // Built-in binary operator.
5188 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5189 if (IsArithmeticOp(OP->getOpcode())) {
5190 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005191 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005192 return true;
5193 }
5194 }
5195
5196 // Overloaded operator.
5197 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5198 if (Call->getNumArgs() != 2)
5199 return false;
5200
5201 // Make sure this is really a binary operator that is safe to pass into
5202 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5203 OverloadedOperatorKind OO = Call->getOperator();
5204 if (OO < OO_Plus || OO > OO_Arrow)
5205 return false;
5206
5207 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5208 if (IsArithmeticOp(OpKind)) {
5209 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005210 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005211 return true;
5212 }
5213 }
5214
5215 return false;
5216}
5217
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005218static bool IsLogicOp(BinaryOperatorKind Opc) {
5219 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5220}
5221
Hans Wennborg2f072b42011-06-09 17:06:51 +00005222/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5223/// or is a logical expression such as (x==y) which has int type, but is
5224/// commonly interpreted as boolean.
5225static bool ExprLooksBoolean(Expr *E) {
5226 E = E->IgnoreParenImpCasts();
5227
5228 if (E->getType()->isBooleanType())
5229 return true;
5230 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5231 return IsLogicOp(OP->getOpcode());
5232 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5233 return OP->getOpcode() == UO_LNot;
5234
5235 return false;
5236}
5237
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005238/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5239/// and binary operator are mixed in a way that suggests the programmer assumed
5240/// the conditional operator has higher precedence, for example:
5241/// "int x = a + someBinaryCondition ? 1 : 2".
5242static void DiagnoseConditionalPrecedence(Sema &Self,
5243 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005244 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005245 Expr *LHSExpr,
5246 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005247 BinaryOperatorKind CondOpcode;
5248 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005249
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005250 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005251 return;
5252 if (!ExprLooksBoolean(CondRHS))
5253 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005254
Hans Wennborg2f072b42011-06-09 17:06:51 +00005255 // The condition is an arithmetic binary expression, with a right-
5256 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005257
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005258 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005259 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005260 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005261
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005262 SuggestParentheses(Self, OpLoc,
5263 Self.PDiag(diag::note_precedence_conditional_silence)
5264 << BinaryOperator::getOpcodeStr(CondOpcode),
5265 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005266
5267 SuggestParentheses(Self, OpLoc,
5268 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005269 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005270}
5271
Steve Narofff69936d2007-09-16 03:34:24 +00005272/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005273/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005274ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005275 SourceLocation ColonLoc,
5276 Expr *CondExpr, Expr *LHSExpr,
5277 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005278 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5279 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005280 OpaqueValueExpr *opaqueValue = 0;
5281 Expr *commonExpr = 0;
5282 if (LHSExpr == 0) {
5283 commonExpr = CondExpr;
5284
5285 // We usually want to apply unary conversions *before* saving, except
5286 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005287 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005288 && !commonExpr->isTypeDependent()
5289 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5290 && commonExpr->isGLValue()
5291 && commonExpr->isOrdinaryOrBitFieldObject()
5292 && RHSExpr->isOrdinaryOrBitFieldObject()
5293 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005294 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5295 if (commonRes.isInvalid())
5296 return ExprError();
5297 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005298 }
5299
5300 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5301 commonExpr->getType(),
5302 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005303 commonExpr->getObjectKind(),
5304 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005305 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005306 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005307
John McCallf89e55a2010-11-18 06:31:45 +00005308 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005309 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005310 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5311 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005312 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005313 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5314 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005315 return ExprError();
5316
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005317 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5318 RHS.get());
5319
John McCall56ca35d2011-02-17 10:25:35 +00005320 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005321 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5322 LHS.take(), ColonLoc,
5323 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005324
5325 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005326 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005327 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5328 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005329}
5330
John McCalle4be87e2011-01-31 23:13:11 +00005331// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005333// routine is it effectively iqnores the qualifiers on the top level pointee.
5334// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5335// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005336static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005337checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5338 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5339 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005340
Reid Spencer5f016e22007-07-11 17:01:13 +00005341 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005342 const Type *lhptee, *rhptee;
5343 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005344 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5345 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005346
John McCalle4be87e2011-01-31 23:13:11 +00005347 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005348
5349 // C99 6.5.16.1p1: This following citation is common to constraints
5350 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5351 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005352 Qualifiers lq;
5353
John McCallf85e1932011-06-15 23:02:42 +00005354 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5355 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5356 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5357 // Ignore lifetime for further calculation.
5358 lhq.removeObjCLifetime();
5359 rhq.removeObjCLifetime();
5360 }
5361
John McCall86c05f32011-02-01 00:10:29 +00005362 if (!lhq.compatiblyIncludes(rhq)) {
5363 // Treat address-space mismatches as fatal. TODO: address subspaces
5364 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5365 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5366
John McCallf85e1932011-06-15 23:02:42 +00005367 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005368 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005369 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005370 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005371 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005372 && (lhptee->isVoidType() || rhptee->isVoidType()))
5373 ; // keep old
5374
John McCallf85e1932011-06-15 23:02:42 +00005375 // Treat lifetime mismatches as fatal.
5376 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5377 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5378
John McCall86c05f32011-02-01 00:10:29 +00005379 // For GCC compatibility, other qualifier mismatches are treated
5380 // as still compatible in C.
5381 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5382 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005383
Mike Stumpeed9cac2009-02-19 03:04:26 +00005384 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5385 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005386 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005387 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005388 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005389 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005390
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005391 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005392 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005393 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005394 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005395
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005396 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005397 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005398 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005399
5400 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005401 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005402 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005403 }
John McCall86c05f32011-02-01 00:10:29 +00005404
Mike Stumpeed9cac2009-02-19 03:04:26 +00005405 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005406 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005407 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5408 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005409 // Check if the pointee types are compatible ignoring the sign.
5410 // We explicitly check for char so that we catch "char" vs
5411 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005412 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005413 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005414 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005415 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005416
Chris Lattner6a2b9262009-10-17 20:33:28 +00005417 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005418 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005419 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005420 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005421
John McCall86c05f32011-02-01 00:10:29 +00005422 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005423 // Types are compatible ignoring the sign. Qualifier incompatibility
5424 // takes priority over sign incompatibility because the sign
5425 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005426 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005427 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005428
John McCalle4be87e2011-01-31 23:13:11 +00005429 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005430 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005431
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005432 // If we are a multi-level pointer, it's possible that our issue is simply
5433 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5434 // the eventual target type is the same and the pointers have the same
5435 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005436 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005437 do {
John McCall86c05f32011-02-01 00:10:29 +00005438 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5439 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005440 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005441
John McCall86c05f32011-02-01 00:10:29 +00005442 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005443 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005444 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005445
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005446 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005447 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005448 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005449 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005450 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5451 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005452 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005453}
5454
John McCalle4be87e2011-01-31 23:13:11 +00005455/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005456/// block pointer types are compatible or whether a block and normal pointer
5457/// are compatible. It is more restrict than comparing two function pointer
5458// types.
John McCalle4be87e2011-01-31 23:13:11 +00005459static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005460checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5461 QualType RHSType) {
5462 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5463 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005464
Steve Naroff1c7d0672008-09-04 15:10:53 +00005465 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005466
Steve Naroff1c7d0672008-09-04 15:10:53 +00005467 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005468 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5469 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005470
John McCalle4be87e2011-01-31 23:13:11 +00005471 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005472 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005473 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005474
John McCalle4be87e2011-01-31 23:13:11 +00005475 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005476
Steve Naroff1c7d0672008-09-04 15:10:53 +00005477 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005478 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5479 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005480
Richard Trieu1da27a12011-09-06 20:21:22 +00005481 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005482 return Sema::IncompatibleBlockPointer;
5483
Steve Naroff1c7d0672008-09-04 15:10:53 +00005484 return ConvTy;
5485}
5486
John McCalle4be87e2011-01-31 23:13:11 +00005487/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005488/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005489static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005490checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5491 QualType RHSType) {
5492 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5493 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005494
Richard Trieu1da27a12011-09-06 20:21:22 +00005495 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005496 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005497 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5498 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005499 return Sema::IncompatiblePointer;
5500 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005501 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005502 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005503 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5504 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005505 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005506 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005507 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005508 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5509 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005510
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005511 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5512 // make an exception for id<P>
5513 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005514 return Sema::CompatiblePointerDiscardsQualifiers;
5515
Richard Trieu1da27a12011-09-06 20:21:22 +00005516 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005517 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005518 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005519 return Sema::IncompatibleObjCQualifiedId;
5520 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005521}
5522
John McCall1c23e912010-11-16 02:32:08 +00005523Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005524Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005525 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005526 // Fake up an opaque expression. We don't actually care about what
5527 // cast operations are required, so if CheckAssignmentConstraints
5528 // adds casts to this they'll be wasted, but fortunately that doesn't
5529 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005530 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5531 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005532 CastKind K = CK_Invalid;
5533
Richard Trieu1da27a12011-09-06 20:21:22 +00005534 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005535}
5536
Mike Stumpeed9cac2009-02-19 03:04:26 +00005537/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5538/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005539/// pointers. Here are some objectionable examples that GCC considers warnings:
5540///
5541/// int a, *pint;
5542/// short *pshort;
5543/// struct foo *pfoo;
5544///
5545/// pint = pshort; // warning: assignment from incompatible pointer type
5546/// a = pint; // warning: assignment makes integer from pointer without a cast
5547/// pint = a; // warning: assignment makes pointer from integer without a cast
5548/// pint = pfoo; // warning: assignment from incompatible pointer type
5549///
5550/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005551/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005552///
John McCalldaa8e4e2010-11-15 09:13:47 +00005553/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005554Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005555Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005556 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005557 QualType RHSType = RHS.get()->getType();
5558 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005559
Chris Lattnerfc144e22008-01-04 23:18:45 +00005560 // Get canonical types. We're not formatting these types, just comparing
5561 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005562 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5563 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005564
Eli Friedmanb001de72011-10-06 23:00:33 +00005565
John McCallb6cfa242011-01-31 22:28:28 +00005566 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005567 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005568 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005569 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005570 }
5571
Eli Friedman860a3192012-06-16 02:19:17 +00005572 // If we have an atomic type, try a non-atomic assignment, then just add an
5573 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005574 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005575 Sema::AssignConvertType result =
5576 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5577 if (result != Compatible)
5578 return result;
5579 if (Kind != CK_NoOp)
5580 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5581 Kind = CK_NonAtomicToAtomic;
5582 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005583 }
5584
Douglas Gregor9d293df2008-10-28 00:22:11 +00005585 // If the left-hand side is a reference type, then we are in a
5586 // (rare!) case where we've allowed the use of references in C,
5587 // e.g., as a parameter type in a built-in function. In this case,
5588 // just make sure that the type referenced is compatible with the
5589 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005590 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005591 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005592 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5593 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005594 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005595 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005596 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005597 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005598 }
John McCallb6cfa242011-01-31 22:28:28 +00005599
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005600 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5601 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005602 if (LHSType->isExtVectorType()) {
5603 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005604 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005605 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005606 // CK_VectorSplat does T -> vector T, so first cast to the
5607 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005608 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5609 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005610 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005611 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005612 }
5613 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005614 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005615 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005616 }
Mike Stump1eb44332009-09-09 15:08:12 +00005617
John McCallb6cfa242011-01-31 22:28:28 +00005618 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005619 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5620 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005621 // Allow assignments of an AltiVec vector type to an equivalent GCC
5622 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005623 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005624 Kind = CK_BitCast;
5625 return Compatible;
5626 }
5627
Douglas Gregor255210e2010-08-06 10:14:59 +00005628 // If we are allowing lax vector conversions, and LHS and RHS are both
5629 // vectors, the total size only needs to be the same. This is a bitcast;
5630 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005631 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005632 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005633 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005634 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005635 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005636 }
5637 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005638 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005639
John McCallb6cfa242011-01-31 22:28:28 +00005640 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005641 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005642 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005643 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005644 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005645 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005646
John McCallb6cfa242011-01-31 22:28:28 +00005647 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005648 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005649 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005650 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005651 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005652 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005653 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005654
John McCallb6cfa242011-01-31 22:28:28 +00005655 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005656 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005657 Kind = CK_IntegralToPointer; // FIXME: null?
5658 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005659 }
John McCallb6cfa242011-01-31 22:28:28 +00005660
5661 // C pointers are not compatible with ObjC object pointers,
5662 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005663 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005664 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005665 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005666 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005667 return Compatible;
5668 }
5669
5670 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005671 if (RHSType->isObjCClassType() &&
5672 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005673 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005674 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005675 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005676 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005677
John McCallb6cfa242011-01-31 22:28:28 +00005678 Kind = CK_BitCast;
5679 return IncompatiblePointer;
5680 }
5681
5682 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005683 if (RHSType->getAs<BlockPointerType>()) {
5684 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005685 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005686 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005687 }
Steve Naroffb4406862008-09-29 18:10:17 +00005688 }
John McCallb6cfa242011-01-31 22:28:28 +00005689
Steve Naroff1c7d0672008-09-04 15:10:53 +00005690 return Incompatible;
5691 }
5692
John McCallb6cfa242011-01-31 22:28:28 +00005693 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005694 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005695 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005696 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005697 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005698 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005699 }
5700
5701 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005702 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005703 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005704 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005705 }
5706
John McCallb6cfa242011-01-31 22:28:28 +00005707 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005708 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005709 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005710 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005711 }
Steve Naroffb4406862008-09-29 18:10:17 +00005712
John McCallb6cfa242011-01-31 22:28:28 +00005713 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005714 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005715 if (RHSPT->getPointeeType()->isVoidType()) {
5716 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005717 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005718 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005719
Chris Lattnerfc144e22008-01-04 23:18:45 +00005720 return Incompatible;
5721 }
5722
John McCallb6cfa242011-01-31 22:28:28 +00005723 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005724 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005725 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005726 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005727 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005728 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005729 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005730 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005731 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005732 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005733 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005734 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005735 }
5736
5737 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005738 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005739 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005740 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005741 }
5742
John McCallb6cfa242011-01-31 22:28:28 +00005743 // In general, C pointers are not compatible with ObjC object pointers,
5744 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005745 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005746 Kind = CK_CPointerToObjCPointerCast;
5747
John McCallb6cfa242011-01-31 22:28:28 +00005748 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005749 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005750 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005751 }
5752
5753 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005754 if (LHSType->isObjCClassType() &&
5755 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005756 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005757 return Compatible;
5758 }
5759
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005760 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005761 }
John McCallb6cfa242011-01-31 22:28:28 +00005762
5763 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005764 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005765 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005766 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005767 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005768 }
5769
Steve Naroff14108da2009-07-10 23:34:53 +00005770 return Incompatible;
5771 }
John McCallb6cfa242011-01-31 22:28:28 +00005772
5773 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005774 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005775 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005776 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005777 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005778 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005779 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005780
John McCallb6cfa242011-01-31 22:28:28 +00005781 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005782 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005783 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005784 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005785 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005786
Chris Lattnerfc144e22008-01-04 23:18:45 +00005787 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005788 }
John McCallb6cfa242011-01-31 22:28:28 +00005789
5790 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005791 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005792 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005793 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005794 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005795 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005796 }
Steve Naroff14108da2009-07-10 23:34:53 +00005797
John McCallb6cfa242011-01-31 22:28:28 +00005798 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005799 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005800 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005801 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005802 }
5803
Steve Naroff14108da2009-07-10 23:34:53 +00005804 return Incompatible;
5805 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005806
John McCallb6cfa242011-01-31 22:28:28 +00005807 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005808 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5809 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005810 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005811 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005812 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005813 }
John McCallb6cfa242011-01-31 22:28:28 +00005814
Reid Spencer5f016e22007-07-11 17:01:13 +00005815 return Incompatible;
5816}
5817
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005818/// \brief Constructs a transparent union from an expression that is
5819/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005820static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5821 ExprResult &EResult, QualType UnionType,
5822 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005823 // Build an initializer list that designates the appropriate member
5824 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005825 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005826 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005827 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005828 Initializer->setType(UnionType);
5829 Initializer->setInitializedFieldInUnion(Field);
5830
5831 // Build a compound literal constructing a value of the transparent
5832 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005833 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005834 EResult = S.Owned(
5835 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5836 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005837}
5838
5839Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005840Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005841 ExprResult &RHS) {
5842 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005843
Mike Stump1eb44332009-09-09 15:08:12 +00005844 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005845 // transparent_union GCC extension.
5846 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005847 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005848 return Incompatible;
5849
5850 // The field to initialize within the transparent union.
5851 RecordDecl *UD = UT->getDecl();
5852 FieldDecl *InitField = 0;
5853 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005854 for (RecordDecl::field_iterator it = UD->field_begin(),
5855 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005856 it != itend; ++it) {
5857 if (it->getType()->isPointerType()) {
5858 // If the transparent union contains a pointer type, we allow:
5859 // 1) void pointer
5860 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005861 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005862 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005863 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005864 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005865 break;
5866 }
Mike Stump1eb44332009-09-09 15:08:12 +00005867
Richard Trieuf7720da2011-09-06 20:40:12 +00005868 if (RHS.get()->isNullPointerConstant(Context,
5869 Expr::NPC_ValueDependentIsNull)) {
5870 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5871 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005872 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005873 break;
5874 }
5875 }
5876
John McCalldaa8e4e2010-11-15 09:13:47 +00005877 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005878 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005879 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005880 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005881 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005882 break;
5883 }
5884 }
5885
5886 if (!InitField)
5887 return Incompatible;
5888
Richard Trieuf7720da2011-09-06 20:40:12 +00005889 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005890 return Compatible;
5891}
5892
Chris Lattner5cf216b2008-01-04 18:04:52 +00005893Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005894Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5895 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005896 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005897 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005898 // C++ 5.17p3: If the left operand is not of class type, the
5899 // expression is implicitly converted (C++ 4) to the
5900 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005901 ExprResult Res;
5902 if (Diagnose) {
5903 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5904 AA_Assigning);
5905 } else {
5906 ImplicitConversionSequence ICS =
5907 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5908 /*SuppressUserConversions=*/false,
5909 /*AllowExplicit=*/false,
5910 /*InOverloadResolution=*/false,
5911 /*CStyle=*/false,
5912 /*AllowObjCWritebackConversion=*/false);
5913 if (ICS.isFailure())
5914 return Incompatible;
5915 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5916 ICS, AA_Assigning);
5917 }
John Wiegley429bb272011-04-08 18:41:53 +00005918 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005919 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005920 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005921 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005922 !CheckObjCARCUnavailableWeakConversion(LHSType,
5923 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005924 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005925 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005926 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005927 }
5928
5929 // FIXME: Currently, we fall through and treat C++ classes like C
5930 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005931 // FIXME: We also fall through for atomics; not sure what should
5932 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005933 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005934
Steve Naroff529a4ad2007-11-27 17:58:44 +00005935 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5936 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005937 if ((LHSType->isPointerType() ||
5938 LHSType->isObjCObjectPointerType() ||
5939 LHSType->isBlockPointerType())
5940 && RHS.get()->isNullPointerConstant(Context,
5941 Expr::NPC_ValueDependentIsNull)) {
5942 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005943 return Compatible;
5944 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005945
Chris Lattner943140e2007-10-16 02:55:40 +00005946 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005947 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005948 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005949 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005950 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005951 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005952 if (!LHSType->isReferenceType()) {
5953 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5954 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005955 return Incompatible;
5956 }
Steve Narofff1120de2007-08-24 22:33:52 +00005957
John McCalldaa8e4e2010-11-15 09:13:47 +00005958 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005959 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005960 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005961
Steve Narofff1120de2007-08-24 22:33:52 +00005962 // C99 6.5.16.1p2: The value of the right operand is converted to the
5963 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005964 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5965 // so that we can use references in built-in functions even in C.
5966 // The getNonReferenceType() call makes sure that the resulting expression
5967 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005968 if (result != Incompatible && RHS.get()->getType() != LHSType)
5969 RHS = ImpCastExprToType(RHS.take(),
5970 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005971 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005972}
5973
Richard Trieuf7720da2011-09-06 20:40:12 +00005974QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5975 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005976 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005977 << LHS.get()->getType() << RHS.get()->getType()
5978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005979 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005980}
5981
Richard Trieu08062aa2011-09-06 21:01:04 +00005982QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005983 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005984 if (!IsCompAssign) {
5985 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5986 if (LHS.isInvalid())
5987 return QualType();
5988 }
5989 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5990 if (RHS.isInvalid())
5991 return QualType();
5992
Mike Stumpeed9cac2009-02-19 03:04:26 +00005993 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005994 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005995 QualType LHSType =
5996 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5997 QualType RHSType =
5998 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005999
Nate Begemanbe2341d2008-07-14 18:02:46 +00006000 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006001 if (LHSType == RHSType)
6002 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006003
Douglas Gregor255210e2010-08-06 10:14:59 +00006004 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006005 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6006 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6007 if (LHSType->isExtVectorType()) {
6008 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6009 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006010 }
6011
Richard Trieuccd891a2011-09-09 01:45:06 +00006012 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006013 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6014 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006015 }
6016
David Blaikie4e4d0842012-03-11 07:00:24 +00006017 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006018 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006019 // If we are allowing lax vector conversions, and LHS and RHS are both
6020 // vectors, the total size only needs to be the same. This is a
6021 // bitcast; no bits are changed but the result type is different.
6022 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006023 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6024 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006025 }
6026
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006027 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6028 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6029 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006030 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006031 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006032 std::swap(RHS, LHS);
6033 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006034 }
Mike Stump1eb44332009-09-09 15:08:12 +00006035
Nate Begemandde25982009-06-28 19:12:57 +00006036 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006037 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006038 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006039 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6040 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006041 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006042 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006043 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006044 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6045 if (swapped) std::swap(RHS, LHS);
6046 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006047 }
6048 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006049 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6050 RHSType->isRealFloatingType()) {
6051 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006052 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006053 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006054 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006055 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6056 if (swapped) std::swap(RHS, LHS);
6057 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006058 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006059 }
6060 }
Mike Stump1eb44332009-09-09 15:08:12 +00006061
Nate Begemandde25982009-06-28 19:12:57 +00006062 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006063 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006064 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006065 << LHS.get()->getType() << RHS.get()->getType()
6066 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006067 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006068}
6069
Richard Trieu481037f2011-09-16 00:53:10 +00006070// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6071// expression. These are mainly cases where the null pointer is used as an
6072// integer instead of a pointer.
6073static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6074 SourceLocation Loc, bool IsCompare) {
6075 // The canonical way to check for a GNU null is with isNullPointerConstant,
6076 // but we use a bit of a hack here for speed; this is a relatively
6077 // hot path, and isNullPointerConstant is slow.
6078 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6079 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6080
6081 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6082
6083 // Avoid analyzing cases where the result will either be invalid (and
6084 // diagnosed as such) or entirely valid and not something to warn about.
6085 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6086 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6087 return;
6088
6089 // Comparison operations would not make sense with a null pointer no matter
6090 // what the other expression is.
6091 if (!IsCompare) {
6092 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6093 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6094 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6095 return;
6096 }
6097
6098 // The rest of the operations only make sense with a null pointer
6099 // if the other expression is a pointer.
6100 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6101 NonNullType->canDecayToPointerType())
6102 return;
6103
6104 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6105 << LHSNull /* LHS is NULL */ << NonNullType
6106 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6107}
6108
Richard Trieu08062aa2011-09-06 21:01:04 +00006109QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006110 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006111 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006112 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6113
Richard Trieu08062aa2011-09-06 21:01:04 +00006114 if (LHS.get()->getType()->isVectorType() ||
6115 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006116 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006117
Richard Trieuccd891a2011-09-09 01:45:06 +00006118 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006119 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006120 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006121
David Chisnall7a7ee302012-01-16 17:27:18 +00006122
Eli Friedman860a3192012-06-16 02:19:17 +00006123 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006124 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006125
Chris Lattner7ef655a2010-01-12 21:23:57 +00006126 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006127 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006128 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006129 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006130 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6131 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006132
Chris Lattner7ef655a2010-01-12 21:23:57 +00006133 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006134}
6135
Chris Lattner7ef655a2010-01-12 21:23:57 +00006136QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006137 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006138 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6139
Richard Trieu08062aa2011-09-06 21:01:04 +00006140 if (LHS.get()->getType()->isVectorType() ||
6141 RHS.get()->getType()->isVectorType()) {
6142 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6143 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006144 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006145 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006146 }
Steve Naroff90045e82007-07-13 23:32:42 +00006147
Richard Trieuccd891a2011-09-09 01:45:06 +00006148 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006149 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006150 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006151
Eli Friedman860a3192012-06-16 02:19:17 +00006152 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006153 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006154
Chris Lattner7ef655a2010-01-12 21:23:57 +00006155 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006156 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006157 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006158 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6159 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006160
Chris Lattner7ef655a2010-01-12 21:23:57 +00006161 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006162}
6163
Chandler Carruth13b21be2011-06-27 08:02:19 +00006164/// \brief Diagnose invalid arithmetic on two void pointers.
6165static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006166 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006167 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006168 ? diag::err_typecheck_pointer_arith_void_type
6169 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006170 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6171 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006172}
6173
6174/// \brief Diagnose invalid arithmetic on a void pointer.
6175static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6176 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006177 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006178 ? diag::err_typecheck_pointer_arith_void_type
6179 : diag::ext_gnu_void_ptr)
6180 << 0 /* one pointer */ << Pointer->getSourceRange();
6181}
6182
6183/// \brief Diagnose invalid arithmetic on two function pointers.
6184static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6185 Expr *LHS, Expr *RHS) {
6186 assert(LHS->getType()->isAnyPointerType());
6187 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006188 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006189 ? diag::err_typecheck_pointer_arith_function_type
6190 : diag::ext_gnu_ptr_func_arith)
6191 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6192 // We only show the second type if it differs from the first.
6193 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6194 RHS->getType())
6195 << RHS->getType()->getPointeeType()
6196 << LHS->getSourceRange() << RHS->getSourceRange();
6197}
6198
6199/// \brief Diagnose invalid arithmetic on a function pointer.
6200static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6201 Expr *Pointer) {
6202 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006203 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006204 ? diag::err_typecheck_pointer_arith_function_type
6205 : diag::ext_gnu_ptr_func_arith)
6206 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6207 << 0 /* one pointer, so only one type */
6208 << Pointer->getSourceRange();
6209}
6210
Richard Trieud9f19342011-09-12 18:08:02 +00006211/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006212///
6213/// \returns True if pointer has incomplete type
6214static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6215 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006216 assert(Operand->getType()->isAnyPointerType() &&
6217 !Operand->getType()->isDependentType());
6218 QualType PointeeTy = Operand->getType()->getPointeeType();
6219 return S.RequireCompleteType(Loc, PointeeTy,
6220 diag::err_typecheck_arithmetic_incomplete_type,
6221 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006222}
6223
Chandler Carruth13b21be2011-06-27 08:02:19 +00006224/// \brief Check the validity of an arithmetic pointer operand.
6225///
6226/// If the operand has pointer type, this code will check for pointer types
6227/// which are invalid in arithmetic operations. These will be diagnosed
6228/// appropriately, including whether or not the use is supported as an
6229/// extension.
6230///
6231/// \returns True when the operand is valid to use (even if as an extension).
6232static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6233 Expr *Operand) {
6234 if (!Operand->getType()->isAnyPointerType()) return true;
6235
6236 QualType PointeeTy = Operand->getType()->getPointeeType();
6237 if (PointeeTy->isVoidType()) {
6238 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006239 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006240 }
6241 if (PointeeTy->isFunctionType()) {
6242 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006243 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006244 }
6245
Richard Trieu097ecd22011-09-02 02:15:37 +00006246 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006247
6248 return true;
6249}
6250
6251/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6252/// operands.
6253///
6254/// This routine will diagnose any invalid arithmetic on pointer operands much
6255/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6256/// for emitting a single diagnostic even for operations where both LHS and RHS
6257/// are (potentially problematic) pointers.
6258///
6259/// \returns True when the operand is valid to use (even if as an extension).
6260static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006261 Expr *LHSExpr, Expr *RHSExpr) {
6262 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6263 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006264 if (!isLHSPointer && !isRHSPointer) return true;
6265
6266 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006267 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6268 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006269
6270 // Check for arithmetic on pointers to incomplete types.
6271 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6272 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6273 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006274 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6275 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6276 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006277
David Blaikie4e4d0842012-03-11 07:00:24 +00006278 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006279 }
6280
6281 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6282 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6283 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006284 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6285 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6286 RHSExpr);
6287 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006288
David Blaikie4e4d0842012-03-11 07:00:24 +00006289 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006290 }
6291
John McCall1503f0d2012-07-31 05:14:30 +00006292 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6293 return false;
6294 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6295 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006296
Chandler Carruth13b21be2011-06-27 08:02:19 +00006297 return true;
6298}
6299
Nico Weber1cb2d742012-03-02 22:01:22 +00006300/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6301/// literal.
6302static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6303 Expr *LHSExpr, Expr *RHSExpr) {
6304 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6305 Expr* IndexExpr = RHSExpr;
6306 if (!StrExpr) {
6307 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6308 IndexExpr = LHSExpr;
6309 }
6310
6311 bool IsStringPlusInt = StrExpr &&
6312 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6313 if (!IsStringPlusInt)
6314 return;
6315
6316 llvm::APSInt index;
6317 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6318 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6319 if (index.isNonNegative() &&
6320 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6321 index.isUnsigned()))
6322 return;
6323 }
6324
6325 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6326 Self.Diag(OpLoc, diag::warn_string_plus_int)
6327 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6328
6329 // Only print a fixit for "str" + int, not for int + "str".
6330 if (IndexExpr == RHSExpr) {
6331 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6332 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6333 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6334 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6335 << FixItHint::CreateInsertion(EndLoc, "]");
6336 } else
6337 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6338}
6339
Richard Trieud9f19342011-09-12 18:08:02 +00006340/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006341static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006342 Expr *LHSExpr, Expr *RHSExpr) {
6343 assert(LHSExpr->getType()->isAnyPointerType());
6344 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006345 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006346 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6347 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006348}
6349
Chris Lattner7ef655a2010-01-12 21:23:57 +00006350QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006351 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6352 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006353 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6354
Richard Trieudef75842011-09-06 21:13:51 +00006355 if (LHS.get()->getType()->isVectorType() ||
6356 RHS.get()->getType()->isVectorType()) {
6357 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006358 if (CompLHSTy) *CompLHSTy = compType;
6359 return compType;
6360 }
Steve Naroff49b45262007-07-13 16:58:59 +00006361
Richard Trieudef75842011-09-06 21:13:51 +00006362 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6363 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006364 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006365
Nico Weber1cb2d742012-03-02 22:01:22 +00006366 // Diagnose "string literal" '+' int.
6367 if (Opc == BO_Add)
6368 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6369
Reid Spencer5f016e22007-07-11 17:01:13 +00006370 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006371 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006372 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006373 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006374 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006375
John McCall1503f0d2012-07-31 05:14:30 +00006376 // Type-checking. Ultimately the pointer's going to be in PExp;
6377 // note that we bias towards the LHS being the pointer.
6378 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006379
John McCall1503f0d2012-07-31 05:14:30 +00006380 bool isObjCPointer;
6381 if (PExp->getType()->isPointerType()) {
6382 isObjCPointer = false;
6383 } else if (PExp->getType()->isObjCObjectPointerType()) {
6384 isObjCPointer = true;
6385 } else {
6386 std::swap(PExp, IExp);
6387 if (PExp->getType()->isPointerType()) {
6388 isObjCPointer = false;
6389 } else if (PExp->getType()->isObjCObjectPointerType()) {
6390 isObjCPointer = true;
6391 } else {
6392 return InvalidOperands(Loc, LHS, RHS);
6393 }
6394 }
6395 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006396
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006397 if (!IExp->getType()->isIntegerType())
6398 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006399
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006400 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6401 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006402
John McCall1503f0d2012-07-31 05:14:30 +00006403 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006404 return QualType();
6405
6406 // Check array bounds for pointer arithemtic
6407 CheckArrayAccess(PExp, IExp);
6408
6409 if (CompLHSTy) {
6410 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6411 if (LHSTy.isNull()) {
6412 LHSTy = LHS.get()->getType();
6413 if (LHSTy->isPromotableIntegerType())
6414 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006415 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006416 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006417 }
6418
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006419 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006420}
6421
Chris Lattnereca7be62008-04-07 05:30:13 +00006422// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006423QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006424 SourceLocation Loc,
6425 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006426 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6427
Richard Trieudef75842011-09-06 21:13:51 +00006428 if (LHS.get()->getType()->isVectorType() ||
6429 RHS.get()->getType()->isVectorType()) {
6430 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006431 if (CompLHSTy) *CompLHSTy = compType;
6432 return compType;
6433 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006434
Richard Trieudef75842011-09-06 21:13:51 +00006435 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6436 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006437 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006438
Chris Lattner6e4ab612007-12-09 21:53:25 +00006439 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006440
Chris Lattner6e4ab612007-12-09 21:53:25 +00006441 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006442 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006443 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006444 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006445 }
Mike Stump1eb44332009-09-09 15:08:12 +00006446
Chris Lattner6e4ab612007-12-09 21:53:25 +00006447 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006448 if (LHS.get()->getType()->isAnyPointerType()) {
6449 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006450
Chris Lattnerb5f15622009-04-24 23:50:08 +00006451 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006452 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6453 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006454 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006455
Chris Lattner6e4ab612007-12-09 21:53:25 +00006456 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006457 if (RHS.get()->getType()->isIntegerType()) {
6458 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006459 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006460
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006461 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006462 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6463 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006464
Richard Trieudef75842011-09-06 21:13:51 +00006465 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6466 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006467 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006468
Chris Lattner6e4ab612007-12-09 21:53:25 +00006469 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006470 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006471 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006472 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006473
David Blaikie4e4d0842012-03-11 07:00:24 +00006474 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006475 // Pointee types must be the same: C++ [expr.add]
6476 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006477 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006478 }
6479 } else {
6480 // Pointee types must be compatible C99 6.5.6p3
6481 if (!Context.typesAreCompatible(
6482 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6483 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006484 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006485 return QualType();
6486 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006487 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006488
Chandler Carruth13b21be2011-06-27 08:02:19 +00006489 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006490 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006491 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006492
Richard Trieudef75842011-09-06 21:13:51 +00006493 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006494 return Context.getPointerDiffType();
6495 }
6496 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006497
Richard Trieudef75842011-09-06 21:13:51 +00006498 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006499}
6500
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006501static bool isScopedEnumerationType(QualType T) {
6502 if (const EnumType *ET = dyn_cast<EnumType>(T))
6503 return ET->getDecl()->isScoped();
6504 return false;
6505}
6506
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006507static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006508 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006509 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006510 llvm::APSInt Right;
6511 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006512 if (RHS.get()->isValueDependent() ||
6513 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006514 return;
6515
6516 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006517 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006518 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006519 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006520 return;
6521 }
6522 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006523 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006524 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006525 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006526 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006527 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006528 return;
6529 }
6530 if (Opc != BO_Shl)
6531 return;
6532
6533 // When left shifting an ICE which is signed, we can check for overflow which
6534 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6535 // integers have defined behavior modulo one more than the maximum value
6536 // representable in the result type, so never warn for those.
6537 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006538 if (LHS.get()->isValueDependent() ||
6539 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6540 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006541 return;
6542 llvm::APInt ResultBits =
6543 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6544 if (LeftBits.uge(ResultBits))
6545 return;
6546 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6547 Result = Result.shl(Right);
6548
Ted Kremenekfa821382011-06-15 00:54:52 +00006549 // Print the bit representation of the signed integer as an unsigned
6550 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006551 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006552 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6553
Chandler Carruth21206d52011-02-23 23:34:11 +00006554 // If we are only missing a sign bit, this is less likely to result in actual
6555 // bugs -- if the result is cast back to an unsigned type, it will have the
6556 // expected value. Thus we place this behind a different warning that can be
6557 // turned off separately if needed.
6558 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006559 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006560 << HexResult.str() << LHSType
6561 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006562 return;
6563 }
6564
6565 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006566 << HexResult.str() << Result.getMinSignedBits() << LHSType
6567 << Left.getBitWidth() << LHS.get()->getSourceRange()
6568 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006569}
6570
Chris Lattnereca7be62008-04-07 05:30:13 +00006571// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006572QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006573 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006574 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006575 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6576
Chris Lattnerca5eede2007-12-12 05:47:28 +00006577 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006578 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6579 !RHS.get()->getType()->hasIntegerRepresentation())
6580 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006581
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006582 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6583 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006584 if (isScopedEnumerationType(LHS.get()->getType()) ||
6585 isScopedEnumerationType(RHS.get()->getType())) {
6586 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006587 }
6588
Nate Begeman2207d792009-10-25 02:26:48 +00006589 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006590 if (LHS.get()->getType()->isVectorType() ||
6591 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006592 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006593
Chris Lattnerca5eede2007-12-12 05:47:28 +00006594 // Shifts don't perform usual arithmetic conversions, they just do integer
6595 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006596
John McCall1bc80af2010-12-16 19:28:59 +00006597 // For the LHS, do usual unary conversions, but then reset them away
6598 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006599 ExprResult OldLHS = LHS;
6600 LHS = UsualUnaryConversions(LHS.take());
6601 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006602 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006603 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006604 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006605
6606 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006607 RHS = UsualUnaryConversions(RHS.take());
6608 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006609 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006610
Ryan Flynnd0439682009-08-07 16:20:20 +00006611 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006612 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006613
Chris Lattnerca5eede2007-12-12 05:47:28 +00006614 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006615 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006616}
6617
Chandler Carruth99919472010-07-10 12:30:03 +00006618static bool IsWithinTemplateSpecialization(Decl *D) {
6619 if (DeclContext *DC = D->getDeclContext()) {
6620 if (isa<ClassTemplateSpecializationDecl>(DC))
6621 return true;
6622 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6623 return FD->isFunctionTemplateSpecialization();
6624 }
6625 return false;
6626}
6627
Richard Trieue648ac32011-09-02 03:48:46 +00006628/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006629static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6630 ExprResult &RHS) {
6631 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6632 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006633
6634 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6635 if (!LHSEnumType)
6636 return;
6637 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6638 if (!RHSEnumType)
6639 return;
6640
6641 // Ignore anonymous enums.
6642 if (!LHSEnumType->getDecl()->getIdentifier())
6643 return;
6644 if (!RHSEnumType->getDecl()->getIdentifier())
6645 return;
6646
6647 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6648 return;
6649
6650 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6651 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006653}
6654
Richard Trieu7be1be02011-09-02 02:55:45 +00006655/// \brief Diagnose bad pointer comparisons.
6656static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006657 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006658 bool IsError) {
6659 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006660 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006661 << LHS.get()->getType() << RHS.get()->getType()
6662 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006663}
6664
6665/// \brief Returns false if the pointers are converted to a composite type,
6666/// true otherwise.
6667static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006668 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006669 // C++ [expr.rel]p2:
6670 // [...] Pointer conversions (4.10) and qualification
6671 // conversions (4.4) are performed on pointer operands (or on
6672 // a pointer operand and a null pointer constant) to bring
6673 // them to their composite pointer type. [...]
6674 //
6675 // C++ [expr.eq]p1 uses the same notion for (in)equality
6676 // comparisons of pointers.
6677
6678 // C++ [expr.eq]p2:
6679 // In addition, pointers to members can be compared, or a pointer to
6680 // member and a null pointer constant. Pointer to member conversions
6681 // (4.11) and qualification conversions (4.4) are performed to bring
6682 // them to a common type. If one operand is a null pointer constant,
6683 // the common type is the type of the other operand. Otherwise, the
6684 // common type is a pointer to member type similar (4.4) to the type
6685 // of one of the operands, with a cv-qualification signature (4.4)
6686 // that is the union of the cv-qualification signatures of the operand
6687 // types.
6688
Richard Trieuba261492011-09-06 21:27:33 +00006689 QualType LHSType = LHS.get()->getType();
6690 QualType RHSType = RHS.get()->getType();
6691 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6692 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006693
6694 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006695 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006696 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006697 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006698 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006699 return true;
6700 }
6701
6702 if (NonStandardCompositeType)
6703 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006704 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6705 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006706
Richard Trieuba261492011-09-06 21:27:33 +00006707 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6708 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006709 return false;
6710}
6711
6712static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006713 ExprResult &LHS,
6714 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006715 bool IsError) {
6716 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6717 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006718 << LHS.get()->getType() << RHS.get()->getType()
6719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006720}
6721
Jordan Rose9f63a452012-06-08 21:14:25 +00006722static bool isObjCObjectLiteral(ExprResult &E) {
6723 switch (E.get()->getStmtClass()) {
6724 case Stmt::ObjCArrayLiteralClass:
6725 case Stmt::ObjCDictionaryLiteralClass:
6726 case Stmt::ObjCStringLiteralClass:
6727 case Stmt::ObjCBoxedExprClass:
6728 return true;
6729 default:
6730 // Note that ObjCBoolLiteral is NOT an object literal!
6731 return false;
6732 }
6733}
6734
Jordan Rose8d872ca2012-07-17 17:46:40 +00006735static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6736 // Get the LHS object's interface type.
6737 QualType Type = LHS->getType();
6738 QualType InterfaceType;
6739 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6740 InterfaceType = PTy->getPointeeType();
6741 if (const ObjCObjectType *iQFaceTy =
6742 InterfaceType->getAsObjCQualifiedInterfaceType())
6743 InterfaceType = iQFaceTy->getBaseType();
6744 } else {
6745 // If this is not actually an Objective-C object, bail out.
6746 return false;
6747 }
6748
6749 // If the RHS isn't an Objective-C object, bail out.
6750 if (!RHS->getType()->isObjCObjectPointerType())
6751 return false;
6752
6753 // Try to find the -isEqual: method.
6754 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6755 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6756 InterfaceType,
6757 /*instance=*/true);
6758 if (!Method) {
6759 if (Type->isObjCIdType()) {
6760 // For 'id', just check the global pool.
6761 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6762 /*receiverId=*/true,
6763 /*warn=*/false);
6764 } else {
6765 // Check protocols.
6766 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6767 cast<ObjCObjectPointerType>(Type),
6768 /*instance=*/true);
6769 }
6770 }
6771
6772 if (!Method)
6773 return false;
6774
6775 QualType T = Method->param_begin()[0]->getType();
6776 if (!T->isObjCObjectPointerType())
6777 return false;
6778
6779 QualType R = Method->getResultType();
6780 if (!R->isScalarType())
6781 return false;
6782
6783 return true;
6784}
6785
6786static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6787 ExprResult &LHS, ExprResult &RHS,
6788 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006789 Expr *Literal;
6790 Expr *Other;
6791 if (isObjCObjectLiteral(LHS)) {
6792 Literal = LHS.get();
6793 Other = RHS.get();
6794 } else {
6795 Literal = RHS.get();
6796 Other = LHS.get();
6797 }
6798
6799 // Don't warn on comparisons against nil.
6800 Other = Other->IgnoreParenCasts();
6801 if (Other->isNullPointerConstant(S.getASTContext(),
6802 Expr::NPC_ValueDependentIsNotNull))
6803 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006804
Jordan Roseeec207f2012-07-17 17:46:44 +00006805 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006806 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006807 enum {
6808 LK_Array,
6809 LK_Dictionary,
6810 LK_Numeric,
6811 LK_Boxed,
6812 LK_String
6813 } LiteralKind;
6814
Jordan Rose9f63a452012-06-08 21:14:25 +00006815 switch (Literal->getStmtClass()) {
6816 case Stmt::ObjCStringLiteralClass:
6817 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006818 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006819 break;
6820 case Stmt::ObjCArrayLiteralClass:
6821 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006822 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006823 break;
6824 case Stmt::ObjCDictionaryLiteralClass:
6825 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006826 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006827 break;
6828 case Stmt::ObjCBoxedExprClass: {
6829 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6830 switch (Inner->getStmtClass()) {
6831 case Stmt::IntegerLiteralClass:
6832 case Stmt::FloatingLiteralClass:
6833 case Stmt::CharacterLiteralClass:
6834 case Stmt::ObjCBoolLiteralExprClass:
6835 case Stmt::CXXBoolLiteralExprClass:
6836 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006837 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006838 break;
6839 case Stmt::ImplicitCastExprClass: {
6840 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6841 // Boolean literals can be represented by implicit casts.
6842 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006843 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006844 break;
6845 }
6846 // FALLTHROUGH
6847 }
6848 default:
6849 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006850 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006851 break;
6852 }
6853 break;
6854 }
6855 default:
6856 llvm_unreachable("Unknown Objective-C object literal kind");
6857 }
6858
Jordan Roseeec207f2012-07-17 17:46:44 +00006859 if (LiteralKind == LK_String)
6860 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6861 << Literal->getSourceRange();
6862 else
6863 S.Diag(Loc, diag::warn_objc_literal_comparison)
6864 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006865
Jordan Rose8d872ca2012-07-17 17:46:40 +00006866 if (BinaryOperator::isEqualityOp(Opc) &&
6867 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6868 SourceLocation Start = LHS.get()->getLocStart();
6869 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6870 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006871
Jordan Rose8d872ca2012-07-17 17:46:40 +00006872 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6873 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6874 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6875 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006876 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006877}
6878
Douglas Gregor0c6db942009-05-04 06:07:12 +00006879// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006880QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006881 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006882 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006883 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6884
John McCall2de56d12010-08-25 11:45:40 +00006885 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006886
Chris Lattner02dd4b12009-12-05 05:40:13 +00006887 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006888 if (LHS.get()->getType()->isVectorType() ||
6889 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006890 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006891
Richard Trieuf1775fb2011-09-06 21:43:51 +00006892 QualType LHSType = LHS.get()->getType();
6893 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006894
Richard Trieuf1775fb2011-09-06 21:43:51 +00006895 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6896 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006897
Richard Trieuf1775fb2011-09-06 21:43:51 +00006898 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006899
Richard Trieuf1775fb2011-09-06 21:43:51 +00006900 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006901 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006902 !LHS.get()->getLocStart().isMacroID() &&
6903 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006904 // For non-floating point types, check for self-comparisons of the form
6905 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6906 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006907 //
6908 // NOTE: Don't warn about comparison expressions resulting from macro
6909 // expansion. Also don't warn about comparisons which are only self
6910 // comparisons within a template specialization. The warnings should catch
6911 // obvious cases in the definition of the template anyways. The idea is to
6912 // warn when the typed comparison operator will always evaluate to the same
6913 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006914 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006915 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006916 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006917 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006918 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006919 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006920 << (Opc == BO_EQ
6921 || Opc == BO_LE
6922 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006923 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006924 !DRL->getDecl()->getType()->isReferenceType() &&
6925 !DRR->getDecl()->getType()->isReferenceType()) {
6926 // what is it always going to eval to?
6927 char always_evals_to;
6928 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006929 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006930 always_evals_to = 0; // false
6931 break;
John McCall2de56d12010-08-25 11:45:40 +00006932 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006933 always_evals_to = 1; // true
6934 break;
6935 default:
6936 // best we can say is 'a constant'
6937 always_evals_to = 2; // e.g. array1 <= array2
6938 break;
6939 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006940 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006941 << 1 // array
6942 << always_evals_to);
6943 }
6944 }
Chandler Carruth99919472010-07-10 12:30:03 +00006945 }
Mike Stump1eb44332009-09-09 15:08:12 +00006946
Chris Lattner55660a72009-03-08 19:39:53 +00006947 if (isa<CastExpr>(LHSStripped))
6948 LHSStripped = LHSStripped->IgnoreParenCasts();
6949 if (isa<CastExpr>(RHSStripped))
6950 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006951
Chris Lattner55660a72009-03-08 19:39:53 +00006952 // Warn about comparisons against a string constant (unless the other
6953 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006954 Expr *literalString = 0;
6955 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006956 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006957 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006958 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006959 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006960 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006961 } else if ((isa<StringLiteral>(RHSStripped) ||
6962 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006963 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006964 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006965 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006966 literalStringStripped = RHSStripped;
6967 }
6968
6969 if (literalString) {
6970 std::string resultComparison;
6971 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006972 case BO_LT: resultComparison = ") < 0"; break;
6973 case BO_GT: resultComparison = ") > 0"; break;
6974 case BO_LE: resultComparison = ") <= 0"; break;
6975 case BO_GE: resultComparison = ") >= 0"; break;
6976 case BO_EQ: resultComparison = ") == 0"; break;
6977 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006978 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006979 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006980
Ted Kremenek351ba912011-02-23 01:52:04 +00006981 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006982 PDiag(diag::warn_stringcompare)
6983 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006984 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006985 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006986 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006987
Douglas Gregord64fdd02010-06-08 19:50:34 +00006988 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006989 if (LHS.get()->getType()->isArithmeticType() &&
6990 RHS.get()->getType()->isArithmeticType()) {
6991 UsualArithmeticConversions(LHS, RHS);
6992 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006993 return QualType();
6994 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006995 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006996 LHS = UsualUnaryConversions(LHS.take());
6997 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006998 return QualType();
6999
Richard Trieuf1775fb2011-09-06 21:43:51 +00007000 RHS = UsualUnaryConversions(RHS.take());
7001 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007002 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007003 }
7004
Richard Trieuf1775fb2011-09-06 21:43:51 +00007005 LHSType = LHS.get()->getType();
7006 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007007
Douglas Gregor447b69e2008-11-19 03:25:36 +00007008 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007009 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007010
Richard Trieuccd891a2011-09-09 01:45:06 +00007011 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007012 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007013 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007014 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007015 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007016 if (LHSType->hasFloatingRepresentation())
7017 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007018
Richard Trieuf1775fb2011-09-06 21:43:51 +00007019 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007020 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007021 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007022
Richard Trieuf1775fb2011-09-06 21:43:51 +00007023 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007024 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007025 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007026 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007027
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007028 // All of the following pointer-related warnings are GCC extensions, except
7029 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007030 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007031 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007032 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007033 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007034 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007035
David Blaikie4e4d0842012-03-11 07:00:24 +00007036 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007037 if (LCanPointeeTy == RCanPointeeTy)
7038 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007039 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007040 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7041 // Valid unless comparison between non-null pointer and function pointer
7042 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007043 // In a SFINAE context, we treat this as a hard error to maintain
7044 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007045 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7046 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007047 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007048 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007049
7050 if (isSFINAEContext())
7051 return QualType();
7052
Richard Trieuf1775fb2011-09-06 21:43:51 +00007053 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007054 return ResultTy;
7055 }
7056 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007057
Richard Trieuf1775fb2011-09-06 21:43:51 +00007058 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007059 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007060 else
7061 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007062 }
Eli Friedman3075e762009-08-23 00:27:47 +00007063 // C99 6.5.9p2 and C99 6.5.8p2
7064 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7065 RCanPointeeTy.getUnqualifiedType())) {
7066 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007067 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007068 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 << LHSType << RHSType << LHS.get()->getSourceRange()
7070 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007071 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007072 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007073 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7074 // Valid unless comparison between non-null pointer and function pointer
7075 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007076 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007077 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007078 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007079 } else {
7080 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007081 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007082 }
John McCall34d6f932011-03-11 04:25:25 +00007083 if (LCanPointeeTy != RCanPointeeTy) {
7084 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007085 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007086 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007087 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007088 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007089 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007090 }
Mike Stump1eb44332009-09-09 15:08:12 +00007091
David Blaikie4e4d0842012-03-11 07:00:24 +00007092 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007093 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007094 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007095 return ResultTy;
7096
Mike Stump1eb44332009-09-09 15:08:12 +00007097 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007098 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007099 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007100 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007101 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007102 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7103 RHS = ImpCastExprToType(RHS.take(), LHSType,
7104 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007105 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007106 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007107 return ResultTy;
7108 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007109 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007110 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007111 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007112 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7113 LHS = ImpCastExprToType(LHS.take(), RHSType,
7114 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007115 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007116 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007117 return ResultTy;
7118 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007119
7120 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007121 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007122 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7123 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007124 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007125 else
7126 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007127 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007128
7129 // Handle scoped enumeration types specifically, since they don't promote
7130 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007131 if (LHS.get()->getType()->isEnumeralType() &&
7132 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7133 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007134 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007135 }
Mike Stump1eb44332009-09-09 15:08:12 +00007136
Steve Naroff1c7d0672008-09-04 15:10:53 +00007137 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007138 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007139 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007140 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7141 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007142
Steve Naroff1c7d0672008-09-04 15:10:53 +00007143 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007144 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007145 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007146 << LHSType << RHSType << LHS.get()->getSourceRange()
7147 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007148 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007149 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007150 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007151 }
John Wiegley429bb272011-04-08 18:41:53 +00007152
Steve Naroff59f53942008-09-28 01:11:11 +00007153 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007154 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007155 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7156 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007157 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007158 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007159 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007160 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007161 ->getPointeeType()->isVoidType())))
7162 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007163 << LHSType << RHSType << LHS.get()->getSourceRange()
7164 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007165 }
John McCall34d6f932011-03-11 04:25:25 +00007166 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007167 LHS = ImpCastExprToType(LHS.take(), RHSType,
7168 RHSType->isPointerType() ? CK_BitCast
7169 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007170 else
John McCall1d9b3b22011-09-09 05:25:32 +00007171 RHS = ImpCastExprToType(RHS.take(), LHSType,
7172 LHSType->isPointerType() ? CK_BitCast
7173 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007174 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007175 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007176
Richard Trieuf1775fb2011-09-06 21:43:51 +00007177 if (LHSType->isObjCObjectPointerType() ||
7178 RHSType->isObjCObjectPointerType()) {
7179 const PointerType *LPT = LHSType->getAs<PointerType>();
7180 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007181 if (LPT || RPT) {
7182 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7183 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007184
Steve Naroffa8069f12008-11-17 19:49:16 +00007185 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007186 !Context.typesAreCompatible(LHSType, RHSType)) {
7187 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007188 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007189 }
John McCall34d6f932011-03-11 04:25:25 +00007190 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007191 LHS = ImpCastExprToType(LHS.take(), RHSType,
7192 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007193 else
John McCall1d9b3b22011-09-09 05:25:32 +00007194 RHS = ImpCastExprToType(RHS.take(), LHSType,
7195 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007196 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007197 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007198 if (LHSType->isObjCObjectPointerType() &&
7199 RHSType->isObjCObjectPointerType()) {
7200 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7201 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007202 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007203 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007204 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007205
John McCall34d6f932011-03-11 04:25:25 +00007206 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007207 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007208 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007209 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007210 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007211 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007212 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007213 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7214 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007215 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007216 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007217 if (LangOpts.DebuggerSupport) {
7218 // Under a debugger, allow the comparison of pointers to integers,
7219 // since users tend to want to compare addresses.
7220 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007221 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007222 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007223 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007224 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007225 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007226 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007227 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7228 isError = true;
7229 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007230 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007231
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007232 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007233 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007234 << LHSType << RHSType << LHS.get()->getSourceRange()
7235 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007236 if (isError)
7237 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007238 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007239
Richard Trieuf1775fb2011-09-06 21:43:51 +00007240 if (LHSType->isIntegerType())
7241 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007242 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007243 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007244 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007245 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007246 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007247 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007248
Steve Naroff39218df2008-09-04 16:56:14 +00007249 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007250 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007251 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7252 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007253 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007254 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007255 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007256 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7257 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007258 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007259 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007260
Richard Trieuf1775fb2011-09-06 21:43:51 +00007261 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007262}
7263
Tanya Lattner4f692c22012-01-16 21:02:28 +00007264
7265// Return a signed type that is of identical size and number of elements.
7266// For floating point vectors, return an integer type of identical size
7267// and number of elements.
7268QualType Sema::GetSignedVectorType(QualType V) {
7269 const VectorType *VTy = V->getAs<VectorType>();
7270 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7271 if (TypeSize == Context.getTypeSize(Context.CharTy))
7272 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7273 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7274 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7275 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7276 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7277 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7278 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7279 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7280 "Unhandled vector element size in vector compare");
7281 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7282}
7283
Nate Begemanbe2341d2008-07-14 18:02:46 +00007284/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007285/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007286/// like a scalar comparison, a vector comparison produces a vector of integer
7287/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007288QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007289 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007290 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007291 // Check to make sure we're operating on vectors of the same type and width,
7292 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007293 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007294 if (vType.isNull())
7295 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007296
Richard Trieu9f60dee2011-09-07 01:19:57 +00007297 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007298
Anton Yartsev7870b132011-03-27 15:36:07 +00007299 // If AltiVec, the comparison results in a numeric type, i.e.
7300 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007301 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007302 return Context.getLogicalOperationType();
7303
Nate Begemanbe2341d2008-07-14 18:02:46 +00007304 // For non-floating point types, check for self-comparisons of the form
7305 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7306 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007307 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007308 if (DeclRefExpr* DRL
7309 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7310 if (DeclRefExpr* DRR
7311 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007312 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007313 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007314 PDiag(diag::warn_comparison_always)
7315 << 0 // self-
7316 << 2 // "a constant"
7317 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007318 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007319
Nate Begemanbe2341d2008-07-14 18:02:46 +00007320 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007321 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007322 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007323 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007324 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007325
7326 // Return a signed type for the vector.
7327 return GetSignedVectorType(LHSType);
7328}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007329
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007330QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7331 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007332 // Ensure that either both operands are of the same vector type, or
7333 // one operand is of a vector type and the other is of its element type.
7334 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7335 if (vType.isNull() || vType->isFloatingType())
7336 return InvalidOperands(Loc, LHS, RHS);
7337
7338 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007339}
7340
Reid Spencer5f016e22007-07-11 17:01:13 +00007341inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007342 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007343 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7344
Richard Trieu9f60dee2011-09-07 01:19:57 +00007345 if (LHS.get()->getType()->isVectorType() ||
7346 RHS.get()->getType()->isVectorType()) {
7347 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7348 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007349 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007350
Richard Trieu9f60dee2011-09-07 01:19:57 +00007351 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007352 }
Steve Naroff90045e82007-07-13 23:32:42 +00007353
Richard Trieu9f60dee2011-09-07 01:19:57 +00007354 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7355 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007356 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007357 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007358 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007359 LHS = LHSResult.take();
7360 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007361
Eli Friedman860a3192012-06-16 02:19:17 +00007362 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007363 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007364 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007365}
7366
7367inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007368 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007369
Tanya Lattner4f692c22012-01-16 21:02:28 +00007370 // Check vector operands differently.
7371 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7372 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7373
Chris Lattner90a8f272010-07-13 19:41:32 +00007374 // Diagnose cases where the user write a logical and/or but probably meant a
7375 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7376 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007377 if (LHS.get()->getType()->isIntegerType() &&
7378 !LHS.get()->getType()->isBooleanType() &&
7379 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007380 // Don't warn in macros or template instantiations.
7381 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007382 // If the RHS can be constant folded, and if it constant folds to something
7383 // that isn't 0 or 1 (which indicate a potential logical operation that
7384 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007385 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007386 llvm::APSInt Result;
7387 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007388 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007389 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007390 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007391 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007392 << (Opc == BO_LAnd ? "&&" : "||");
7393 // Suggest replacing the logical operator with the bitwise version
7394 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7395 << (Opc == BO_LAnd ? "&" : "|")
7396 << FixItHint::CreateReplacement(SourceRange(
7397 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007398 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007399 Opc == BO_LAnd ? "&" : "|");
7400 if (Opc == BO_LAnd)
7401 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7402 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7403 << FixItHint::CreateRemoval(
7404 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007405 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007406 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007407 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007408 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007409 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007410 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007411
David Blaikie4e4d0842012-03-11 07:00:24 +00007412 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007413 LHS = UsualUnaryConversions(LHS.take());
7414 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007415 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007416
Richard Trieu9f60dee2011-09-07 01:19:57 +00007417 RHS = UsualUnaryConversions(RHS.take());
7418 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007419 return QualType();
7420
Richard Trieu9f60dee2011-09-07 01:19:57 +00007421 if (!LHS.get()->getType()->isScalarType() ||
7422 !RHS.get()->getType()->isScalarType())
7423 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007424
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007425 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007426 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007427
John McCall75f7c0f2010-06-04 00:29:51 +00007428 // The following is safe because we only use this method for
7429 // non-overloadable operands.
7430
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007431 // C++ [expr.log.and]p1
7432 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007433 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007434 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7435 if (LHSRes.isInvalid())
7436 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007437 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007438
Richard Trieu9f60dee2011-09-07 01:19:57 +00007439 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7440 if (RHSRes.isInvalid())
7441 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007442 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007443
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007444 // C++ [expr.log.and]p2
7445 // C++ [expr.log.or]p2
7446 // The result is a bool.
7447 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007448}
7449
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007450/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7451/// is a read-only property; return true if so. A readonly property expression
7452/// depends on various declarations and thus must be treated specially.
7453///
Mike Stump1eb44332009-09-09 15:08:12 +00007454static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007455 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7456 if (!PropExpr) return false;
7457 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007458
John McCall3c3b7f92011-10-25 17:37:35 +00007459 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7460 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007461 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007462 PropExpr->getBase()->getType();
7463
John McCall3c3b7f92011-10-25 17:37:35 +00007464 if (const ObjCObjectPointerType *OPT =
7465 BaseType->getAsObjCInterfacePointerType())
7466 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7467 if (S.isPropertyReadonly(PDecl, IFace))
7468 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007469 return false;
7470}
7471
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007472static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007473 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7474 if (!ME) return false;
7475 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7476 ObjCMessageExpr *Base =
7477 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7478 if (!Base) return false;
7479 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007480}
7481
John McCall78dae242012-03-13 00:37:01 +00007482/// Is the given expression (which must be 'const') a reference to a
7483/// variable which was originally non-const, but which has become
7484/// 'const' due to being captured within a block?
7485enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7486static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7487 assert(E->isLValue() && E->getType().isConstQualified());
7488 E = E->IgnoreParens();
7489
7490 // Must be a reference to a declaration from an enclosing scope.
7491 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7492 if (!DRE) return NCCK_None;
7493 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7494
7495 // The declaration must be a variable which is not declared 'const'.
7496 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7497 if (!var) return NCCK_None;
7498 if (var->getType().isConstQualified()) return NCCK_None;
7499 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7500
7501 // Decide whether the first capture was for a block or a lambda.
7502 DeclContext *DC = S.CurContext;
7503 while (DC->getParent() != var->getDeclContext())
7504 DC = DC->getParent();
7505 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7506}
7507
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007508/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7509/// emit an error and return true. If so, return false.
7510static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007511 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007512 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007513 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007514 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007515 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7516 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007517 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7518 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007519 if (IsLV == Expr::MLV_Valid)
7520 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007521
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007522 unsigned Diag = 0;
7523 bool NeedType = false;
7524 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007525 case Expr::MLV_ConstQualified:
7526 Diag = diag::err_typecheck_assign_const;
7527
John McCall78dae242012-03-13 00:37:01 +00007528 // Use a specialized diagnostic when we're assigning to an object
7529 // from an enclosing function or block.
7530 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7531 if (NCCK == NCCK_Block)
7532 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7533 else
7534 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7535 break;
7536 }
7537
John McCall7acddac2011-06-17 06:42:21 +00007538 // In ARC, use some specialized diagnostics for occasions where we
7539 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007540 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007541 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7542 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7543 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7544
John McCall7acddac2011-06-17 06:42:21 +00007545 // Use the normal diagnostic if it's pseudo-__strong but the
7546 // user actually wrote 'const'.
7547 if (var->isARCPseudoStrong() &&
7548 (!var->getTypeSourceInfo() ||
7549 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7550 // There are two pseudo-strong cases:
7551 // - self
John McCallf85e1932011-06-15 23:02:42 +00007552 ObjCMethodDecl *method = S.getCurMethodDecl();
7553 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007554 Diag = method->isClassMethod()
7555 ? diag::err_typecheck_arc_assign_self_class_method
7556 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007557
7558 // - fast enumeration variables
7559 else
John McCallf85e1932011-06-15 23:02:42 +00007560 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007561
John McCallf85e1932011-06-15 23:02:42 +00007562 SourceRange Assign;
7563 if (Loc != OrigLoc)
7564 Assign = SourceRange(OrigLoc, OrigLoc);
7565 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7566 // We need to preserve the AST regardless, so migration tool
7567 // can do its job.
7568 return false;
7569 }
7570 }
7571 }
7572
7573 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007574 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007575 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007576 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7577 NeedType = true;
7578 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007579 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007580 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7581 NeedType = true;
7582 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007583 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007584 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7585 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007586 case Expr::MLV_Valid:
7587 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007588 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007589 case Expr::MLV_MemberFunction:
7590 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007591 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7592 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007593 case Expr::MLV_IncompleteType:
7594 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007595 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007596 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007597 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007598 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7599 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007600 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007601 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007602 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007603 case Expr::MLV_InvalidMessageExpression:
7604 Diag = diag::error_readonly_message_assignment;
7605 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007606 case Expr::MLV_SubObjCPropertySetting:
7607 Diag = diag::error_no_subobject_property_setting;
7608 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007609 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007610
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007611 SourceRange Assign;
7612 if (Loc != OrigLoc)
7613 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007614 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007615 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007616 else
Mike Stump1eb44332009-09-09 15:08:12 +00007617 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007618 return true;
7619}
7620
Nico Weber7c81b432012-07-03 02:03:06 +00007621static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7622 SourceLocation Loc,
7623 Sema &Sema) {
7624 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007625 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7626 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7627 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7628 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007629 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007630 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007631
Nico Weber7c81b432012-07-03 02:03:06 +00007632 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007633 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7634 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7635 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7636 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7637 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7638 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007639 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007640 }
7641}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007642
7643// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007644QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007645 SourceLocation Loc,
7646 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007647 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7648
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007649 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007650 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007651 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007652
Richard Trieu268942b2011-09-07 01:33:52 +00007653 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007654 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7655 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007656 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007657 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007658 Expr *RHSCheck = RHS.get();
7659
Nico Weber7c81b432012-07-03 02:03:06 +00007660 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007661
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007662 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007663 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007664 if (RHS.isInvalid())
7665 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007666 // Special case of NSObject attributes on c-style pointer types.
7667 if (ConvTy == IncompatiblePointer &&
7668 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007669 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007670 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007671 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007672 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007673
John McCallf89e55a2010-11-18 06:31:45 +00007674 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007675 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007676 Diag(Loc, diag::err_objc_object_assignment)
7677 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007678
Chris Lattner2c156472008-08-21 18:04:13 +00007679 // If the RHS is a unary plus or minus, check to see if they = and + are
7680 // right next to each other. If so, the user may have typo'd "x =+ 4"
7681 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007682 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7683 RHSCheck = ICE->getSubExpr();
7684 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007685 if ((UO->getOpcode() == UO_Plus ||
7686 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007687 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007688 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007689 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007690 // And there is a space or other character before the subexpr of the
7691 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007692 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007693 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007694 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007695 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007696 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007697 }
Chris Lattner2c156472008-08-21 18:04:13 +00007698 }
John McCallf85e1932011-06-15 23:02:42 +00007699
7700 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007701 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7702 // Warn about retain cycles where a block captures the LHS, but
7703 // not if the LHS is a simple variable into which the block is
7704 // being stored...unless that variable can be captured by reference!
7705 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7706 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7707 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7708 checkRetainCycles(LHSExpr, RHS.get());
7709
7710 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007711 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007712 }
John McCallf85e1932011-06-15 23:02:42 +00007713 }
Chris Lattner2c156472008-08-21 18:04:13 +00007714 } else {
7715 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007716 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007717 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007718
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007719 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007720 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007721 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007722
Richard Trieu268942b2011-09-07 01:33:52 +00007723 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007724
Reid Spencer5f016e22007-07-11 17:01:13 +00007725 // C99 6.5.16p3: The type of an assignment expression is the type of the
7726 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007727 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007728 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7729 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007730 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007731 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007732 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007733 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007734}
7735
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007736// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007737static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007738 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007739 LHS = S.CheckPlaceholderExpr(LHS.take());
7740 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007741 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007742 return QualType();
7743
John McCallcf2e5062010-10-12 07:14:40 +00007744 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7745 // operands, but not unary promotions.
7746 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007747
John McCallf6a16482010-12-04 03:47:34 +00007748 // So we treat the LHS as a ignored value, and in C++ we allow the
7749 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007750 LHS = S.IgnoredValueConversions(LHS.take());
7751 if (LHS.isInvalid())
7752 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007753
Eli Friedmana6115062012-05-24 00:47:05 +00007754 S.DiagnoseUnusedExprResult(LHS.get());
7755
David Blaikie4e4d0842012-03-11 07:00:24 +00007756 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007757 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7758 if (RHS.isInvalid())
7759 return QualType();
7760 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007761 S.RequireCompleteType(Loc, RHS.get()->getType(),
7762 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007763 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007764
John Wiegley429bb272011-04-08 18:41:53 +00007765 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007766}
7767
Steve Naroff49b45262007-07-13 16:58:59 +00007768/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7769/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007770static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7771 ExprValueKind &VK,
7772 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007773 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007774 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007775 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007776
Chris Lattner3528d352008-11-21 07:05:48 +00007777 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007778 // Atomic types can be used for increment / decrement where the non-atomic
7779 // versions can, so ignore the _Atomic() specifier for the purpose of
7780 // checking.
7781 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7782 ResType = ResAtomicType->getValueType();
7783
Chris Lattner3528d352008-11-21 07:05:48 +00007784 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007785
David Blaikie4e4d0842012-03-11 07:00:24 +00007786 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007787 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007788 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007789 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007790 return QualType();
7791 }
7792 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007793 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007794 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007795 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007796 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007797 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007798 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007799 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007800 } else if (ResType->isObjCObjectPointerType()) {
7801 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7802 // Otherwise, we just need a complete type.
7803 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7804 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7805 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007806 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007807 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007808 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007809 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007810 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007811 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007812 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007813 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007814 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007815 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007816 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007817 } else {
John McCall09431682010-11-18 19:01:18 +00007818 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007819 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007820 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007821 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007822 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007823 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007824 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007825 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007826 // In C++, a prefix increment is the same type as the operand. Otherwise
7827 // (in C or with postfix), the increment is the unqualified type of the
7828 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007829 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007830 VK = VK_LValue;
7831 return ResType;
7832 } else {
7833 VK = VK_RValue;
7834 return ResType.getUnqualifiedType();
7835 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007836}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007837
7838
Anders Carlsson369dee42008-02-01 07:15:58 +00007839/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007840/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007841/// where the declaration is needed for type checking. We only need to
7842/// handle cases when the expression references a function designator
7843/// or is an lvalue. Here are some examples:
7844/// - &(x) => x
7845/// - &*****f => f for f a function designator.
7846/// - &s.xx => s
7847/// - &s.zz[1].yy -> s, if zz is an array
7848/// - *(x + 1) -> x, if x is an array
7849/// - &"123"[2] -> 0
7850/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007851static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007852 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007853 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007854 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007855 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007856 // If this is an arrow operator, the address is an offset from
7857 // the base's value, so the object the base refers to is
7858 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007859 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007860 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007861 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007862 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007863 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007864 // FIXME: This code shouldn't be necessary! We should catch the implicit
7865 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007866 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7867 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7868 if (ICE->getSubExpr()->getType()->isArrayType())
7869 return getPrimaryDecl(ICE->getSubExpr());
7870 }
7871 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007872 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007873 case Stmt::UnaryOperatorClass: {
7874 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007875
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007876 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007877 case UO_Real:
7878 case UO_Imag:
7879 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007880 return getPrimaryDecl(UO->getSubExpr());
7881 default:
7882 return 0;
7883 }
7884 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007885 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007886 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007887 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007888 // If the result of an implicit cast is an l-value, we care about
7889 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007890 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007891 default:
7892 return 0;
7893 }
7894}
7895
Richard Trieu5520f232011-09-07 21:46:33 +00007896namespace {
7897 enum {
7898 AO_Bit_Field = 0,
7899 AO_Vector_Element = 1,
7900 AO_Property_Expansion = 2,
7901 AO_Register_Variable = 3,
7902 AO_No_Error = 4
7903 };
7904}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007905/// \brief Diagnose invalid operand for address of operations.
7906///
7907/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007908static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7909 Expr *E, unsigned Type) {
7910 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7911}
7912
Reid Spencer5f016e22007-07-11 17:01:13 +00007913/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007914/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007915/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007916/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007917/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007918/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007919/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007920static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007921 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007922 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7923 if (PTy->getKind() == BuiltinType::Overload) {
7924 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7925 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7926 << OrigOp.get()->getSourceRange();
7927 return QualType();
7928 }
7929
7930 return S.Context.OverloadTy;
7931 }
7932
7933 if (PTy->getKind() == BuiltinType::UnknownAny)
7934 return S.Context.UnknownAnyTy;
7935
7936 if (PTy->getKind() == BuiltinType::BoundMember) {
7937 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7938 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007939 return QualType();
7940 }
John McCall3c3b7f92011-10-25 17:37:35 +00007941
7942 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7943 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007944 }
John McCall9c72c602010-08-27 09:08:28 +00007945
John McCall3c3b7f92011-10-25 17:37:35 +00007946 if (OrigOp.get()->isTypeDependent())
7947 return S.Context.DependentTy;
7948
7949 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007950
John McCall9c72c602010-08-27 09:08:28 +00007951 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007952 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007953
David Blaikie4e4d0842012-03-11 07:00:24 +00007954 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007955 // Implement C99-only parts of addressof rules.
7956 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007957 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007958 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7959 // (assuming the deref expression is valid).
7960 return uOp->getSubExpr()->getType();
7961 }
7962 // Technically, there should be a check for array subscript
7963 // expressions here, but the result of one is always an lvalue anyway.
7964 }
John McCall5808ce42011-02-03 08:15:49 +00007965 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007966 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007967 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007968
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007969 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007970 bool sfinae = S.isSFINAEContext();
7971 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7972 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007973 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007974 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007975 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007976 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007977 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007978 } else if (lval == Expr::LV_MemberFunction) {
7979 // If it's an instance method, make a member pointer.
7980 // The expression must have exactly the form &A::foo.
7981
7982 // If the underlying expression isn't a decl ref, give up.
7983 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007984 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007985 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007986 return QualType();
7987 }
7988 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7989 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7990
7991 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007992 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007993 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007994 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007995
7996 // The method was named without a qualifier.
7997 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007998 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007999 << op->getSourceRange();
8000 }
8001
John McCall09431682010-11-18 19:01:18 +00008002 return S.Context.getMemberPointerType(op->getType(),
8003 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008004 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008005 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008006 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008007 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008008 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008009 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008010 AddressOfError = AO_Property_Expansion;
8011 } else {
8012 // FIXME: emit more specific diag...
8013 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8014 << op->getSourceRange();
8015 return QualType();
8016 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008017 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008018 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008019 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008020 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008021 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008022 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008023 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008024 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008025 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008026 // with the register storage-class specifier.
8027 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008028 // in C++ it is not error to take address of a register
8029 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008030 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008031 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008032 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008033 }
John McCallba135432009-11-21 08:51:07 +00008034 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008035 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008036 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008037 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008038 // Could be a pointer to member, though, if there is an explicit
8039 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008040 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008041 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008042 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008043 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008044 S.Diag(OpLoc,
8045 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008046 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008047 return QualType();
8048 }
Mike Stump1eb44332009-09-09 15:08:12 +00008049
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008050 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8051 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008052 return S.Context.getMemberPointerType(op->getType(),
8053 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008054 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008055 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008056 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008057 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008058 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008059
Richard Trieu5520f232011-09-07 21:46:33 +00008060 if (AddressOfError != AO_No_Error) {
8061 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8062 return QualType();
8063 }
8064
Eli Friedman441cf102009-05-16 23:27:50 +00008065 if (lval == Expr::LV_IncompleteVoidType) {
8066 // Taking the address of a void variable is technically illegal, but we
8067 // allow it in cases which are otherwise valid.
8068 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008069 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008070 }
8071
Reid Spencer5f016e22007-07-11 17:01:13 +00008072 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008073 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008074 return S.Context.getObjCObjectPointerType(op->getType());
8075 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008076}
8077
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008078/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008079static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8080 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008081 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008082 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008083
John Wiegley429bb272011-04-08 18:41:53 +00008084 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8085 if (ConvResult.isInvalid())
8086 return QualType();
8087 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008088 QualType OpTy = Op->getType();
8089 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008090
8091 if (isa<CXXReinterpretCastExpr>(Op)) {
8092 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8093 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8094 Op->getSourceRange());
8095 }
8096
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008097 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8098 // is an incomplete type or void. It would be possible to warn about
8099 // dereferencing a void pointer, but it's completely well-defined, and such a
8100 // warning is unlikely to catch any mistakes.
8101 if (const PointerType *PT = OpTy->getAs<PointerType>())
8102 Result = PT->getPointeeType();
8103 else if (const ObjCObjectPointerType *OPT =
8104 OpTy->getAs<ObjCObjectPointerType>())
8105 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008106 else {
John McCallfb8721c2011-04-10 19:13:55 +00008107 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008108 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008109 if (PR.take() != Op)
8110 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008111 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008112
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008113 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008114 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008115 << OpTy << Op->getSourceRange();
8116 return QualType();
8117 }
John McCall09431682010-11-18 19:01:18 +00008118
8119 // Dereferences are usually l-values...
8120 VK = VK_LValue;
8121
8122 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008123 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008124 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008125
8126 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008127}
8128
John McCall2de56d12010-08-25 11:45:40 +00008129static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008130 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008131 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008132 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008133 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008134 case tok::periodstar: Opc = BO_PtrMemD; break;
8135 case tok::arrowstar: Opc = BO_PtrMemI; break;
8136 case tok::star: Opc = BO_Mul; break;
8137 case tok::slash: Opc = BO_Div; break;
8138 case tok::percent: Opc = BO_Rem; break;
8139 case tok::plus: Opc = BO_Add; break;
8140 case tok::minus: Opc = BO_Sub; break;
8141 case tok::lessless: Opc = BO_Shl; break;
8142 case tok::greatergreater: Opc = BO_Shr; break;
8143 case tok::lessequal: Opc = BO_LE; break;
8144 case tok::less: Opc = BO_LT; break;
8145 case tok::greaterequal: Opc = BO_GE; break;
8146 case tok::greater: Opc = BO_GT; break;
8147 case tok::exclaimequal: Opc = BO_NE; break;
8148 case tok::equalequal: Opc = BO_EQ; break;
8149 case tok::amp: Opc = BO_And; break;
8150 case tok::caret: Opc = BO_Xor; break;
8151 case tok::pipe: Opc = BO_Or; break;
8152 case tok::ampamp: Opc = BO_LAnd; break;
8153 case tok::pipepipe: Opc = BO_LOr; break;
8154 case tok::equal: Opc = BO_Assign; break;
8155 case tok::starequal: Opc = BO_MulAssign; break;
8156 case tok::slashequal: Opc = BO_DivAssign; break;
8157 case tok::percentequal: Opc = BO_RemAssign; break;
8158 case tok::plusequal: Opc = BO_AddAssign; break;
8159 case tok::minusequal: Opc = BO_SubAssign; break;
8160 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8161 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8162 case tok::ampequal: Opc = BO_AndAssign; break;
8163 case tok::caretequal: Opc = BO_XorAssign; break;
8164 case tok::pipeequal: Opc = BO_OrAssign; break;
8165 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008166 }
8167 return Opc;
8168}
8169
John McCall2de56d12010-08-25 11:45:40 +00008170static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008171 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008172 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008173 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008174 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008175 case tok::plusplus: Opc = UO_PreInc; break;
8176 case tok::minusminus: Opc = UO_PreDec; break;
8177 case tok::amp: Opc = UO_AddrOf; break;
8178 case tok::star: Opc = UO_Deref; break;
8179 case tok::plus: Opc = UO_Plus; break;
8180 case tok::minus: Opc = UO_Minus; break;
8181 case tok::tilde: Opc = UO_Not; break;
8182 case tok::exclaim: Opc = UO_LNot; break;
8183 case tok::kw___real: Opc = UO_Real; break;
8184 case tok::kw___imag: Opc = UO_Imag; break;
8185 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008186 }
8187 return Opc;
8188}
8189
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008190/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8191/// This warning is only emitted for builtin assignment operations. It is also
8192/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008193static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008194 SourceLocation OpLoc) {
8195 if (!S.ActiveTemplateInstantiations.empty())
8196 return;
8197 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8198 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008199 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8200 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8201 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8202 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8203 if (!LHSDeclRef || !RHSDeclRef ||
8204 LHSDeclRef->getLocation().isMacroID() ||
8205 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008206 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008207 const ValueDecl *LHSDecl =
8208 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8209 const ValueDecl *RHSDecl =
8210 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8211 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008212 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008213 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008214 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008215 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008216 if (RefTy->getPointeeType().isVolatileQualified())
8217 return;
8218
8219 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008220 << LHSDeclRef->getType()
8221 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008222}
8223
Douglas Gregoreaebc752008-11-06 23:29:22 +00008224/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8225/// operator @p Opc at location @c TokLoc. This routine only supports
8226/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008227ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008228 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008229 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008230 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008231 // The syntax only allows initializer lists on the RHS of assignment,
8232 // so we don't need to worry about accepting invalid code for
8233 // non-assignment operators.
8234 // C++11 5.17p9:
8235 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8236 // of x = {} is x = T().
8237 InitializationKind Kind =
8238 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8239 InitializedEntity Entity =
8240 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8241 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008242 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008243 if (Init.isInvalid())
8244 return Init;
8245 RHSExpr = Init.take();
8246 }
8247
Richard Trieu78ea78b2011-09-07 01:49:20 +00008248 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008249 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008250 // The following two variables are used for compound assignment operators
8251 QualType CompLHSTy; // Type of LHS after promotions for computation
8252 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008253 ExprValueKind VK = VK_RValue;
8254 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008255
8256 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008257 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008258 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008259 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008260 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8261 VK = LHS.get()->getValueKind();
8262 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008263 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008264 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008265 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008266 break;
John McCall2de56d12010-08-25 11:45:40 +00008267 case BO_PtrMemD:
8268 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008269 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008270 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008271 break;
John McCall2de56d12010-08-25 11:45:40 +00008272 case BO_Mul:
8273 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008274 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008275 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008276 break;
John McCall2de56d12010-08-25 11:45:40 +00008277 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008278 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008279 break;
John McCall2de56d12010-08-25 11:45:40 +00008280 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008281 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008282 break;
John McCall2de56d12010-08-25 11:45:40 +00008283 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008284 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008285 break;
John McCall2de56d12010-08-25 11:45:40 +00008286 case BO_Shl:
8287 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008288 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008289 break;
John McCall2de56d12010-08-25 11:45:40 +00008290 case BO_LE:
8291 case BO_LT:
8292 case BO_GE:
8293 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008294 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008295 break;
John McCall2de56d12010-08-25 11:45:40 +00008296 case BO_EQ:
8297 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008298 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008299 break;
John McCall2de56d12010-08-25 11:45:40 +00008300 case BO_And:
8301 case BO_Xor:
8302 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008303 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008304 break;
John McCall2de56d12010-08-25 11:45:40 +00008305 case BO_LAnd:
8306 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008307 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008308 break;
John McCall2de56d12010-08-25 11:45:40 +00008309 case BO_MulAssign:
8310 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008311 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008312 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008313 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008314 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8315 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008316 break;
John McCall2de56d12010-08-25 11:45:40 +00008317 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008318 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008319 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008320 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8321 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008322 break;
John McCall2de56d12010-08-25 11:45:40 +00008323 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008324 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008325 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8326 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008327 break;
John McCall2de56d12010-08-25 11:45:40 +00008328 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008329 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8330 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8331 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008332 break;
John McCall2de56d12010-08-25 11:45:40 +00008333 case BO_ShlAssign:
8334 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008335 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008336 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008337 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008339 break;
John McCall2de56d12010-08-25 11:45:40 +00008340 case BO_AndAssign:
8341 case BO_XorAssign:
8342 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008343 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008344 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008345 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8346 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008347 break;
John McCall2de56d12010-08-25 11:45:40 +00008348 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008349 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008350 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008351 VK = RHS.get()->getValueKind();
8352 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008353 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008354 break;
8355 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008356 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008357 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008358
8359 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008360 CheckArrayAccess(LHS.get());
8361 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008362
Eli Friedmanab3a8522009-03-28 01:22:36 +00008363 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008364 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008365 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008366 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008367 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008368 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008369 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008370 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008371 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008372 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008373 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008374}
8375
Sebastian Redlaee3c932009-10-27 12:10:02 +00008376/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8377/// operators are mixed in a way that suggests that the programmer forgot that
8378/// comparison operators have higher precedence. The most typical example of
8379/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008380static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008381 SourceLocation OpLoc, Expr *LHSExpr,
8382 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008383 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008384 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8385 RHSopc = static_cast<BinOp::Opcode>(-1);
8386 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8387 LHSopc = BO->getOpcode();
8388 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8389 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008390
8391 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008392 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008393 return;
8394
8395 // Bitwise operations are sometimes used as eager logical ops.
8396 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008397 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8398 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008399 return;
8400
Richard Trieu78ea78b2011-09-07 01:49:20 +00008401 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8402 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008403 if (!isLeftComp && !isRightComp) return;
8404
Richard Trieu78ea78b2011-09-07 01:49:20 +00008405 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8406 OpLoc)
8407 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8408 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8409 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008410 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008411 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8412 RHSExpr->getLocEnd())
8413 : SourceRange(LHSExpr->getLocStart(),
8414 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008415
8416 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8417 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8418 SuggestParentheses(Self, OpLoc,
8419 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008420 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008421 SuggestParentheses(Self, OpLoc,
8422 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8423 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008424}
8425
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008426/// \brief It accepts a '&' expr that is inside a '|' one.
8427/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8428/// in parentheses.
8429static void
8430EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8431 BinaryOperator *Bop) {
8432 assert(Bop->getOpcode() == BO_And);
8433 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8434 << Bop->getSourceRange() << OpLoc;
8435 SuggestParentheses(Self, Bop->getOperatorLoc(),
8436 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8437 Bop->getSourceRange());
8438}
8439
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008440/// \brief It accepts a '&&' expr that is inside a '||' one.
8441/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8442/// in parentheses.
8443static void
8444EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008445 BinaryOperator *Bop) {
8446 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008447 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8448 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008449 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008450 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008451 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008452}
8453
8454/// \brief Returns true if the given expression can be evaluated as a constant
8455/// 'true'.
8456static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8457 bool Res;
8458 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8459}
8460
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008461/// \brief Returns true if the given expression can be evaluated as a constant
8462/// 'false'.
8463static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8464 bool Res;
8465 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8466}
8467
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008468/// \brief Look for '&&' in the left hand of a '||' expr.
8469static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008470 Expr *LHSExpr, Expr *RHSExpr) {
8471 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008472 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008473 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008474 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008475 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008476 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8477 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8478 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8479 } else if (Bop->getOpcode() == BO_LOr) {
8480 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8481 // If it's "a || b && 1 || c" we didn't warn earlier for
8482 // "a || b && 1", but warn now.
8483 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8484 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8485 }
8486 }
8487 }
8488}
8489
8490/// \brief Look for '&&' in the right hand of a '||' expr.
8491static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008492 Expr *LHSExpr, Expr *RHSExpr) {
8493 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008494 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008495 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008496 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008497 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008498 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8499 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8500 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008501 }
8502 }
8503}
8504
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008505/// \brief Look for '&' in the left or right hand of a '|' expr.
8506static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8507 Expr *OrArg) {
8508 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8509 if (Bop->getOpcode() == BO_And)
8510 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8511 }
8512}
8513
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008514/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008515/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008516static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008517 SourceLocation OpLoc, Expr *LHSExpr,
8518 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008519 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008520 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008521 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008522
8523 // Diagnose "arg1 & arg2 | arg3"
8524 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008525 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8526 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008527 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008528
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008529 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8530 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008531 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008532 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8533 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008534 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008535}
8536
Reid Spencer5f016e22007-07-11 17:01:13 +00008537// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008538ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008539 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008540 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008541 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008542 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8543 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008544
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008545 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008546 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008547
Richard Trieubefece12011-09-07 02:02:10 +00008548 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008549}
8550
John McCall3c3b7f92011-10-25 17:37:35 +00008551/// Build an overloaded binary operator expression in the given scope.
8552static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8553 BinaryOperatorKind Opc,
8554 Expr *LHS, Expr *RHS) {
8555 // Find all of the overloaded operators visible from this
8556 // point. We perform both an operator-name lookup from the local
8557 // scope and an argument-dependent lookup based on the types of
8558 // the arguments.
8559 UnresolvedSet<16> Functions;
8560 OverloadedOperatorKind OverOp
8561 = BinaryOperator::getOverloadedOperator(Opc);
8562 if (Sc && OverOp != OO_None)
8563 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8564 RHS->getType(), Functions);
8565
8566 // Build the (potentially-overloaded, potentially-dependent)
8567 // binary operation.
8568 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8569}
8570
John McCall60d7b3a2010-08-24 06:29:42 +00008571ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008572 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008573 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008574 // We want to end up calling one of checkPseudoObjectAssignment
8575 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8576 // both expressions are overloadable or either is type-dependent),
8577 // or CreateBuiltinBinOp (in any other case). We also want to get
8578 // any placeholder types out of the way.
8579
John McCall3c3b7f92011-10-25 17:37:35 +00008580 // Handle pseudo-objects in the LHS.
8581 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8582 // Assignments with a pseudo-object l-value need special analysis.
8583 if (pty->getKind() == BuiltinType::PseudoObject &&
8584 BinaryOperator::isAssignmentOp(Opc))
8585 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8586
8587 // Don't resolve overloads if the other type is overloadable.
8588 if (pty->getKind() == BuiltinType::Overload) {
8589 // We can't actually test that if we still have a placeholder,
8590 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008591 // code below are valid when the LHS is an overload set. Note
8592 // that an overload set can be dependently-typed, but it never
8593 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008594 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8595 if (resolvedRHS.isInvalid()) return ExprError();
8596 RHSExpr = resolvedRHS.take();
8597
John McCallac516502011-10-28 01:04:34 +00008598 if (RHSExpr->isTypeDependent() ||
8599 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008600 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8601 }
8602
8603 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8604 if (LHS.isInvalid()) return ExprError();
8605 LHSExpr = LHS.take();
8606 }
8607
8608 // Handle pseudo-objects in the RHS.
8609 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8610 // An overload in the RHS can potentially be resolved by the type
8611 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008612 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8613 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8614 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8615
Eli Friedman87884912012-01-17 21:27:43 +00008616 if (LHSExpr->getType()->isOverloadableType())
8617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8618
John McCall3c3b7f92011-10-25 17:37:35 +00008619 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008620 }
John McCall3c3b7f92011-10-25 17:37:35 +00008621
8622 // Don't resolve overloads if the other type is overloadable.
8623 if (pty->getKind() == BuiltinType::Overload &&
8624 LHSExpr->getType()->isOverloadableType())
8625 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8626
8627 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8628 if (!resolvedRHS.isUsable()) return ExprError();
8629 RHSExpr = resolvedRHS.take();
8630 }
8631
David Blaikie4e4d0842012-03-11 07:00:24 +00008632 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008633 // If either expression is type-dependent, always build an
8634 // overloaded op.
8635 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8636 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008637
John McCallac516502011-10-28 01:04:34 +00008638 // Otherwise, build an overloaded op if either expression has an
8639 // overloadable type.
8640 if (LHSExpr->getType()->isOverloadableType() ||
8641 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008642 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008643 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008644
Douglas Gregoreaebc752008-11-06 23:29:22 +00008645 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008646 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008647}
8648
John McCall60d7b3a2010-08-24 06:29:42 +00008649ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008650 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008651 Expr *InputExpr) {
8652 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008653 ExprValueKind VK = VK_RValue;
8654 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008655 QualType resultType;
8656 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008657 case UO_PreInc:
8658 case UO_PreDec:
8659 case UO_PostInc:
8660 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008661 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008662 Opc == UO_PreInc ||
8663 Opc == UO_PostInc,
8664 Opc == UO_PreInc ||
8665 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008666 break;
John McCall2de56d12010-08-25 11:45:40 +00008667 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008668 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008669 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008670 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008671 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008672 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008673 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008674 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008675 }
John McCall2de56d12010-08-25 11:45:40 +00008676 case UO_Plus:
8677 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008678 Input = UsualUnaryConversions(Input.take());
8679 if (Input.isInvalid()) return ExprError();
8680 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008681 if (resultType->isDependentType())
8682 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008683 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8684 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008685 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008686 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008687 resultType->isEnumeralType())
8688 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008689 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008690 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008691 resultType->isPointerType())
8692 break;
8693
Sebastian Redl0eb23302009-01-19 00:08:26 +00008694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008695 << resultType << Input.get()->getSourceRange());
8696
John McCall2de56d12010-08-25 11:45:40 +00008697 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008698 Input = UsualUnaryConversions(Input.take());
8699 if (Input.isInvalid()) return ExprError();
8700 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008701 if (resultType->isDependentType())
8702 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008703 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8704 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8705 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008706 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008707 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008708 else if (resultType->hasIntegerRepresentation())
8709 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008710 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008712 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008713 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008714 break;
John Wiegley429bb272011-04-08 18:41:53 +00008715
John McCall2de56d12010-08-25 11:45:40 +00008716 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008717 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008718 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8719 if (Input.isInvalid()) return ExprError();
8720 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008721
8722 // Though we still have to promote half FP to float...
8723 if (resultType->isHalfType()) {
8724 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8725 resultType = Context.FloatTy;
8726 }
8727
Sebastian Redl28507842009-02-26 14:39:58 +00008728 if (resultType->isDependentType())
8729 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008730 if (resultType->isScalarType()) {
8731 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008732 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008733 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8734 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008735 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8736 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008737 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008738 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008739 // Vector logical not returns the signed variant of the operand type.
8740 resultType = GetSignedVectorType(resultType);
8741 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008742 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008743 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008744 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008745 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008746
Reid Spencer5f016e22007-07-11 17:01:13 +00008747 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008748 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008749 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008750 break;
John McCall2de56d12010-08-25 11:45:40 +00008751 case UO_Real:
8752 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008753 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008754 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8755 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008756 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008757 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8758 if (Input.get()->getValueKind() != VK_RValue &&
8759 Input.get()->getObjectKind() == OK_Ordinary)
8760 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008761 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008762 // In C, a volatile scalar is read by __imag. In C++, it is not.
8763 Input = DefaultLvalueConversion(Input.take());
8764 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008765 break;
John McCall2de56d12010-08-25 11:45:40 +00008766 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008767 resultType = Input.get()->getType();
8768 VK = Input.get()->getValueKind();
8769 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008770 break;
8771 }
John Wiegley429bb272011-04-08 18:41:53 +00008772 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008773 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008774
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008775 // Check for array bounds violations in the operand of the UnaryOperator,
8776 // except for the '*' and '&' operators that have to be handled specially
8777 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8778 // that are explicitly defined as valid by the standard).
8779 if (Opc != UO_AddrOf && Opc != UO_Deref)
8780 CheckArrayAccess(Input.get());
8781
John Wiegley429bb272011-04-08 18:41:53 +00008782 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008783 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008784}
8785
Douglas Gregord3d08532011-12-14 21:23:13 +00008786/// \brief Determine whether the given expression is a qualified member
8787/// access expression, of a form that could be turned into a pointer to member
8788/// with the address-of operator.
8789static bool isQualifiedMemberAccess(Expr *E) {
8790 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8791 if (!DRE->getQualifier())
8792 return false;
8793
8794 ValueDecl *VD = DRE->getDecl();
8795 if (!VD->isCXXClassMember())
8796 return false;
8797
8798 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8799 return true;
8800 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8801 return Method->isInstance();
8802
8803 return false;
8804 }
8805
8806 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8807 if (!ULE->getQualifier())
8808 return false;
8809
8810 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8811 DEnd = ULE->decls_end();
8812 D != DEnd; ++D) {
8813 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8814 if (Method->isInstance())
8815 return true;
8816 } else {
8817 // Overload set does not contain methods.
8818 break;
8819 }
8820 }
8821
8822 return false;
8823 }
8824
8825 return false;
8826}
8827
John McCall60d7b3a2010-08-24 06:29:42 +00008828ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008829 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008830 // First things first: handle placeholders so that the
8831 // overloaded-operator check considers the right type.
8832 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8833 // Increment and decrement of pseudo-object references.
8834 if (pty->getKind() == BuiltinType::PseudoObject &&
8835 UnaryOperator::isIncrementDecrementOp(Opc))
8836 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8837
8838 // extension is always a builtin operator.
8839 if (Opc == UO_Extension)
8840 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8841
8842 // & gets special logic for several kinds of placeholder.
8843 // The builtin code knows what to do.
8844 if (Opc == UO_AddrOf &&
8845 (pty->getKind() == BuiltinType::Overload ||
8846 pty->getKind() == BuiltinType::UnknownAny ||
8847 pty->getKind() == BuiltinType::BoundMember))
8848 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8849
8850 // Anything else needs to be handled now.
8851 ExprResult Result = CheckPlaceholderExpr(Input);
8852 if (Result.isInvalid()) return ExprError();
8853 Input = Result.take();
8854 }
8855
David Blaikie4e4d0842012-03-11 07:00:24 +00008856 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008857 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8858 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008859 // Find all of the overloaded operators visible from this
8860 // point. We perform both an operator-name lookup from the local
8861 // scope and an argument-dependent lookup based on the types of
8862 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008863 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008864 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008865 if (S && OverOp != OO_None)
8866 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8867 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008868
John McCall9ae2f072010-08-23 23:25:46 +00008869 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008870 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008871
John McCall9ae2f072010-08-23 23:25:46 +00008872 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008873}
8874
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008875// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008876ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008877 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008878 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008879}
8880
Steve Naroff1b273c42007-09-16 14:56:35 +00008881/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008882ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008883 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008884 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008885 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008886 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008887 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008888}
8889
John McCallf85e1932011-06-15 23:02:42 +00008890/// Given the last statement in a statement-expression, check whether
8891/// the result is a producing expression (like a call to an
8892/// ns_returns_retained function) and, if so, rebuild it to hoist the
8893/// release out of the full-expression. Otherwise, return null.
8894/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008895static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008896 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008897 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008898 if (!cleanups) return 0;
8899
8900 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008901 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008902 return 0;
8903
8904 // Splice out the cast. This shouldn't modify any interesting
8905 // features of the statement.
8906 Expr *producer = cast->getSubExpr();
8907 assert(producer->getType() == cast->getType());
8908 assert(producer->getValueKind() == cast->getValueKind());
8909 cleanups->setSubExpr(producer);
8910 return cleanups;
8911}
8912
John McCall73f428c2012-04-04 01:27:53 +00008913void Sema::ActOnStartStmtExpr() {
8914 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8915}
8916
8917void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008918 // Note that function is also called by TreeTransform when leaving a
8919 // StmtExpr scope without rebuilding anything.
8920
John McCall73f428c2012-04-04 01:27:53 +00008921 DiscardCleanupsInEvaluationContext();
8922 PopExpressionEvaluationContext();
8923}
8924
John McCall60d7b3a2010-08-24 06:29:42 +00008925ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008926Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008927 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008928 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8929 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8930
John McCall73f428c2012-04-04 01:27:53 +00008931 if (hasAnyUnrecoverableErrorsInThisFunction())
8932 DiscardCleanupsInEvaluationContext();
8933 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8934 PopExpressionEvaluationContext();
8935
Douglas Gregordd8f5692010-03-10 04:54:39 +00008936 bool isFileScope
8937 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008938 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008939 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008940
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008941 // FIXME: there are a variety of strange constraints to enforce here, for
8942 // example, it is not possible to goto into a stmt expression apparently.
8943 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008944
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008945 // If there are sub stmts in the compound stmt, take the type of the last one
8946 // as the type of the stmtexpr.
8947 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008948 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008949 if (!Compound->body_empty()) {
8950 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008951 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008952 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008953 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8954 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008955 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008956 }
John McCallf85e1932011-06-15 23:02:42 +00008957
John Wiegley429bb272011-04-08 18:41:53 +00008958 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008959 // Do function/array conversion on the last expression, but not
8960 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008961 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8962 if (LastExpr.isInvalid())
8963 return ExprError();
8964 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008965
John Wiegley429bb272011-04-08 18:41:53 +00008966 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008967 // In ARC, if the final expression ends in a consume, splice
8968 // the consume out and bind it later. In the alternate case
8969 // (when dealing with a retainable type), the result
8970 // initialization will create a produce. In both cases the
8971 // result will be +1, and we'll need to balance that out with
8972 // a bind.
8973 if (Expr *rebuiltLastStmt
8974 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8975 LastExpr = rebuiltLastStmt;
8976 } else {
8977 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008978 InitializedEntity::InitializeResult(LPLoc,
8979 Ty,
8980 false),
8981 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008982 LastExpr);
8983 }
8984
John Wiegley429bb272011-04-08 18:41:53 +00008985 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008986 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008987 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008988 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008989 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008990 else
John Wiegley429bb272011-04-08 18:41:53 +00008991 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008992 StmtExprMayBindToTemp = true;
8993 }
8994 }
8995 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008996 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008997
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008998 // FIXME: Check that expression type is complete/non-abstract; statement
8999 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009000 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9001 if (StmtExprMayBindToTemp)
9002 return MaybeBindToTemporary(ResStmtExpr);
9003 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009004}
Steve Naroffd34e9152007-08-01 22:05:33 +00009005
John McCall60d7b3a2010-08-24 06:29:42 +00009006ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009007 TypeSourceInfo *TInfo,
9008 OffsetOfComponent *CompPtr,
9009 unsigned NumComponents,
9010 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009011 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009012 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009013 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009014
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009015 // We must have at least one component that refers to the type, and the first
9016 // one is known to be a field designator. Verify that the ArgTy represents
9017 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009018 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009019 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9020 << ArgTy << TypeRange);
9021
9022 // Type must be complete per C99 7.17p3 because a declaring a variable
9023 // with an incomplete type would be ill-formed.
9024 if (!Dependent
9025 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009026 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009027 return ExprError();
9028
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009029 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9030 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009031 // FIXME: This diagnostic isn't actually visible because the location is in
9032 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009033 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009034 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9035 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009036
9037 bool DidWarnAboutNonPOD = false;
9038 QualType CurrentType = ArgTy;
9039 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009040 SmallVector<OffsetOfNode, 4> Comps;
9041 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009042 for (unsigned i = 0; i != NumComponents; ++i) {
9043 const OffsetOfComponent &OC = CompPtr[i];
9044 if (OC.isBrackets) {
9045 // Offset of an array sub-field. TODO: Should we allow vector elements?
9046 if (!CurrentType->isDependentType()) {
9047 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9048 if(!AT)
9049 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9050 << CurrentType);
9051 CurrentType = AT->getElementType();
9052 } else
9053 CurrentType = Context.DependentTy;
9054
Richard Smithea011432011-10-17 23:29:39 +00009055 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9056 if (IdxRval.isInvalid())
9057 return ExprError();
9058 Expr *Idx = IdxRval.take();
9059
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009060 // The expression must be an integral expression.
9061 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009062 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9063 !Idx->getType()->isIntegerType())
9064 return ExprError(Diag(Idx->getLocStart(),
9065 diag::err_typecheck_subscript_not_integer)
9066 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009067
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009068 // Record this array index.
9069 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009070 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009071 continue;
9072 }
9073
9074 // Offset of a field.
9075 if (CurrentType->isDependentType()) {
9076 // We have the offset of a field, but we can't look into the dependent
9077 // type. Just record the identifier of the field.
9078 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9079 CurrentType = Context.DependentTy;
9080 continue;
9081 }
9082
9083 // We need to have a complete type to look into.
9084 if (RequireCompleteType(OC.LocStart, CurrentType,
9085 diag::err_offsetof_incomplete_type))
9086 return ExprError();
9087
9088 // Look for the designated field.
9089 const RecordType *RC = CurrentType->getAs<RecordType>();
9090 if (!RC)
9091 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9092 << CurrentType);
9093 RecordDecl *RD = RC->getDecl();
9094
9095 // C++ [lib.support.types]p5:
9096 // The macro offsetof accepts a restricted set of type arguments in this
9097 // International Standard. type shall be a POD structure or a POD union
9098 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009099 // C++11 [support.types]p4:
9100 // If type is not a standard-layout class (Clause 9), the results are
9101 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009102 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009103 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9104 unsigned DiagID =
9105 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9106 : diag::warn_offsetof_non_pod_type;
9107
9108 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009109 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009110 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009111 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9112 << CurrentType))
9113 DidWarnAboutNonPOD = true;
9114 }
9115
9116 // Look for the field.
9117 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9118 LookupQualifiedName(R, RD);
9119 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009120 IndirectFieldDecl *IndirectMemberDecl = 0;
9121 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009122 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009123 MemberDecl = IndirectMemberDecl->getAnonField();
9124 }
9125
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009126 if (!MemberDecl)
9127 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9128 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9129 OC.LocEnd));
9130
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009131 // C99 7.17p3:
9132 // (If the specified member is a bit-field, the behavior is undefined.)
9133 //
9134 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009135 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009136 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9137 << MemberDecl->getDeclName()
9138 << SourceRange(BuiltinLoc, RParenLoc);
9139 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9140 return ExprError();
9141 }
Eli Friedman19410a72010-08-05 10:11:36 +00009142
9143 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009144 if (IndirectMemberDecl)
9145 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009146
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009147 // If the member was found in a base class, introduce OffsetOfNodes for
9148 // the base class indirections.
9149 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9150 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009151 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009152 CXXBasePath &Path = Paths.front();
9153 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9154 B != BEnd; ++B)
9155 Comps.push_back(OffsetOfNode(B->Base));
9156 }
Eli Friedman19410a72010-08-05 10:11:36 +00009157
Francois Pichet87c2e122010-11-21 06:08:52 +00009158 if (IndirectMemberDecl) {
9159 for (IndirectFieldDecl::chain_iterator FI =
9160 IndirectMemberDecl->chain_begin(),
9161 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9162 assert(isa<FieldDecl>(*FI));
9163 Comps.push_back(OffsetOfNode(OC.LocStart,
9164 cast<FieldDecl>(*FI), OC.LocEnd));
9165 }
9166 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009167 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009168
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009169 CurrentType = MemberDecl->getType().getNonReferenceType();
9170 }
9171
9172 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009173 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009174}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009175
John McCall60d7b3a2010-08-24 06:29:42 +00009176ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009177 SourceLocation BuiltinLoc,
9178 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009179 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009180 OffsetOfComponent *CompPtr,
9181 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009182 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009183
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009184 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009185 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009186 if (ArgTy.isNull())
9187 return ExprError();
9188
Eli Friedman5a15dc12010-08-05 10:15:45 +00009189 if (!ArgTInfo)
9190 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9191
9192 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009193 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009194}
9195
9196
John McCall60d7b3a2010-08-24 06:29:42 +00009197ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009198 Expr *CondExpr,
9199 Expr *LHSExpr, Expr *RHSExpr,
9200 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009201 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9202
John McCallf89e55a2010-11-18 06:31:45 +00009203 ExprValueKind VK = VK_RValue;
9204 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009205 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009206 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009207 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009208 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009209 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009210 } else {
9211 // The conditional expression is required to be a constant expression.
9212 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009213 ExprResult CondICE
9214 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9215 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009216 if (CondICE.isInvalid())
9217 return ExprError();
9218 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009219
Sebastian Redl28507842009-02-26 14:39:58 +00009220 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009221 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9222
9223 resType = ActiveExpr->getType();
9224 ValueDependent = ActiveExpr->isValueDependent();
9225 VK = ActiveExpr->getValueKind();
9226 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009227 }
9228
Sebastian Redlf53597f2009-03-15 17:47:39 +00009229 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009230 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009231 resType->isDependentType(),
9232 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009233}
9234
Steve Naroff4eb206b2008-09-03 18:15:37 +00009235//===----------------------------------------------------------------------===//
9236// Clang Extensions.
9237//===----------------------------------------------------------------------===//
9238
9239/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009240void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009241 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009242 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009243 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009244 if (CurScope)
9245 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009246 else
9247 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009248
Eli Friedman84b007f2012-01-26 03:00:14 +00009249 getCurBlock()->HasImplicitReturnType = true;
9250
John McCall538773c2011-11-11 03:19:12 +00009251 // Enter a new evaluation context to insulate the block from any
9252 // cleanups from the enclosing full-expression.
9253 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009254}
9255
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009256void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9257 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009258 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009259 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009260 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009261
John McCallbf1a0282010-06-04 23:28:52 +00009262 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009263 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009264
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009265 // FIXME: We should allow unexpanded parameter packs here, but that would,
9266 // in turn, make the block expression contain unexpanded parameter packs.
9267 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9268 // Drop the parameters.
9269 FunctionProtoType::ExtProtoInfo EPI;
9270 EPI.HasTrailingReturn = false;
9271 EPI.TypeQuals |= DeclSpec::TQ_const;
9272 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9273 EPI);
9274 Sig = Context.getTrivialTypeSourceInfo(T);
9275 }
9276
John McCall711c52b2011-01-05 12:14:39 +00009277 // GetTypeForDeclarator always produces a function type for a block
9278 // literal signature. Furthermore, it is always a FunctionProtoType
9279 // unless the function was written with a typedef.
9280 assert(T->isFunctionType() &&
9281 "GetTypeForDeclarator made a non-function block signature");
9282
9283 // Look for an explicit signature in that function type.
9284 FunctionProtoTypeLoc ExplicitSignature;
9285
9286 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9287 if (isa<FunctionProtoTypeLoc>(tmp)) {
9288 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9289
9290 // Check whether that explicit signature was synthesized by
9291 // GetTypeForDeclarator. If so, don't save that as part of the
9292 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009293 if (ExplicitSignature.getLocalRangeBegin() ==
9294 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009295 // This would be much cheaper if we stored TypeLocs instead of
9296 // TypeSourceInfos.
9297 TypeLoc Result = ExplicitSignature.getResultLoc();
9298 unsigned Size = Result.getFullDataSize();
9299 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9300 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9301
9302 ExplicitSignature = FunctionProtoTypeLoc();
9303 }
John McCall82dc0092010-06-04 11:21:44 +00009304 }
Mike Stump1eb44332009-09-09 15:08:12 +00009305
John McCall711c52b2011-01-05 12:14:39 +00009306 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9307 CurBlock->FunctionType = T;
9308
9309 const FunctionType *Fn = T->getAs<FunctionType>();
9310 QualType RetTy = Fn->getResultType();
9311 bool isVariadic =
9312 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9313
John McCallc71a4912010-06-04 19:02:56 +00009314 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009315
John McCall82dc0092010-06-04 11:21:44 +00009316 // Don't allow returning a objc interface by value.
9317 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009318 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009319 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9320 return;
9321 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009322
John McCall82dc0092010-06-04 11:21:44 +00009323 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009324 // return type. TODO: what should we do with declarators like:
9325 // ^ * { ... }
9326 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009327 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009328 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009329 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009330 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009331 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009332
John McCall82dc0092010-06-04 11:21:44 +00009333 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009334 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009335 if (ExplicitSignature) {
9336 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9337 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009338 if (Param->getIdentifier() == 0 &&
9339 !Param->isImplicit() &&
9340 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009341 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009342 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009343 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009344 }
John McCall82dc0092010-06-04 11:21:44 +00009345
9346 // Fake up parameter variables if we have a typedef, like
9347 // ^ fntype { ... }
9348 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9349 for (FunctionProtoType::arg_type_iterator
9350 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9351 ParmVarDecl *Param =
9352 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009353 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009354 *I);
John McCallc71a4912010-06-04 19:02:56 +00009355 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009356 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009357 }
John McCall82dc0092010-06-04 11:21:44 +00009358
John McCallc71a4912010-06-04 19:02:56 +00009359 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009360 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009361 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009362 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9363 CurBlock->TheDecl->param_end(),
9364 /*CheckParameterNames=*/false);
9365 }
9366
John McCall82dc0092010-06-04 11:21:44 +00009367 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009368 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009369
John McCall82dc0092010-06-04 11:21:44 +00009370 // Put the parameter variables in scope. We can bail out immediately
9371 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009372 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009373 return;
9374
Steve Naroff090276f2008-10-10 01:28:17 +00009375 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009376 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9377 (*AI)->setOwningFunction(CurBlock->TheDecl);
9378
Steve Naroff090276f2008-10-10 01:28:17 +00009379 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009380 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009381 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009382
Steve Naroff090276f2008-10-10 01:28:17 +00009383 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009384 }
John McCall7a9813c2010-01-22 00:28:27 +00009385 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009386}
9387
9388/// ActOnBlockError - If there is an error parsing a block, this callback
9389/// is invoked to pop the information about the block from the action impl.
9390void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009391 // Leave the expression-evaluation context.
9392 DiscardCleanupsInEvaluationContext();
9393 PopExpressionEvaluationContext();
9394
Steve Naroff4eb206b2008-09-03 18:15:37 +00009395 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009396 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009397 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009398}
9399
9400/// ActOnBlockStmtExpr - This is called when the body of a block statement
9401/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009402ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009403 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009404 // If blocks are disabled, emit an error.
9405 if (!LangOpts.Blocks)
9406 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009407
John McCall538773c2011-11-11 03:19:12 +00009408 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009409 if (hasAnyUnrecoverableErrorsInThisFunction())
9410 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009411 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9412 PopExpressionEvaluationContext();
9413
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009414 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009415
9416 if (BSI->HasImplicitReturnType)
9417 deduceClosureReturnType(*BSI);
9418
Steve Naroff090276f2008-10-10 01:28:17 +00009419 PopDeclContext();
9420
Steve Naroff4eb206b2008-09-03 18:15:37 +00009421 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009422 if (!BSI->ReturnType.isNull())
9423 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009424
Mike Stump56925862009-07-28 22:04:01 +00009425 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009426 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009427
John McCall469a1eb2011-02-02 13:00:07 +00009428 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009429 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9430 SmallVector<BlockDecl::Capture, 4> Captures;
9431 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9432 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9433 if (Cap.isThisCapture())
9434 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009435 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009436 Cap.isNested(), Cap.getCopyExpr());
9437 Captures.push_back(NewCap);
9438 }
9439 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9440 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009441
John McCallc71a4912010-06-04 19:02:56 +00009442 // If the user wrote a function type in some form, try to use that.
9443 if (!BSI->FunctionType.isNull()) {
9444 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9445
9446 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9447 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9448
9449 // Turn protoless block types into nullary block types.
9450 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009451 FunctionProtoType::ExtProtoInfo EPI;
9452 EPI.ExtInfo = Ext;
9453 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009454
9455 // Otherwise, if we don't need to change anything about the function type,
9456 // preserve its sugar structure.
9457 } else if (FTy->getResultType() == RetTy &&
9458 (!NoReturn || FTy->getNoReturnAttr())) {
9459 BlockTy = BSI->FunctionType;
9460
9461 // Otherwise, make the minimal modifications to the function type.
9462 } else {
9463 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009464 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9465 EPI.TypeQuals = 0; // FIXME: silently?
9466 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009467 BlockTy = Context.getFunctionType(RetTy,
9468 FPT->arg_type_begin(),
9469 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009470 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009471 }
9472
9473 // If we don't have a function type, just build one from nothing.
9474 } else {
John McCalle23cf432010-12-14 08:05:40 +00009475 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009476 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009477 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009478 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009479
John McCallc71a4912010-06-04 19:02:56 +00009480 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9481 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009482 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009483
Chris Lattner17a78302009-04-19 05:28:12 +00009484 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009485 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009486 !hasAnyUnrecoverableErrorsInThisFunction() &&
9487 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009488 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009489
Chris Lattnere476bdc2011-02-17 23:58:47 +00009490 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009491
Jordan Rose7dd900e2012-07-02 21:19:23 +00009492 // Try to apply the named return value optimization. We have to check again
9493 // if we can do this, though, because blocks keep return statements around
9494 // to deduce an implicit return type.
9495 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9496 !BSI->TheDecl->isDependentContext())
9497 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009498
Benjamin Kramerd2486192011-07-12 14:11:05 +00009499 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9500 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009501 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009502
John McCall80ee6e82011-11-10 05:35:25 +00009503 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009504 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009505 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009506 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009507 ExprCleanupObjects.push_back(Result->getBlockDecl());
9508 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009509
9510 // It also gets a branch-protected scope if any of the captured
9511 // variables needs destruction.
9512 for (BlockDecl::capture_const_iterator
9513 ci = Result->getBlockDecl()->capture_begin(),
9514 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9515 const VarDecl *var = ci->getVariable();
9516 if (var->getType().isDestructedType() != QualType::DK_none) {
9517 getCurFunction()->setHasBranchProtectedScope();
9518 break;
9519 }
9520 }
John McCall80ee6e82011-11-10 05:35:25 +00009521 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009522
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009523 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009524}
9525
John McCall60d7b3a2010-08-24 06:29:42 +00009526ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009527 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009528 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009529 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009530 GetTypeFromParser(Ty, &TInfo);
9531 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009532}
9533
John McCall60d7b3a2010-08-24 06:29:42 +00009534ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009535 Expr *E, TypeSourceInfo *TInfo,
9536 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009537 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009538
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009539 // Get the va_list type
9540 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009541 if (VaListType->isArrayType()) {
9542 // Deal with implicit array decay; for example, on x86-64,
9543 // va_list is an array, but it's supposed to decay to
9544 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009545 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009546 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009547 ExprResult Result = UsualUnaryConversions(E);
9548 if (Result.isInvalid())
9549 return ExprError();
9550 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009551 } else {
9552 // Otherwise, the va_list argument must be an l-value because
9553 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009554 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009555 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009556 return ExprError();
9557 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009558
Douglas Gregordd027302009-05-19 23:10:31 +00009559 if (!E->isTypeDependent() &&
9560 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009561 return ExprError(Diag(E->getLocStart(),
9562 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009563 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009564 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009565
David Majnemer0adde122011-06-14 05:17:32 +00009566 if (!TInfo->getType()->isDependentType()) {
9567 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009568 diag::err_second_parameter_to_va_arg_incomplete,
9569 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009570 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009571
David Majnemer0adde122011-06-14 05:17:32 +00009572 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009573 TInfo->getType(),
9574 diag::err_second_parameter_to_va_arg_abstract,
9575 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009576 return ExprError();
9577
Douglas Gregor4eb75222011-07-30 06:45:27 +00009578 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009579 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009580 TInfo->getType()->isObjCLifetimeType()
9581 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9582 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009583 << TInfo->getType()
9584 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009585 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009586
9587 // Check for va_arg where arguments of the given type will be promoted
9588 // (i.e. this va_arg is guaranteed to have undefined behavior).
9589 QualType PromoteType;
9590 if (TInfo->getType()->isPromotableIntegerType()) {
9591 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9592 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9593 PromoteType = QualType();
9594 }
9595 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9596 PromoteType = Context.DoubleTy;
9597 if (!PromoteType.isNull())
9598 Diag(TInfo->getTypeLoc().getBeginLoc(),
9599 diag::warn_second_parameter_to_va_arg_never_compatible)
9600 << TInfo->getType()
9601 << PromoteType
9602 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009603 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009604
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009605 QualType T = TInfo->getType().getNonLValueExprType(Context);
9606 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009607}
9608
John McCall60d7b3a2010-08-24 06:29:42 +00009609ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009610 // The type of __null will be int or long, depending on the size of
9611 // pointers on the target.
9612 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009613 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9614 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009615 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009616 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009617 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009618 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009619 Ty = Context.LongLongTy;
9620 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009621 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009622 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009623
Sebastian Redlf53597f2009-03-15 17:47:39 +00009624 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009625}
9626
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009627static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009628 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009629 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009630 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009631
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009632 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9633 if (!PT)
9634 return;
9635
9636 // Check if the destination is of type 'id'.
9637 if (!PT->isObjCIdType()) {
9638 // Check if the destination is the 'NSString' interface.
9639 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9640 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9641 return;
9642 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009643
John McCall4b9c2d22011-11-06 09:01:30 +00009644 // Ignore any parens, implicit casts (should only be
9645 // array-to-pointer decays), and not-so-opaque values. The last is
9646 // important for making this trigger for property assignments.
9647 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9648 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9649 if (OV->getSourceExpr())
9650 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9651
9652 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009653 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009654 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009655
Douglas Gregor849b2432010-03-31 17:46:05 +00009656 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009657}
9658
Chris Lattner5cf216b2008-01-04 18:04:52 +00009659bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9660 SourceLocation Loc,
9661 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009662 Expr *SrcExpr, AssignmentAction Action,
9663 bool *Complained) {
9664 if (Complained)
9665 *Complained = false;
9666
Chris Lattner5cf216b2008-01-04 18:04:52 +00009667 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009668 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009669 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009670 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009671 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009672 ConversionFixItGenerator ConvHints;
9673 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009674 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009675
Chris Lattner5cf216b2008-01-04 18:04:52 +00009676 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009677 case Compatible:
9678 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9679 return false;
9680
Chris Lattnerb7b61152008-01-04 18:22:42 +00009681 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009682 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009683 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9684 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009685 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009686 case IntToPointer:
9687 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009688 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9689 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009690 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009691 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009692 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009693 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009694 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9695 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009696 if (Hint.isNull() && !CheckInferredResultType) {
9697 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9698 }
9699 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009700 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009701 case IncompatiblePointerSign:
9702 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9703 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009704 case FunctionVoidPointer:
9705 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9706 break;
John McCall86c05f32011-02-01 00:10:29 +00009707 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009708 // Perform array-to-pointer decay if necessary.
9709 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9710
John McCall86c05f32011-02-01 00:10:29 +00009711 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9712 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9713 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9714 DiagKind = diag::err_typecheck_incompatible_address_space;
9715 break;
John McCallf85e1932011-06-15 23:02:42 +00009716
9717
9718 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009719 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009720 break;
John McCall86c05f32011-02-01 00:10:29 +00009721 }
9722
9723 llvm_unreachable("unknown error case for discarding qualifiers!");
9724 // fallthrough
9725 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009726 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009727 // If the qualifiers lost were because we were applying the
9728 // (deprecated) C++ conversion from a string literal to a char*
9729 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9730 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009731 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009732 // bit of refactoring (so that the second argument is an
9733 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009734 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009735 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009736 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009737 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9738 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009739 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9740 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009741 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009742 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009743 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009744 case IntToBlockPointer:
9745 DiagKind = diag::err_int_to_block_pointer;
9746 break;
9747 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009748 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009749 break;
Steve Naroff39579072008-10-14 22:18:38 +00009750 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009751 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009752 // it can give a more specific diagnostic.
9753 DiagKind = diag::warn_incompatible_qualified_id;
9754 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009755 case IncompatibleVectors:
9756 DiagKind = diag::warn_incompatible_vectors;
9757 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009758 case IncompatibleObjCWeakRef:
9759 DiagKind = diag::err_arc_weak_unavailable_assign;
9760 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009761 case Incompatible:
9762 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009763 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9764 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009765 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009766 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009767 break;
9768 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009769
Douglas Gregord4eea832010-04-09 00:35:39 +00009770 QualType FirstType, SecondType;
9771 switch (Action) {
9772 case AA_Assigning:
9773 case AA_Initializing:
9774 // The destination type comes first.
9775 FirstType = DstType;
9776 SecondType = SrcType;
9777 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009778
Douglas Gregord4eea832010-04-09 00:35:39 +00009779 case AA_Returning:
9780 case AA_Passing:
9781 case AA_Converting:
9782 case AA_Sending:
9783 case AA_Casting:
9784 // The source type comes first.
9785 FirstType = SrcType;
9786 SecondType = DstType;
9787 break;
9788 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009789
Anna Zaks67221552011-07-28 19:51:27 +00009790 PartialDiagnostic FDiag = PDiag(DiagKind);
9791 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9792
9793 // If we can fix the conversion, suggest the FixIts.
9794 assert(ConvHints.isNull() || Hint.isNull());
9795 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009796 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9797 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009798 FDiag << *HI;
9799 } else {
9800 FDiag << Hint;
9801 }
9802 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9803
Richard Trieu6efd4c52011-11-23 22:32:32 +00009804 if (MayHaveFunctionDiff)
9805 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9806
Anna Zaks67221552011-07-28 19:51:27 +00009807 Diag(Loc, FDiag);
9808
Richard Trieu6efd4c52011-11-23 22:32:32 +00009809 if (SecondType == Context.OverloadTy)
9810 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9811 FirstType);
9812
Douglas Gregor926df6c2011-06-11 01:09:30 +00009813 if (CheckInferredResultType)
9814 EmitRelatedResultTypeNote(SrcExpr);
9815
Douglas Gregora41a8c52010-04-22 00:20:18 +00009816 if (Complained)
9817 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009818 return isInvalid;
9819}
Anders Carlssone21555e2008-11-30 19:50:32 +00009820
Richard Smith282e7e62012-02-04 09:53:13 +00009821ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9822 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009823 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9824 public:
9825 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9826 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9827 }
9828 } Diagnoser;
9829
9830 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9831}
9832
9833ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9834 llvm::APSInt *Result,
9835 unsigned DiagID,
9836 bool AllowFold) {
9837 class IDDiagnoser : public VerifyICEDiagnoser {
9838 unsigned DiagID;
9839
9840 public:
9841 IDDiagnoser(unsigned DiagID)
9842 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9843
9844 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9845 S.Diag(Loc, DiagID) << SR;
9846 }
9847 } Diagnoser(DiagID);
9848
9849 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9850}
9851
9852void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9853 SourceRange SR) {
9854 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009855}
9856
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009857ExprResult
9858Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009859 VerifyICEDiagnoser &Diagnoser,
9860 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009861 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009862
David Blaikie4e4d0842012-03-11 07:00:24 +00009863 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009864 // C++11 [expr.const]p5:
9865 // If an expression of literal class type is used in a context where an
9866 // integral constant expression is required, then that class type shall
9867 // have a single non-explicit conversion function to an integral or
9868 // unscoped enumeration type
9869 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009870 if (!Diagnoser.Suppress) {
9871 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9872 public:
9873 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9874
9875 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9876 QualType T) {
9877 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9878 }
9879
9880 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9881 SourceLocation Loc,
9882 QualType T) {
9883 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9884 }
9885
9886 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9887 SourceLocation Loc,
9888 QualType T,
9889 QualType ConvTy) {
9890 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9891 }
9892
9893 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9894 CXXConversionDecl *Conv,
9895 QualType ConvTy) {
9896 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9897 << ConvTy->isEnumeralType() << ConvTy;
9898 }
9899
9900 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9901 QualType T) {
9902 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9903 }
9904
9905 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9906 CXXConversionDecl *Conv,
9907 QualType ConvTy) {
9908 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9909 << ConvTy->isEnumeralType() << ConvTy;
9910 }
9911
9912 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9913 SourceLocation Loc,
9914 QualType T,
9915 QualType ConvTy) {
9916 return DiagnosticBuilder::getEmpty();
9917 }
9918 } ConvertDiagnoser;
9919
9920 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9921 ConvertDiagnoser,
9922 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009923 } else {
9924 // The caller wants to silently enquire whether this is an ICE. Don't
9925 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009926 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9927 public:
9928 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9929
9930 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9931 QualType T) {
9932 return DiagnosticBuilder::getEmpty();
9933 }
9934
9935 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9936 SourceLocation Loc,
9937 QualType T) {
9938 return DiagnosticBuilder::getEmpty();
9939 }
9940
9941 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9942 SourceLocation Loc,
9943 QualType T,
9944 QualType ConvTy) {
9945 return DiagnosticBuilder::getEmpty();
9946 }
9947
9948 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9949 CXXConversionDecl *Conv,
9950 QualType ConvTy) {
9951 return DiagnosticBuilder::getEmpty();
9952 }
9953
9954 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9955 QualType T) {
9956 return DiagnosticBuilder::getEmpty();
9957 }
9958
9959 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9960 CXXConversionDecl *Conv,
9961 QualType ConvTy) {
9962 return DiagnosticBuilder::getEmpty();
9963 }
9964
9965 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9966 SourceLocation Loc,
9967 QualType T,
9968 QualType ConvTy) {
9969 return DiagnosticBuilder::getEmpty();
9970 }
9971 } ConvertDiagnoser;
9972
9973 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9974 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009975 }
9976 if (Converted.isInvalid())
9977 return Converted;
9978 E = Converted.take();
9979 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9980 return ExprError();
9981 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9982 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009983 if (!Diagnoser.Suppress)
9984 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009985 return ExprError();
9986 }
9987
Richard Smithdaaefc52011-12-14 23:32:26 +00009988 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9989 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009990 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009991 if (Result)
9992 *Result = E->EvaluateKnownConstInt(Context);
9993 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009994 }
9995
Anders Carlssone21555e2008-11-30 19:50:32 +00009996 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009997 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9998 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009999
Richard Smithdaaefc52011-12-14 23:32:26 +000010000 // Try to evaluate the expression, and produce diagnostics explaining why it's
10001 // not a constant expression as a side-effect.
10002 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10003 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10004
10005 // In C++11, we can rely on diagnostics being produced for any expression
10006 // which is not a constant expression. If no diagnostics were produced, then
10007 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010008 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010009 if (Result)
10010 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010011 return Owned(E);
10012 }
10013
10014 // If our only note is the usual "invalid subexpression" note, just point
10015 // the caret at its location rather than producing an essentially
10016 // redundant note.
10017 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10018 diag::note_invalid_subexpr_in_const_expr) {
10019 DiagLoc = Notes[0].first;
10020 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010021 }
10022
10023 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010024 if (!Diagnoser.Suppress) {
10025 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010026 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10027 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010028 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010029
Richard Smith282e7e62012-02-04 09:53:13 +000010030 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010031 }
10032
Douglas Gregorab41fe92012-05-04 22:38:52 +000010033 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010034 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10035 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010036
Anders Carlssone21555e2008-11-30 19:50:32 +000010037 if (Result)
10038 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010039 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010040}
Douglas Gregore0762c92009-06-19 23:52:42 +000010041
Eli Friedmanef331b72012-01-20 01:26:23 +000010042namespace {
10043 // Handle the case where we conclude a expression which we speculatively
10044 // considered to be unevaluated is actually evaluated.
10045 class TransformToPE : public TreeTransform<TransformToPE> {
10046 typedef TreeTransform<TransformToPE> BaseTransform;
10047
10048 public:
10049 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10050
10051 // Make sure we redo semantic analysis
10052 bool AlwaysRebuild() { return true; }
10053
Eli Friedman56ff2832012-02-06 23:29:57 +000010054 // Make sure we handle LabelStmts correctly.
10055 // FIXME: This does the right thing, but maybe we need a more general
10056 // fix to TreeTransform?
10057 StmtResult TransformLabelStmt(LabelStmt *S) {
10058 S->getDecl()->setStmt(0);
10059 return BaseTransform::TransformLabelStmt(S);
10060 }
10061
Eli Friedmanef331b72012-01-20 01:26:23 +000010062 // We need to special-case DeclRefExprs referring to FieldDecls which
10063 // are not part of a member pointer formation; normal TreeTransforming
10064 // doesn't catch this case because of the way we represent them in the AST.
10065 // FIXME: This is a bit ugly; is it really the best way to handle this
10066 // case?
10067 //
10068 // Error on DeclRefExprs referring to FieldDecls.
10069 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10070 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010071 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010072 return SemaRef.Diag(E->getLocation(),
10073 diag::err_invalid_non_static_member_use)
10074 << E->getDecl() << E->getSourceRange();
10075
10076 return BaseTransform::TransformDeclRefExpr(E);
10077 }
10078
10079 // Exception: filter out member pointer formation
10080 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10081 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10082 return E;
10083
10084 return BaseTransform::TransformUnaryOperator(E);
10085 }
10086
Douglas Gregore2c59132012-02-09 08:14:43 +000010087 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10088 // Lambdas never need to be transformed.
10089 return E;
10090 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010091 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010092}
10093
Eli Friedmanef331b72012-01-20 01:26:23 +000010094ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010095 assert(ExprEvalContexts.back().Context == Unevaluated &&
10096 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010097 ExprEvalContexts.back().Context =
10098 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10099 if (ExprEvalContexts.back().Context == Unevaluated)
10100 return E;
10101 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010102}
10103
Douglas Gregor2afce722009-11-26 00:44:06 +000010104void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010105Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010106 Decl *LambdaContextDecl,
10107 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010108 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010109 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010110 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010111 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010112 LambdaContextDecl,
10113 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010114 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010115 if (!MaybeODRUseExprs.empty())
10116 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010117}
10118
Richard Trieu67e29332011-08-02 04:35:43 +000010119void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010120 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010121
Douglas Gregore2c59132012-02-09 08:14:43 +000010122 if (!Rec.Lambdas.empty()) {
10123 if (Rec.Context == Unevaluated) {
10124 // C++11 [expr.prim.lambda]p2:
10125 // A lambda-expression shall not appear in an unevaluated operand
10126 // (Clause 5).
10127 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10128 Diag(Rec.Lambdas[I]->getLocStart(),
10129 diag::err_lambda_unevaluated_operand);
10130 } else {
10131 // Mark the capture expressions odr-used. This was deferred
10132 // during lambda expression creation.
10133 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10134 LambdaExpr *Lambda = Rec.Lambdas[I];
10135 for (LambdaExpr::capture_init_iterator
10136 C = Lambda->capture_init_begin(),
10137 CEnd = Lambda->capture_init_end();
10138 C != CEnd; ++C) {
10139 MarkDeclarationsReferencedInExpr(*C);
10140 }
10141 }
10142 }
10143 }
10144
Douglas Gregor2afce722009-11-26 00:44:06 +000010145 // When are coming out of an unevaluated context, clear out any
10146 // temporaries that we may have created as part of the evaluation of
10147 // the expression in that context: they aren't relevant because they
10148 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010149 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010150 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10151 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010152 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010153 CleanupVarDeclMarking();
10154 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010155 // Otherwise, merge the contexts together.
10156 } else {
10157 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010158 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10159 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010160 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010161
10162 // Pop the current expression evaluation context off the stack.
10163 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010164}
Douglas Gregore0762c92009-06-19 23:52:42 +000010165
John McCallf85e1932011-06-15 23:02:42 +000010166void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010167 ExprCleanupObjects.erase(
10168 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10169 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010170 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010171 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010172}
10173
Eli Friedman71b8fb52012-01-21 01:01:51 +000010174ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10175 if (!E->getType()->isVariablyModifiedType())
10176 return E;
10177 return TranformToPotentiallyEvaluated(E);
10178}
10179
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010180static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010181 // Do not mark anything as "used" within a dependent context; wait for
10182 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010183 if (SemaRef.CurContext->isDependentContext())
10184 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010185
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 switch (SemaRef.ExprEvalContexts.back().Context) {
10187 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010188 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010189 // (Depending on how you read the standard, we actually do need to do
10190 // something here for null pointer constants, but the standard's
10191 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010192 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010193
Eli Friedman5f2987c2012-02-02 03:46:19 +000010194 case Sema::ConstantEvaluated:
10195 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010196 // We are in a potentially evaluated expression (or a constant-expression
10197 // in C++03); we need to do implicit template instantiation, implicitly
10198 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010199 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010200
Eli Friedman5f2987c2012-02-02 03:46:19 +000010201 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010202 // Referenced declarations will only be used if the construct in the
10203 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010204 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010205 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010206 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010207}
10208
10209/// \brief Mark a function referenced, and check whether it is odr-used
10210/// (C++ [basic.def.odr]p2, C99 6.9p3)
10211void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10212 assert(Func && "No function?");
10213
10214 Func->setReferenced();
10215
Richard Smith57b9c4e2012-02-14 22:25:15 +000010216 // Don't mark this function as used multiple times, unless it's a constexpr
10217 // function which we need to instantiate.
10218 if (Func->isUsed(false) &&
10219 !(Func->isConstexpr() && !Func->getBody() &&
10220 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010221 return;
10222
10223 if (!IsPotentiallyEvaluatedContext(*this))
10224 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010225
Douglas Gregore0762c92009-06-19 23:52:42 +000010226 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010227 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010228 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010229 if (Constructor->isDefaultConstructor()) {
10230 if (Constructor->isTrivial())
10231 return;
10232 if (!Constructor->isUsed(false))
10233 DefineImplicitDefaultConstructor(Loc, Constructor);
10234 } else if (Constructor->isCopyConstructor()) {
10235 if (!Constructor->isUsed(false))
10236 DefineImplicitCopyConstructor(Loc, Constructor);
10237 } else if (Constructor->isMoveConstructor()) {
10238 if (!Constructor->isUsed(false))
10239 DefineImplicitMoveConstructor(Loc, Constructor);
10240 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010241 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010242
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010243 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010244 } else if (CXXDestructorDecl *Destructor =
10245 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010246 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10247 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010248 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010249 if (Destructor->isVirtual())
10250 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010251 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010252 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10253 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010254 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010255 if (!MethodDecl->isUsed(false)) {
10256 if (MethodDecl->isCopyAssignmentOperator())
10257 DefineImplicitCopyAssignment(Loc, MethodDecl);
10258 else
10259 DefineImplicitMoveAssignment(Loc, MethodDecl);
10260 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010261 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10262 MethodDecl->getParent()->isLambda()) {
10263 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10264 if (Conversion->isLambdaToBlockPointerConversion())
10265 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10266 else
10267 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010268 } else if (MethodDecl->isVirtual())
10269 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010270 }
John McCall15e310a2011-02-19 02:53:41 +000010271
Eli Friedman5f2987c2012-02-02 03:46:19 +000010272 // Recursive functions should be marked when used from another function.
10273 // FIXME: Is this really right?
10274 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010275
Richard Smithb9d0b762012-07-27 04:22:15 +000010276 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010277 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010278 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010279 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10280 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010281
Eli Friedman5f2987c2012-02-02 03:46:19 +000010282 // Implicit instantiation of function templates and member functions of
10283 // class templates.
10284 if (Func->isImplicitlyInstantiable()) {
10285 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010286 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010287 if (FunctionTemplateSpecializationInfo *SpecInfo
10288 = Func->getTemplateSpecializationInfo()) {
10289 if (SpecInfo->getPointOfInstantiation().isInvalid())
10290 SpecInfo->setPointOfInstantiation(Loc);
10291 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010292 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010293 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010294 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10295 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010296 } else if (MemberSpecializationInfo *MSInfo
10297 = Func->getMemberSpecializationInfo()) {
10298 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010299 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010300 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010301 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010302 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010303 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10304 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010305 }
Mike Stump1eb44332009-09-09 15:08:12 +000010306
Richard Smith57b9c4e2012-02-14 22:25:15 +000010307 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010308 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10309 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010310 PendingLocalImplicitInstantiations.push_back(
10311 std::make_pair(Func, PointOfInstantiation));
10312 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010313 // Do not defer instantiations of constexpr functions, to avoid the
10314 // expression evaluator needing to call back into Sema if it sees a
10315 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010316 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010317 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010318 PendingInstantiations.push_back(std::make_pair(Func,
10319 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010320 // Notify the consumer that a function was implicitly instantiated.
10321 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10322 }
John McCall15e310a2011-02-19 02:53:41 +000010323 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010324 } else {
10325 // Walk redefinitions, as some of them may be instantiable.
10326 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10327 e(Func->redecls_end()); i != e; ++i) {
10328 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10329 MarkFunctionReferenced(Loc, *i);
10330 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010331 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010332
10333 // Keep track of used but undefined functions.
10334 if (!Func->isPure() && !Func->hasBody() &&
10335 Func->getLinkage() != ExternalLinkage) {
10336 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10337 if (old.isInvalid()) old = Loc;
10338 }
10339
10340 Func->setUsed(true);
10341}
10342
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010343static void
10344diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10345 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010346 DeclContext *VarDC = var->getDeclContext();
10347
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010348 // If the parameter still belongs to the translation unit, then
10349 // we're actually just using one parameter in the declaration of
10350 // the next.
10351 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010352 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010353 return;
10354
Eli Friedman0a294222012-02-07 00:15:00 +000010355 // For C code, don't diagnose about capture if we're not actually in code
10356 // right now; it's impossible to write a non-constant expression outside of
10357 // function context, so we'll get other (more useful) diagnostics later.
10358 //
10359 // For C++, things get a bit more nasty... it would be nice to suppress this
10360 // diagnostic for certain cases like using a local variable in an array bound
10361 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010362 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010363 return;
10364
Eli Friedman0a294222012-02-07 00:15:00 +000010365 if (isa<CXXMethodDecl>(VarDC) &&
10366 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10367 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10368 << var->getIdentifier();
10369 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10370 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10371 << var->getIdentifier() << fn->getDeclName();
10372 } else if (isa<BlockDecl>(VarDC)) {
10373 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10374 << var->getIdentifier();
10375 } else {
10376 // FIXME: Is there any other context where a local variable can be
10377 // declared?
10378 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10379 << var->getIdentifier();
10380 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010381
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010382 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10383 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010384
10385 // FIXME: Add additional diagnostic info about class etc. which prevents
10386 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010387}
10388
Douglas Gregorf8af9822012-02-12 18:42:33 +000010389/// \brief Capture the given variable in the given lambda expression.
10390static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010391 VarDecl *Var, QualType FieldType,
10392 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010393 SourceLocation Loc,
10394 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010395 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010396
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010397 // Build the non-static data member.
10398 FieldDecl *Field
10399 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10400 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010401 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010402 Field->setImplicit(true);
10403 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010404 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010405
10406 // C++11 [expr.prim.lambda]p21:
10407 // When the lambda-expression is evaluated, the entities that
10408 // are captured by copy are used to direct-initialize each
10409 // corresponding non-static data member of the resulting closure
10410 // object. (For array members, the array elements are
10411 // direct-initialized in increasing subscript order.) These
10412 // initializations are performed in the (unspecified) order in
10413 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010414
Douglas Gregore2c59132012-02-09 08:14:43 +000010415 // Introduce a new evaluation context for the initialization, so
10416 // that temporaries introduced as part of the capture are retained
10417 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010418 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10419
Douglas Gregor73d90922012-02-10 09:26:04 +000010420 // C++ [expr.prim.labda]p12:
10421 // An entity captured by a lambda-expression is odr-used (3.2) in
10422 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010423 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10424 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010425 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010426 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010427
10428 // When the field has array type, create index variables for each
10429 // dimension of the array. We use these index variables to subscript
10430 // the source array, and other clients (e.g., CodeGen) will perform
10431 // the necessary iteration with these index variables.
10432 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010433 QualType BaseType = FieldType;
10434 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010435 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010436 while (const ConstantArrayType *Array
10437 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010438 // Create the iteration variable for this array index.
10439 IdentifierInfo *IterationVarName = 0;
10440 {
10441 SmallString<8> Str;
10442 llvm::raw_svector_ostream OS(Str);
10443 OS << "__i" << IndexVariables.size();
10444 IterationVarName = &S.Context.Idents.get(OS.str());
10445 }
10446 VarDecl *IterationVar
10447 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10448 IterationVarName, SizeType,
10449 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10450 SC_None, SC_None);
10451 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010452 LSI->ArrayIndexVars.push_back(IterationVar);
10453
Douglas Gregor18fe0842012-02-09 02:45:47 +000010454 // Create a reference to the iteration variable.
10455 ExprResult IterationVarRef
10456 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10457 assert(!IterationVarRef.isInvalid() &&
10458 "Reference to invented variable cannot fail!");
10459 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10460 assert(!IterationVarRef.isInvalid() &&
10461 "Conversion of invented variable cannot fail!");
10462
10463 // Subscript the array with this iteration variable.
10464 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10465 Ref, Loc, IterationVarRef.take(), Loc);
10466 if (Subscript.isInvalid()) {
10467 S.CleanupVarDeclMarking();
10468 S.DiscardCleanupsInEvaluationContext();
10469 S.PopExpressionEvaluationContext();
10470 return ExprError();
10471 }
10472
10473 Ref = Subscript.take();
10474 BaseType = Array->getElementType();
10475 }
10476
10477 // Construct the entity that we will be initializing. For an array, this
10478 // will be first element in the array, which may require several levels
10479 // of array-subscript entities.
10480 SmallVector<InitializedEntity, 4> Entities;
10481 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010482 Entities.push_back(
10483 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010484 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10485 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10486 0,
10487 Entities.back()));
10488
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010489 InitializationKind InitKind
10490 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010491 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010492 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010493 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010494 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010495
10496 // If this initialization requires any cleanups (e.g., due to a
10497 // default argument to a copy constructor), note that for the
10498 // lambda.
10499 if (S.ExprNeedsCleanups)
10500 LSI->ExprNeedsCleanups = true;
10501
10502 // Exit the expression evaluation context used for the capture.
10503 S.CleanupVarDeclMarking();
10504 S.DiscardCleanupsInEvaluationContext();
10505 S.PopExpressionEvaluationContext();
10506 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010507}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010508
Douglas Gregor999713e2012-02-18 09:37:24 +000010509bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10510 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10511 bool BuildAndDiagnose,
10512 QualType &CaptureType,
10513 QualType &DeclRefType) {
10514 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010515
Eli Friedmanb942cb22012-02-03 22:47:37 +000010516 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010517 if (Var->getDeclContext() == DC) return true;
10518 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010519
Douglas Gregorf8af9822012-02-12 18:42:33 +000010520 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010521
Douglas Gregor999713e2012-02-18 09:37:24 +000010522 // Walk up the stack to determine whether we can capture the variable,
10523 // performing the "simple" checks that don't depend on type. We stop when
10524 // we've either hit the declared scope of the variable or find an existing
10525 // capture of that variable.
10526 CaptureType = Var->getType();
10527 DeclRefType = CaptureType.getNonReferenceType();
10528 bool Explicit = (Kind != TryCapture_Implicit);
10529 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010530 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010531 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010532 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010533 DeclContext *ParentDC;
10534 if (isa<BlockDecl>(DC))
10535 ParentDC = DC->getParent();
10536 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010537 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010538 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10539 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010540 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010541 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010542 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010543 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010544 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010545
Eli Friedmanb942cb22012-02-03 22:47:37 +000010546 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010547 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010548
Eli Friedmanb942cb22012-02-03 22:47:37 +000010549 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010550 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010551 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010552 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010553
10554 // Retrieve the capture type for this variable.
10555 CaptureType = CSI->getCapture(Var).getCaptureType();
10556
10557 // Compute the type of an expression that refers to this variable.
10558 DeclRefType = CaptureType.getNonReferenceType();
10559
10560 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10561 if (Cap.isCopyCapture() &&
10562 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10563 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010564 break;
10565 }
10566
Douglas Gregorf8af9822012-02-12 18:42:33 +000010567 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010568 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010569
10570 // Lambdas are not allowed to capture unnamed variables
10571 // (e.g. anonymous unions).
10572 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10573 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010574 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010575 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010576 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10577 Diag(Var->getLocation(), diag::note_declared_at);
10578 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010579 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010580 }
10581
10582 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010583 if (Var->getType()->isVariablyModifiedType()) {
10584 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010585 if (IsBlock)
10586 Diag(Loc, diag::err_ref_vm_type);
10587 else
10588 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10589 Diag(Var->getLocation(), diag::note_previous_decl)
10590 << Var->getDeclName();
10591 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010592 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010593 }
10594
Eli Friedmanb942cb22012-02-03 22:47:37 +000010595 // Lambdas are not allowed to capture __block variables; they don't
10596 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010597 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010598 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010599 Diag(Loc, diag::err_lambda_capture_block)
10600 << Var->getDeclName();
10601 Diag(Var->getLocation(), diag::note_previous_decl)
10602 << Var->getDeclName();
10603 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010604 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010605 }
10606
Douglas Gregorf8af9822012-02-12 18:42:33 +000010607 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10608 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010609 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010610 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10611 Diag(Var->getLocation(), diag::note_previous_decl)
10612 << Var->getDeclName();
10613 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10614 diag::note_lambda_decl);
10615 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010616 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010617 }
10618
10619 FunctionScopesIndex--;
10620 DC = ParentDC;
10621 Explicit = false;
10622 } while (!Var->getDeclContext()->Equals(DC));
10623
Douglas Gregor999713e2012-02-18 09:37:24 +000010624 // Walk back down the scope stack, computing the type of the capture at
10625 // each step, checking type-specific requirements, and adding captures if
10626 // requested.
10627 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10628 ++I) {
10629 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010630
Douglas Gregor999713e2012-02-18 09:37:24 +000010631 // Compute the type of the capture and of a reference to the capture within
10632 // this scope.
10633 if (isa<BlockScopeInfo>(CSI)) {
10634 Expr *CopyExpr = 0;
10635 bool ByRef = false;
10636
10637 // Blocks are not allowed to capture arrays.
10638 if (CaptureType->isArrayType()) {
10639 if (BuildAndDiagnose) {
10640 Diag(Loc, diag::err_ref_array_type);
10641 Diag(Var->getLocation(), diag::note_previous_decl)
10642 << Var->getDeclName();
10643 }
10644 return true;
10645 }
10646
John McCall100c6492012-03-30 05:23:48 +000010647 // Forbid the block-capture of autoreleasing variables.
10648 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10649 if (BuildAndDiagnose) {
10650 Diag(Loc, diag::err_arc_autoreleasing_capture)
10651 << /*block*/ 0;
10652 Diag(Var->getLocation(), diag::note_previous_decl)
10653 << Var->getDeclName();
10654 }
10655 return true;
10656 }
10657
Douglas Gregor999713e2012-02-18 09:37:24 +000010658 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10659 // Block capture by reference does not change the capture or
10660 // declaration reference types.
10661 ByRef = true;
10662 } else {
10663 // Block capture by copy introduces 'const'.
10664 CaptureType = CaptureType.getNonReferenceType().withConst();
10665 DeclRefType = CaptureType;
10666
David Blaikie4e4d0842012-03-11 07:00:24 +000010667 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010668 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10669 // The capture logic needs the destructor, so make sure we mark it.
10670 // Usually this is unnecessary because most local variables have
10671 // their destructors marked at declaration time, but parameters are
10672 // an exception because it's technically only the call site that
10673 // actually requires the destructor.
10674 if (isa<ParmVarDecl>(Var))
10675 FinalizeVarWithDestructor(Var, Record);
10676
10677 // According to the blocks spec, the capture of a variable from
10678 // the stack requires a const copy constructor. This is not true
10679 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010680 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010681 DeclRefType.withConst(),
10682 VK_LValue, Loc);
10683 ExprResult Result
10684 = PerformCopyInitialization(
10685 InitializedEntity::InitializeBlock(Var->getLocation(),
10686 CaptureType, false),
10687 Loc, Owned(DeclRef));
10688
10689 // Build a full-expression copy expression if initialization
10690 // succeeded and used a non-trivial constructor. Recover from
10691 // errors by pretending that the copy isn't necessary.
10692 if (!Result.isInvalid() &&
10693 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10694 ->isTrivial()) {
10695 Result = MaybeCreateExprWithCleanups(Result);
10696 CopyExpr = Result.take();
10697 }
10698 }
10699 }
10700 }
10701
10702 // Actually capture the variable.
10703 if (BuildAndDiagnose)
10704 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10705 SourceLocation(), CaptureType, CopyExpr);
10706 Nested = true;
10707 continue;
10708 }
Douglas Gregor68932842012-02-18 05:51:20 +000010709
Douglas Gregor999713e2012-02-18 09:37:24 +000010710 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10711
10712 // Determine whether we are capturing by reference or by value.
10713 bool ByRef = false;
10714 if (I == N - 1 && Kind != TryCapture_Implicit) {
10715 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010716 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010717 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010718 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010719
10720 // Compute the type of the field that will capture this variable.
10721 if (ByRef) {
10722 // C++11 [expr.prim.lambda]p15:
10723 // An entity is captured by reference if it is implicitly or
10724 // explicitly captured but not captured by copy. It is
10725 // unspecified whether additional unnamed non-static data
10726 // members are declared in the closure type for entities
10727 // captured by reference.
10728 //
10729 // FIXME: It is not clear whether we want to build an lvalue reference
10730 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10731 // to do the former, while EDG does the latter. Core issue 1249 will
10732 // clarify, but for now we follow GCC because it's a more permissive and
10733 // easily defensible position.
10734 CaptureType = Context.getLValueReferenceType(DeclRefType);
10735 } else {
10736 // C++11 [expr.prim.lambda]p14:
10737 // For each entity captured by copy, an unnamed non-static
10738 // data member is declared in the closure type. The
10739 // declaration order of these members is unspecified. The type
10740 // of such a data member is the type of the corresponding
10741 // captured entity if the entity is not a reference to an
10742 // object, or the referenced type otherwise. [Note: If the
10743 // captured entity is a reference to a function, the
10744 // corresponding data member is also a reference to a
10745 // function. - end note ]
10746 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10747 if (!RefType->getPointeeType()->isFunctionType())
10748 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010749 }
John McCall100c6492012-03-30 05:23:48 +000010750
10751 // Forbid the lambda copy-capture of autoreleasing variables.
10752 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10753 if (BuildAndDiagnose) {
10754 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10755 Diag(Var->getLocation(), diag::note_previous_decl)
10756 << Var->getDeclName();
10757 }
10758 return true;
10759 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010760 }
10761
Douglas Gregor999713e2012-02-18 09:37:24 +000010762 // Capture this variable in the lambda.
10763 Expr *CopyExpr = 0;
10764 if (BuildAndDiagnose) {
10765 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010766 DeclRefType, Loc,
10767 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010768 if (!Result.isInvalid())
10769 CopyExpr = Result.take();
10770 }
10771
10772 // Compute the type of a reference to this captured variable.
10773 if (ByRef)
10774 DeclRefType = CaptureType.getNonReferenceType();
10775 else {
10776 // C++ [expr.prim.lambda]p5:
10777 // The closure type for a lambda-expression has a public inline
10778 // function call operator [...]. This function call operator is
10779 // declared const (9.3.1) if and only if the lambda-expression’s
10780 // parameter-declaration-clause is not followed by mutable.
10781 DeclRefType = CaptureType.getNonReferenceType();
10782 if (!LSI->Mutable && !CaptureType->isReferenceType())
10783 DeclRefType.addConst();
10784 }
10785
10786 // Add the capture.
10787 if (BuildAndDiagnose)
10788 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10789 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010790 Nested = true;
10791 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010792
10793 return false;
10794}
10795
10796bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10797 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10798 QualType CaptureType;
10799 QualType DeclRefType;
10800 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10801 /*BuildAndDiagnose=*/true, CaptureType,
10802 DeclRefType);
10803}
10804
10805QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10806 QualType CaptureType;
10807 QualType DeclRefType;
10808
10809 // Determine whether we can capture this variable.
10810 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10811 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10812 return QualType();
10813
10814 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010815}
10816
Eli Friedmand2cce132012-02-02 23:15:15 +000010817static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10818 SourceLocation Loc) {
10819 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010820 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010821 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010822 Var->getLinkage() != ExternalLinkage &&
10823 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010824 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10825 if (old.isInvalid()) old = Loc;
10826 }
10827
Douglas Gregor999713e2012-02-18 09:37:24 +000010828 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010829
Eli Friedmand2cce132012-02-02 23:15:15 +000010830 Var->setUsed(true);
10831}
10832
10833void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10834 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10835 // an object that satisfies the requirements for appearing in a
10836 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10837 // is immediately applied." This function handles the lvalue-to-rvalue
10838 // conversion part.
10839 MaybeODRUseExprs.erase(E->IgnoreParens());
10840}
10841
Eli Friedmanac626012012-02-29 03:16:56 +000010842ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10843 if (!Res.isUsable())
10844 return Res;
10845
10846 // If a constant-expression is a reference to a variable where we delay
10847 // deciding whether it is an odr-use, just assume we will apply the
10848 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10849 // (a non-type template argument), we have special handling anyway.
10850 UpdateMarkingForLValueToRValue(Res.get());
10851 return Res;
10852}
10853
Eli Friedmand2cce132012-02-02 23:15:15 +000010854void Sema::CleanupVarDeclMarking() {
10855 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10856 e = MaybeODRUseExprs.end();
10857 i != e; ++i) {
10858 VarDecl *Var;
10859 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010860 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010861 Var = cast<VarDecl>(DRE->getDecl());
10862 Loc = DRE->getLocation();
10863 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10864 Var = cast<VarDecl>(ME->getMemberDecl());
10865 Loc = ME->getMemberLoc();
10866 } else {
10867 llvm_unreachable("Unexpcted expression");
10868 }
10869
10870 MarkVarDeclODRUsed(*this, Var, Loc);
10871 }
10872
10873 MaybeODRUseExprs.clear();
10874}
10875
10876// Mark a VarDecl referenced, and perform the necessary handling to compute
10877// odr-uses.
10878static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10879 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010880 Var->setReferenced();
10881
Eli Friedmand2cce132012-02-02 23:15:15 +000010882 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010883 return;
10884
10885 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010886 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010887 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10888 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010889 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10890 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010891 (!AlreadyInstantiated ||
10892 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010893 if (!AlreadyInstantiated) {
10894 // This is a modification of an existing AST node. Notify listeners.
10895 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10896 L->StaticDataMemberInstantiated(Var);
10897 MSInfo->setPointOfInstantiation(Loc);
10898 }
10899 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010900 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010901 // Do not defer instantiations of variables which could be used in a
10902 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010903 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010904 else
Richard Smith37ce0102012-02-15 02:42:50 +000010905 SemaRef.PendingInstantiations.push_back(
10906 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010907 }
10908 }
10909
Eli Friedmand2cce132012-02-02 23:15:15 +000010910 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10911 // an object that satisfies the requirements for appearing in a
10912 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10913 // is immediately applied." We check the first part here, and
10914 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10915 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010916 // C++03 depends on whether we get the C++03 version correct. This does not
10917 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010918 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010919 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010920 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010921 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10922 SemaRef.MaybeODRUseExprs.insert(E);
10923 else
10924 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10925}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010926
Eli Friedmand2cce132012-02-02 23:15:15 +000010927/// \brief Mark a variable referenced, and check whether it is odr-used
10928/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10929/// used directly for normal expressions referring to VarDecl.
10930void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10931 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010932}
10933
10934static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10935 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010936 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10937 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10938 return;
10939 }
10940
Eli Friedman5f2987c2012-02-02 03:46:19 +000010941 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010942
10943 // If this is a call to a method via a cast, also mark the method in the
10944 // derived class used in case codegen can devirtualize the call.
10945 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10946 if (!ME)
10947 return;
10948 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10949 if (!MD)
10950 return;
10951 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010952 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010953 if (!MostDerivedClassDecl)
10954 return;
10955 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010956 if (!DM)
10957 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010958 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010959}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010960
Eli Friedman5f2987c2012-02-02 03:46:19 +000010961/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10962void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10963 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10964}
10965
10966/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10967void Sema::MarkMemberReferenced(MemberExpr *E) {
10968 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10969}
10970
Douglas Gregor73d90922012-02-10 09:26:04 +000010971/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010972/// marks the declaration referenced, and performs odr-use checking for functions
10973/// and variables. This method should not be used when building an normal
10974/// expression which refers to a variable.
10975void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10976 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10977 MarkVariableReferenced(Loc, VD);
10978 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10979 MarkFunctionReferenced(Loc, FD);
10980 else
10981 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010982}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010983
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010984namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010985 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010986 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010987 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010988 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10989 Sema &S;
10990 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010991
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010992 public:
10993 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010994
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010995 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010996
10997 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10998 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010999 };
11000}
11001
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011002bool MarkReferencedDecls::TraverseTemplateArgument(
11003 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011004 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011005 if (Decl *D = Arg.getAsDecl())
11006 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011007 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011008
11009 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011010}
11011
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011012bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011013 if (ClassTemplateSpecializationDecl *Spec
11014 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11015 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011016 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011017 }
11018
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011019 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011020}
11021
11022void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11023 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011024 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011025}
11026
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011027namespace {
11028 /// \brief Helper class that marks all of the declarations referenced by
11029 /// potentially-evaluated subexpressions as "referenced".
11030 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11031 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011032 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011033
11034 public:
11035 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11036
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011037 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11038 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011039
11040 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011041 // If we were asked not to visit local variables, don't.
11042 if (SkipLocalVariables) {
11043 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11044 if (VD->hasLocalStorage())
11045 return;
11046 }
11047
Eli Friedman5f2987c2012-02-02 03:46:19 +000011048 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011049 }
11050
11051 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011052 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011053 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011054 }
11055
John McCall80ee6e82011-11-10 05:35:25 +000011056 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011057 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011058 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11059 Visit(E->getSubExpr());
11060 }
11061
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011062 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011063 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011064 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011065 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011066 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011067 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011068 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011069
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011070 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11071 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011072 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011073 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11074 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11075 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011076 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011077 S.LookupDestructor(Record));
11078 }
11079
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011080 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011081 }
11082
11083 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011084 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011085 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011086 }
11087
Douglas Gregor102ff972010-10-19 17:17:35 +000011088 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11089 Visit(E->getExpr());
11090 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011091
11092 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11093 Inherited::VisitImplicitCastExpr(E);
11094
11095 if (E->getCastKind() == CK_LValueToRValue)
11096 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11097 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011098 };
11099}
11100
11101/// \brief Mark any declarations that appear within this expression or any
11102/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011103///
11104/// \param SkipLocalVariables If true, don't mark local variables as
11105/// 'referenced'.
11106void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11107 bool SkipLocalVariables) {
11108 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011109}
11110
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011111/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11112/// of the program being compiled.
11113///
11114/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011115/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011116/// possibility that the code will actually be executable. Code in sizeof()
11117/// expressions, code used only during overload resolution, etc., are not
11118/// potentially evaluated. This routine will suppress such diagnostics or,
11119/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011120/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011121/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011122///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011123/// This routine should be used for all diagnostics that describe the run-time
11124/// behavior of a program, such as passing a non-POD value through an ellipsis.
11125/// Failure to do so will likely result in spurious diagnostics or failures
11126/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011127bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011128 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011129 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011130 case Unevaluated:
11131 // The argument will never be evaluated, so don't complain.
11132 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011133
Richard Smithf6702a32011-12-20 02:08:33 +000011134 case ConstantEvaluated:
11135 // Relevant diagnostics should be produced by constant evaluation.
11136 break;
11137
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011138 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011139 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011140 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011141 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011142 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011143 }
11144 else
11145 Diag(Loc, PD);
11146
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011147 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011148 }
11149
11150 return false;
11151}
11152
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011153bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11154 CallExpr *CE, FunctionDecl *FD) {
11155 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11156 return false;
11157
Richard Smith76f3f692012-02-22 02:04:18 +000011158 // If we're inside a decltype's expression, don't check for a valid return
11159 // type or construct temporaries until we know whether this is the last call.
11160 if (ExprEvalContexts.back().IsDecltype) {
11161 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11162 return false;
11163 }
11164
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011165 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011166 FunctionDecl *FD;
11167 CallExpr *CE;
11168
11169 public:
11170 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11171 : FD(FD), CE(CE) { }
11172
11173 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11174 if (!FD) {
11175 S.Diag(Loc, diag::err_call_incomplete_return)
11176 << T << CE->getSourceRange();
11177 return;
11178 }
11179
11180 S.Diag(Loc, diag::err_call_function_incomplete_return)
11181 << CE->getSourceRange() << FD->getDeclName() << T;
11182 S.Diag(FD->getLocation(),
11183 diag::note_function_with_incomplete_return_type_declared_here)
11184 << FD->getDeclName();
11185 }
11186 } Diagnoser(FD, CE);
11187
11188 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011189 return true;
11190
11191 return false;
11192}
11193
Douglas Gregor92c3a042011-01-19 16:50:08 +000011194// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011195// will prevent this condition from triggering, which is what we want.
11196void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11197 SourceLocation Loc;
11198
John McCalla52ef082009-11-11 02:41:58 +000011199 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011200 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011201
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011202 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011203 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011204 return;
11205
Douglas Gregor92c3a042011-01-19 16:50:08 +000011206 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11207
John McCallc8d8ac52009-11-12 00:06:05 +000011208 // Greylist some idioms by putting them into a warning subcategory.
11209 if (ObjCMessageExpr *ME
11210 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11211 Selector Sel = ME->getSelector();
11212
John McCallc8d8ac52009-11-12 00:06:05 +000011213 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011214 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011215 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11216
11217 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011218 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011219 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11220 }
John McCalla52ef082009-11-11 02:41:58 +000011221
John McCall5a881bb2009-10-12 21:59:07 +000011222 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011223 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011224 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011225 return;
11226
Douglas Gregor92c3a042011-01-19 16:50:08 +000011227 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011228 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011229 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11230 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11231 else {
John McCall5a881bb2009-10-12 21:59:07 +000011232 // Not an assignment.
11233 return;
11234 }
11235
Douglas Gregor55b38842010-04-14 16:09:52 +000011236 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011237
Daniel Dunbar96a00142012-03-09 18:35:03 +000011238 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011239 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11240 Diag(Loc, diag::note_condition_assign_silence)
11241 << FixItHint::CreateInsertion(Open, "(")
11242 << FixItHint::CreateInsertion(Close, ")");
11243
Douglas Gregor92c3a042011-01-19 16:50:08 +000011244 if (IsOrAssign)
11245 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11246 << FixItHint::CreateReplacement(Loc, "!=");
11247 else
11248 Diag(Loc, diag::note_condition_assign_to_comparison)
11249 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011250}
11251
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011252/// \brief Redundant parentheses over an equality comparison can indicate
11253/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011254void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011255 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011256 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011257 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11258 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011259 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011260 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011261 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011262
Richard Trieuccd891a2011-09-09 01:45:06 +000011263 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011264
11265 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011266 if (opE->getOpcode() == BO_EQ &&
11267 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11268 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011269 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011270
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011271 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011272 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011273 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011274 << FixItHint::CreateRemoval(ParenERange.getBegin())
11275 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011276 Diag(Loc, diag::note_equality_comparison_to_assign)
11277 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011278 }
11279}
11280
John Wiegley429bb272011-04-08 18:41:53 +000011281ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011282 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011283 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11284 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011285
John McCall864c0412011-04-26 20:42:42 +000011286 ExprResult result = CheckPlaceholderExpr(E);
11287 if (result.isInvalid()) return ExprError();
11288 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011289
John McCall864c0412011-04-26 20:42:42 +000011290 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011291 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011292 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11293
John Wiegley429bb272011-04-08 18:41:53 +000011294 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11295 if (ERes.isInvalid())
11296 return ExprError();
11297 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011298
11299 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011300 if (!T->isScalarType()) { // C99 6.8.4.1p1
11301 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11302 << T << E->getSourceRange();
11303 return ExprError();
11304 }
John McCall5a881bb2009-10-12 21:59:07 +000011305 }
11306
John Wiegley429bb272011-04-08 18:41:53 +000011307 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011308}
Douglas Gregor586596f2010-05-06 17:25:47 +000011309
John McCall60d7b3a2010-08-24 06:29:42 +000011310ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011311 Expr *SubExpr) {
11312 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011313 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011314
Richard Trieuccd891a2011-09-09 01:45:06 +000011315 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011316}
John McCall2a984ca2010-10-12 00:20:44 +000011317
John McCall1de4d4e2011-04-07 08:22:57 +000011318namespace {
John McCall755d8492011-04-12 00:42:48 +000011319 /// A visitor for rebuilding a call to an __unknown_any expression
11320 /// to have an appropriate type.
11321 struct RebuildUnknownAnyFunction
11322 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11323
11324 Sema &S;
11325
11326 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11327
11328 ExprResult VisitStmt(Stmt *S) {
11329 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011330 }
11331
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011332 ExprResult VisitExpr(Expr *E) {
11333 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11334 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011335 return ExprError();
11336 }
11337
11338 /// Rebuild an expression which simply semantically wraps another
11339 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011340 template <class T> ExprResult rebuildSugarExpr(T *E) {
11341 ExprResult SubResult = Visit(E->getSubExpr());
11342 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011343
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011344 Expr *SubExpr = SubResult.take();
11345 E->setSubExpr(SubExpr);
11346 E->setType(SubExpr->getType());
11347 E->setValueKind(SubExpr->getValueKind());
11348 assert(E->getObjectKind() == OK_Ordinary);
11349 return E;
John McCall755d8492011-04-12 00:42:48 +000011350 }
11351
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011352 ExprResult VisitParenExpr(ParenExpr *E) {
11353 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011354 }
11355
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011356 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11357 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011358 }
11359
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011360 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11361 ExprResult SubResult = Visit(E->getSubExpr());
11362 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011363
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011364 Expr *SubExpr = SubResult.take();
11365 E->setSubExpr(SubExpr);
11366 E->setType(S.Context.getPointerType(SubExpr->getType()));
11367 assert(E->getValueKind() == VK_RValue);
11368 assert(E->getObjectKind() == OK_Ordinary);
11369 return E;
John McCall755d8492011-04-12 00:42:48 +000011370 }
11371
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011372 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11373 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011374
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011375 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011376
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011377 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011378 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011379 !(isa<CXXMethodDecl>(VD) &&
11380 cast<CXXMethodDecl>(VD)->isInstance()))
11381 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011382
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011383 return E;
John McCall755d8492011-04-12 00:42:48 +000011384 }
11385
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011386 ExprResult VisitMemberExpr(MemberExpr *E) {
11387 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011388 }
11389
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011390 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11391 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011392 }
11393 };
11394}
11395
11396/// Given a function expression of unknown-any type, try to rebuild it
11397/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011398static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11399 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11400 if (Result.isInvalid()) return ExprError();
11401 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011402}
11403
11404namespace {
John McCall379b5152011-04-11 07:02:50 +000011405 /// A visitor for rebuilding an expression of type __unknown_anytype
11406 /// into one which resolves the type directly on the referring
11407 /// expression. Strict preservation of the original source
11408 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011409 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011410 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011411
11412 Sema &S;
11413
11414 /// The current destination type.
11415 QualType DestType;
11416
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011417 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11418 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011419
John McCalla5fc4722011-04-09 22:50:59 +000011420 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011421 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011422 }
11423
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011424 ExprResult VisitExpr(Expr *E) {
11425 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11426 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011427 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011428 }
11429
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011430 ExprResult VisitCallExpr(CallExpr *E);
11431 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011432
John McCalla5fc4722011-04-09 22:50:59 +000011433 /// Rebuild an expression which simply semantically wraps another
11434 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011435 template <class T> ExprResult rebuildSugarExpr(T *E) {
11436 ExprResult SubResult = Visit(E->getSubExpr());
11437 if (SubResult.isInvalid()) return ExprError();
11438 Expr *SubExpr = SubResult.take();
11439 E->setSubExpr(SubExpr);
11440 E->setType(SubExpr->getType());
11441 E->setValueKind(SubExpr->getValueKind());
11442 assert(E->getObjectKind() == OK_Ordinary);
11443 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011444 }
John McCall1de4d4e2011-04-07 08:22:57 +000011445
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011446 ExprResult VisitParenExpr(ParenExpr *E) {
11447 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011448 }
11449
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011450 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11451 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011452 }
11453
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011454 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11455 const PointerType *Ptr = DestType->getAs<PointerType>();
11456 if (!Ptr) {
11457 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11458 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011459 return ExprError();
11460 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011461 assert(E->getValueKind() == VK_RValue);
11462 assert(E->getObjectKind() == OK_Ordinary);
11463 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011464
11465 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011466 DestType = Ptr->getPointeeType();
11467 ExprResult SubResult = Visit(E->getSubExpr());
11468 if (SubResult.isInvalid()) return ExprError();
11469 E->setSubExpr(SubResult.take());
11470 return E;
John McCall755d8492011-04-12 00:42:48 +000011471 }
11472
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011473 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011474
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011475 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011476
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011477 ExprResult VisitMemberExpr(MemberExpr *E) {
11478 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011479 }
John McCalla5fc4722011-04-09 22:50:59 +000011480
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011481 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11482 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011483 }
11484 };
11485}
11486
John McCall379b5152011-04-11 07:02:50 +000011487/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011488ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11489 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011490
11491 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011492 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011493 FK_FunctionPointer,
11494 FK_BlockPointer
11495 };
11496
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011497 FnKind Kind;
11498 QualType CalleeType = CalleeExpr->getType();
11499 if (CalleeType == S.Context.BoundMemberTy) {
11500 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11501 Kind = FK_MemberFunction;
11502 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11503 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11504 CalleeType = Ptr->getPointeeType();
11505 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011506 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011507 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11508 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011509 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011510 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011511
11512 // Verify that this is a legal result type of a function.
11513 if (DestType->isArrayType() || DestType->isFunctionType()) {
11514 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011515 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011516 diagID = diag::err_block_returning_array_function;
11517
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011518 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011519 << DestType->isFunctionType() << DestType;
11520 return ExprError();
11521 }
11522
11523 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011524 E->setType(DestType.getNonLValueExprType(S.Context));
11525 E->setValueKind(Expr::getValueKindForType(DestType));
11526 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011527
11528 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011529 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011530 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011531 Proto->arg_type_begin(),
11532 Proto->getNumArgs(),
11533 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011534 else
11535 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011536 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011537
11538 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011539 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011540 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011541 // Nothing to do.
11542 break;
11543
11544 case FK_FunctionPointer:
11545 DestType = S.Context.getPointerType(DestType);
11546 break;
11547
11548 case FK_BlockPointer:
11549 DestType = S.Context.getBlockPointerType(DestType);
11550 break;
11551 }
11552
11553 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554 ExprResult CalleeResult = Visit(CalleeExpr);
11555 if (!CalleeResult.isUsable()) return ExprError();
11556 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011557
11558 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011559 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011560}
11561
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011562ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011563 // Verify that this is a legal result type of a call.
11564 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011565 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011566 << DestType->isFunctionType() << DestType;
11567 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011568 }
11569
John McCall48218c62011-07-13 17:56:40 +000011570 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011571 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11572 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11573 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011574 }
John McCall755d8492011-04-12 00:42:48 +000011575
John McCall379b5152011-04-11 07:02:50 +000011576 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011577 E->setType(DestType.getNonReferenceType());
11578 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011579
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011580 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011581}
11582
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011583ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011584 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011585 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011586 assert(E->getValueKind() == VK_RValue);
11587 assert(E->getObjectKind() == OK_Ordinary);
11588
11589 E->setType(DestType);
11590
11591 // Rebuild the sub-expression as the pointee (function) type.
11592 DestType = DestType->castAs<PointerType>()->getPointeeType();
11593
11594 ExprResult Result = Visit(E->getSubExpr());
11595 if (!Result.isUsable()) return ExprError();
11596
11597 E->setSubExpr(Result.take());
11598 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011599 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011600 assert(E->getValueKind() == VK_RValue);
11601 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011602
Sean Callanance9c8312012-03-06 21:34:12 +000011603 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011604
Sean Callanance9c8312012-03-06 21:34:12 +000011605 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011606
Sean Callanance9c8312012-03-06 21:34:12 +000011607 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11608 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011609
Sean Callanance9c8312012-03-06 21:34:12 +000011610 ExprResult Result = Visit(E->getSubExpr());
11611 if (!Result.isUsable()) return ExprError();
11612
11613 E->setSubExpr(Result.take());
11614 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011615 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011616 llvm_unreachable("Unhandled cast type!");
11617 }
John McCall379b5152011-04-11 07:02:50 +000011618}
11619
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011620ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11621 ExprValueKind ValueKind = VK_LValue;
11622 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011623
11624 // We know how to make this work for certain kinds of decls:
11625
11626 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011627 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11628 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11629 DestType = Ptr->getPointeeType();
11630 ExprResult Result = resolveDecl(E, VD);
11631 if (Result.isInvalid()) return ExprError();
11632 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011633 CK_FunctionToPointerDecay, VK_RValue);
11634 }
11635
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011636 if (!Type->isFunctionType()) {
11637 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11638 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011639 return ExprError();
11640 }
John McCall379b5152011-04-11 07:02:50 +000011641
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011642 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11643 if (MD->isInstance()) {
11644 ValueKind = VK_RValue;
11645 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011646 }
11647
John McCall379b5152011-04-11 07:02:50 +000011648 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011649 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011650 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011651
11652 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011653 } else if (isa<VarDecl>(VD)) {
11654 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11655 Type = RefTy->getPointeeType();
11656 } else if (Type->isFunctionType()) {
11657 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11658 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011659 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011660 }
11661
11662 // - nothing else
11663 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011664 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11665 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011666 return ExprError();
11667 }
11668
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011669 VD->setType(DestType);
11670 E->setType(Type);
11671 E->setValueKind(ValueKind);
11672 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011673}
11674
John McCall1de4d4e2011-04-07 08:22:57 +000011675/// Check a cast of an unknown-any type. We intentionally only
11676/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011677ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11678 Expr *CastExpr, CastKind &CastKind,
11679 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011680 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011681 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011682 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011683
Richard Trieuccd891a2011-09-09 01:45:06 +000011684 CastExpr = result.take();
11685 VK = CastExpr->getValueKind();
11686 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011687
Richard Trieuccd891a2011-09-09 01:45:06 +000011688 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011689}
11690
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011691ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11692 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11693}
11694
Richard Trieuccd891a2011-09-09 01:45:06 +000011695static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11696 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011697 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011698 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011699 E = E->IgnoreParenImpCasts();
11700 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11701 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011702 diagID = diag::err_uncasted_call_of_unknown_any;
11703 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011704 break;
John McCall379b5152011-04-11 07:02:50 +000011705 }
John McCall1de4d4e2011-04-07 08:22:57 +000011706 }
11707
John McCall379b5152011-04-11 07:02:50 +000011708 SourceLocation loc;
11709 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011710 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011711 loc = ref->getLocation();
11712 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011713 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011714 loc = mem->getMemberLoc();
11715 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011716 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011717 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011718 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011719 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011720 if (!d) {
11721 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11722 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11723 << orig->getSourceRange();
11724 return ExprError();
11725 }
John McCall379b5152011-04-11 07:02:50 +000011726 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011727 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11728 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011729 return ExprError();
11730 }
11731
11732 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011733
11734 // Never recoverable.
11735 return ExprError();
11736}
11737
John McCall2a984ca2010-10-12 00:20:44 +000011738/// Check for operands with placeholder types and complain if found.
11739/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011740ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011741 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11742 if (!placeholderType) return Owned(E);
11743
11744 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011745
John McCall1de4d4e2011-04-07 08:22:57 +000011746 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011747 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011748 // Try to resolve a single function template specialization.
11749 // This is obligatory.
11750 ExprResult result = Owned(E);
11751 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11752 return result;
11753
11754 // If that failed, try to recover with a call.
11755 } else {
11756 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11757 /*complain*/ true);
11758 return result;
11759 }
11760 }
John McCall1de4d4e2011-04-07 08:22:57 +000011761
John McCall864c0412011-04-26 20:42:42 +000011762 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011763 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011764 ExprResult result = Owned(E);
11765 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11766 /*complain*/ true);
11767 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011768 }
11769
11770 // ARC unbridged casts.
11771 case BuiltinType::ARCUnbridgedCast: {
11772 Expr *realCast = stripARCUnbridgedCast(E);
11773 diagnoseARCUnbridgedCast(realCast);
11774 return Owned(realCast);
11775 }
John McCall864c0412011-04-26 20:42:42 +000011776
John McCall1de4d4e2011-04-07 08:22:57 +000011777 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011778 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011779 return diagnoseUnknownAnyExpr(*this, E);
11780
John McCall3c3b7f92011-10-25 17:37:35 +000011781 // Pseudo-objects.
11782 case BuiltinType::PseudoObject:
11783 return checkPseudoObjectRValue(E);
11784
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011785 case BuiltinType::BuiltinFn:
11786 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11787 return ExprError();
11788
John McCalle0a22d02011-10-18 21:02:43 +000011789 // Everything else should be impossible.
11790#define BUILTIN_TYPE(Id, SingletonId) \
11791 case BuiltinType::Id:
11792#define PLACEHOLDER_TYPE(Id, SingletonId)
11793#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011794 break;
11795 }
11796
11797 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011798}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011799
Richard Trieuccd891a2011-09-09 01:45:06 +000011800bool Sema::CheckCaseExpression(Expr *E) {
11801 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011802 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011803 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11804 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011805 return false;
11806}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011807
11808/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11809ExprResult
11810Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11811 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11812 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011813 QualType BoolT = Context.ObjCBuiltinBoolTy;
11814 if (!Context.getBOOLDecl()) {
11815 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11816 Sema::LookupOrdinaryName);
11817 if (LookupName(Result, getCurScope())) {
11818 NamedDecl *ND = Result.getFoundDecl();
11819 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11820 Context.setBOOLDecl(TD);
11821 }
11822 }
11823 if (Context.getBOOLDecl())
11824 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011825 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011826 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011827}