blob: cfa9ccbfc3347bf88cd397038971d54e091eda47 [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;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007217 if ((LHSIsNull && LHSType->isIntegerType()) ||
7218 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007219 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007220 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007221 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007222 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007223 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007224 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7225 isError = true;
7226 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007227 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007228
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007229 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007230 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007231 << LHSType << RHSType << LHS.get()->getSourceRange()
7232 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007233 if (isError)
7234 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007235 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007236
Richard Trieuf1775fb2011-09-06 21:43:51 +00007237 if (LHSType->isIntegerType())
7238 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007239 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007240 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007241 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007242 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007243 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007244 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007245
Steve Naroff39218df2008-09-04 16:56:14 +00007246 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007247 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007248 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7249 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007250 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007251 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007252 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007253 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7254 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007255 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007256 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007257
Richard Trieuf1775fb2011-09-06 21:43:51 +00007258 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007259}
7260
Tanya Lattner4f692c22012-01-16 21:02:28 +00007261
7262// Return a signed type that is of identical size and number of elements.
7263// For floating point vectors, return an integer type of identical size
7264// and number of elements.
7265QualType Sema::GetSignedVectorType(QualType V) {
7266 const VectorType *VTy = V->getAs<VectorType>();
7267 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7268 if (TypeSize == Context.getTypeSize(Context.CharTy))
7269 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7270 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7271 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7272 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7273 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7274 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7275 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7276 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7277 "Unhandled vector element size in vector compare");
7278 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7279}
7280
Nate Begemanbe2341d2008-07-14 18:02:46 +00007281/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007282/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007283/// like a scalar comparison, a vector comparison produces a vector of integer
7284/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007285QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007286 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007287 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007288 // Check to make sure we're operating on vectors of the same type and width,
7289 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007290 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007291 if (vType.isNull())
7292 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007293
Richard Trieu9f60dee2011-09-07 01:19:57 +00007294 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007295
Anton Yartsev7870b132011-03-27 15:36:07 +00007296 // If AltiVec, the comparison results in a numeric type, i.e.
7297 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007298 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007299 return Context.getLogicalOperationType();
7300
Nate Begemanbe2341d2008-07-14 18:02:46 +00007301 // For non-floating point types, check for self-comparisons of the form
7302 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7303 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007304 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007305 if (DeclRefExpr* DRL
7306 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7307 if (DeclRefExpr* DRR
7308 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007309 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007310 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007311 PDiag(diag::warn_comparison_always)
7312 << 0 // self-
7313 << 2 // "a constant"
7314 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007315 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007316
Nate Begemanbe2341d2008-07-14 18:02:46 +00007317 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007318 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007319 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007320 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007321 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007322
7323 // Return a signed type for the vector.
7324 return GetSignedVectorType(LHSType);
7325}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007326
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007327QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7328 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007329 // Ensure that either both operands are of the same vector type, or
7330 // one operand is of a vector type and the other is of its element type.
7331 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7332 if (vType.isNull() || vType->isFloatingType())
7333 return InvalidOperands(Loc, LHS, RHS);
7334
7335 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007336}
7337
Reid Spencer5f016e22007-07-11 17:01:13 +00007338inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007339 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007340 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7341
Richard Trieu9f60dee2011-09-07 01:19:57 +00007342 if (LHS.get()->getType()->isVectorType() ||
7343 RHS.get()->getType()->isVectorType()) {
7344 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7345 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007346 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007347
Richard Trieu9f60dee2011-09-07 01:19:57 +00007348 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007349 }
Steve Naroff90045e82007-07-13 23:32:42 +00007350
Richard Trieu9f60dee2011-09-07 01:19:57 +00007351 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7352 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007353 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007354 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007355 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007356 LHS = LHSResult.take();
7357 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007358
Eli Friedman860a3192012-06-16 02:19:17 +00007359 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007360 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007361 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007362}
7363
7364inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007365 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007366
Tanya Lattner4f692c22012-01-16 21:02:28 +00007367 // Check vector operands differently.
7368 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7369 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7370
Chris Lattner90a8f272010-07-13 19:41:32 +00007371 // Diagnose cases where the user write a logical and/or but probably meant a
7372 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7373 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007374 if (LHS.get()->getType()->isIntegerType() &&
7375 !LHS.get()->getType()->isBooleanType() &&
7376 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007377 // Don't warn in macros or template instantiations.
7378 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007379 // If the RHS can be constant folded, and if it constant folds to something
7380 // that isn't 0 or 1 (which indicate a potential logical operation that
7381 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007382 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007383 llvm::APSInt Result;
7384 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007385 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007386 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007387 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007388 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007389 << (Opc == BO_LAnd ? "&&" : "||");
7390 // Suggest replacing the logical operator with the bitwise version
7391 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7392 << (Opc == BO_LAnd ? "&" : "|")
7393 << FixItHint::CreateReplacement(SourceRange(
7394 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007395 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007396 Opc == BO_LAnd ? "&" : "|");
7397 if (Opc == BO_LAnd)
7398 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7399 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7400 << FixItHint::CreateRemoval(
7401 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007402 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007403 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007404 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007405 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007406 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007407 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007408
David Blaikie4e4d0842012-03-11 07:00:24 +00007409 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007410 LHS = UsualUnaryConversions(LHS.take());
7411 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007412 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007413
Richard Trieu9f60dee2011-09-07 01:19:57 +00007414 RHS = UsualUnaryConversions(RHS.take());
7415 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007416 return QualType();
7417
Richard Trieu9f60dee2011-09-07 01:19:57 +00007418 if (!LHS.get()->getType()->isScalarType() ||
7419 !RHS.get()->getType()->isScalarType())
7420 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007421
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007422 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007423 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007424
John McCall75f7c0f2010-06-04 00:29:51 +00007425 // The following is safe because we only use this method for
7426 // non-overloadable operands.
7427
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007428 // C++ [expr.log.and]p1
7429 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007430 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007431 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7432 if (LHSRes.isInvalid())
7433 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007434 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007435
Richard Trieu9f60dee2011-09-07 01:19:57 +00007436 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7437 if (RHSRes.isInvalid())
7438 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007439 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007440
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007441 // C++ [expr.log.and]p2
7442 // C++ [expr.log.or]p2
7443 // The result is a bool.
7444 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007445}
7446
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007447/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7448/// is a read-only property; return true if so. A readonly property expression
7449/// depends on various declarations and thus must be treated specially.
7450///
Mike Stump1eb44332009-09-09 15:08:12 +00007451static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007452 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7453 if (!PropExpr) return false;
7454 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007455
John McCall3c3b7f92011-10-25 17:37:35 +00007456 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7457 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007458 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007459 PropExpr->getBase()->getType();
7460
John McCall3c3b7f92011-10-25 17:37:35 +00007461 if (const ObjCObjectPointerType *OPT =
7462 BaseType->getAsObjCInterfacePointerType())
7463 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7464 if (S.isPropertyReadonly(PDecl, IFace))
7465 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007466 return false;
7467}
7468
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007469static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007470 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7471 if (!ME) return false;
7472 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7473 ObjCMessageExpr *Base =
7474 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7475 if (!Base) return false;
7476 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007477}
7478
John McCall78dae242012-03-13 00:37:01 +00007479/// Is the given expression (which must be 'const') a reference to a
7480/// variable which was originally non-const, but which has become
7481/// 'const' due to being captured within a block?
7482enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7483static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7484 assert(E->isLValue() && E->getType().isConstQualified());
7485 E = E->IgnoreParens();
7486
7487 // Must be a reference to a declaration from an enclosing scope.
7488 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7489 if (!DRE) return NCCK_None;
7490 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7491
7492 // The declaration must be a variable which is not declared 'const'.
7493 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7494 if (!var) return NCCK_None;
7495 if (var->getType().isConstQualified()) return NCCK_None;
7496 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7497
7498 // Decide whether the first capture was for a block or a lambda.
7499 DeclContext *DC = S.CurContext;
7500 while (DC->getParent() != var->getDeclContext())
7501 DC = DC->getParent();
7502 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7503}
7504
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007505/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7506/// emit an error and return true. If so, return false.
7507static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007508 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007509 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007510 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007511 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007512 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7513 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007514 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7515 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007516 if (IsLV == Expr::MLV_Valid)
7517 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007518
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007519 unsigned Diag = 0;
7520 bool NeedType = false;
7521 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007522 case Expr::MLV_ConstQualified:
7523 Diag = diag::err_typecheck_assign_const;
7524
John McCall78dae242012-03-13 00:37:01 +00007525 // Use a specialized diagnostic when we're assigning to an object
7526 // from an enclosing function or block.
7527 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7528 if (NCCK == NCCK_Block)
7529 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7530 else
7531 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7532 break;
7533 }
7534
John McCall7acddac2011-06-17 06:42:21 +00007535 // In ARC, use some specialized diagnostics for occasions where we
7536 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007537 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007538 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7539 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7540 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7541
John McCall7acddac2011-06-17 06:42:21 +00007542 // Use the normal diagnostic if it's pseudo-__strong but the
7543 // user actually wrote 'const'.
7544 if (var->isARCPseudoStrong() &&
7545 (!var->getTypeSourceInfo() ||
7546 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7547 // There are two pseudo-strong cases:
7548 // - self
John McCallf85e1932011-06-15 23:02:42 +00007549 ObjCMethodDecl *method = S.getCurMethodDecl();
7550 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007551 Diag = method->isClassMethod()
7552 ? diag::err_typecheck_arc_assign_self_class_method
7553 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007554
7555 // - fast enumeration variables
7556 else
John McCallf85e1932011-06-15 23:02:42 +00007557 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007558
John McCallf85e1932011-06-15 23:02:42 +00007559 SourceRange Assign;
7560 if (Loc != OrigLoc)
7561 Assign = SourceRange(OrigLoc, OrigLoc);
7562 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7563 // We need to preserve the AST regardless, so migration tool
7564 // can do its job.
7565 return false;
7566 }
7567 }
7568 }
7569
7570 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007571 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007572 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007573 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7574 NeedType = true;
7575 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007576 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007577 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7578 NeedType = true;
7579 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007580 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007581 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7582 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007583 case Expr::MLV_Valid:
7584 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007585 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007586 case Expr::MLV_MemberFunction:
7587 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007588 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7589 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007590 case Expr::MLV_IncompleteType:
7591 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007592 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007593 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007594 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007595 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7596 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007597 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007598 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007599 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007600 case Expr::MLV_InvalidMessageExpression:
7601 Diag = diag::error_readonly_message_assignment;
7602 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007603 case Expr::MLV_SubObjCPropertySetting:
7604 Diag = diag::error_no_subobject_property_setting;
7605 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007606 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007607
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007608 SourceRange Assign;
7609 if (Loc != OrigLoc)
7610 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007611 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007612 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007613 else
Mike Stump1eb44332009-09-09 15:08:12 +00007614 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007615 return true;
7616}
7617
Nico Weber7c81b432012-07-03 02:03:06 +00007618static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7619 SourceLocation Loc,
7620 Sema &Sema) {
7621 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007622 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7623 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7624 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7625 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007626 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007627 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007628
Nico Weber7c81b432012-07-03 02:03:06 +00007629 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007630 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7631 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7632 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7633 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7634 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7635 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007636 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007637 }
7638}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007639
7640// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007641QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007642 SourceLocation Loc,
7643 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007644 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7645
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007646 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007647 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007648 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007649
Richard Trieu268942b2011-09-07 01:33:52 +00007650 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007651 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7652 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007653 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007654 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007655 Expr *RHSCheck = RHS.get();
7656
Nico Weber7c81b432012-07-03 02:03:06 +00007657 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007658
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007659 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007660 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007661 if (RHS.isInvalid())
7662 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007663 // Special case of NSObject attributes on c-style pointer types.
7664 if (ConvTy == IncompatiblePointer &&
7665 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007666 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007667 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007668 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007669 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007670
John McCallf89e55a2010-11-18 06:31:45 +00007671 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007672 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007673 Diag(Loc, diag::err_objc_object_assignment)
7674 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007675
Chris Lattner2c156472008-08-21 18:04:13 +00007676 // If the RHS is a unary plus or minus, check to see if they = and + are
7677 // right next to each other. If so, the user may have typo'd "x =+ 4"
7678 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007679 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7680 RHSCheck = ICE->getSubExpr();
7681 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007682 if ((UO->getOpcode() == UO_Plus ||
7683 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007684 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007685 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007686 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007687 // And there is a space or other character before the subexpr of the
7688 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007689 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007690 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007691 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007692 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007693 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007694 }
Chris Lattner2c156472008-08-21 18:04:13 +00007695 }
John McCallf85e1932011-06-15 23:02:42 +00007696
7697 if (ConvTy == Compatible) {
7698 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007699 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007700 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007701 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007702 }
Chris Lattner2c156472008-08-21 18:04:13 +00007703 } else {
7704 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007705 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007706 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007707
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007708 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007709 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007710 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007711
Richard Trieu268942b2011-09-07 01:33:52 +00007712 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007713
Reid Spencer5f016e22007-07-11 17:01:13 +00007714 // C99 6.5.16p3: The type of an assignment expression is the type of the
7715 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007716 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007717 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7718 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007719 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007720 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007721 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007722 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007723}
7724
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007725// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007726static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007727 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007728 LHS = S.CheckPlaceholderExpr(LHS.take());
7729 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007730 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007731 return QualType();
7732
John McCallcf2e5062010-10-12 07:14:40 +00007733 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7734 // operands, but not unary promotions.
7735 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007736
John McCallf6a16482010-12-04 03:47:34 +00007737 // So we treat the LHS as a ignored value, and in C++ we allow the
7738 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007739 LHS = S.IgnoredValueConversions(LHS.take());
7740 if (LHS.isInvalid())
7741 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007742
Eli Friedmana6115062012-05-24 00:47:05 +00007743 S.DiagnoseUnusedExprResult(LHS.get());
7744
David Blaikie4e4d0842012-03-11 07:00:24 +00007745 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007746 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7747 if (RHS.isInvalid())
7748 return QualType();
7749 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007750 S.RequireCompleteType(Loc, RHS.get()->getType(),
7751 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007752 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007753
John Wiegley429bb272011-04-08 18:41:53 +00007754 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007755}
7756
Steve Naroff49b45262007-07-13 16:58:59 +00007757/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7758/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007759static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7760 ExprValueKind &VK,
7761 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007762 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007763 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007764 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007765
Chris Lattner3528d352008-11-21 07:05:48 +00007766 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007767 // Atomic types can be used for increment / decrement where the non-atomic
7768 // versions can, so ignore the _Atomic() specifier for the purpose of
7769 // checking.
7770 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7771 ResType = ResAtomicType->getValueType();
7772
Chris Lattner3528d352008-11-21 07:05:48 +00007773 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007774
David Blaikie4e4d0842012-03-11 07:00:24 +00007775 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007776 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007777 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007778 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007779 return QualType();
7780 }
7781 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007782 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007783 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007784 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007785 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007786 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007787 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007788 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007789 } else if (ResType->isObjCObjectPointerType()) {
7790 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7791 // Otherwise, we just need a complete type.
7792 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7793 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7794 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007795 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007796 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007797 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007798 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007799 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007800 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007801 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007802 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007803 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007804 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007805 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007806 } else {
John McCall09431682010-11-18 19:01:18 +00007807 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007808 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007809 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007810 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007811 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007812 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007813 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007814 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007815 // In C++, a prefix increment is the same type as the operand. Otherwise
7816 // (in C or with postfix), the increment is the unqualified type of the
7817 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007818 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007819 VK = VK_LValue;
7820 return ResType;
7821 } else {
7822 VK = VK_RValue;
7823 return ResType.getUnqualifiedType();
7824 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007825}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007826
7827
Anders Carlsson369dee42008-02-01 07:15:58 +00007828/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007829/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007830/// where the declaration is needed for type checking. We only need to
7831/// handle cases when the expression references a function designator
7832/// or is an lvalue. Here are some examples:
7833/// - &(x) => x
7834/// - &*****f => f for f a function designator.
7835/// - &s.xx => s
7836/// - &s.zz[1].yy -> s, if zz is an array
7837/// - *(x + 1) -> x, if x is an array
7838/// - &"123"[2] -> 0
7839/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007840static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007841 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007842 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007843 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007844 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007845 // If this is an arrow operator, the address is an offset from
7846 // the base's value, so the object the base refers to is
7847 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007848 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007849 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007850 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007851 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007852 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007853 // FIXME: This code shouldn't be necessary! We should catch the implicit
7854 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007855 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7856 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7857 if (ICE->getSubExpr()->getType()->isArrayType())
7858 return getPrimaryDecl(ICE->getSubExpr());
7859 }
7860 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007861 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007862 case Stmt::UnaryOperatorClass: {
7863 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007864
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007865 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007866 case UO_Real:
7867 case UO_Imag:
7868 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007869 return getPrimaryDecl(UO->getSubExpr());
7870 default:
7871 return 0;
7872 }
7873 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007874 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007875 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007876 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007877 // If the result of an implicit cast is an l-value, we care about
7878 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007879 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007880 default:
7881 return 0;
7882 }
7883}
7884
Richard Trieu5520f232011-09-07 21:46:33 +00007885namespace {
7886 enum {
7887 AO_Bit_Field = 0,
7888 AO_Vector_Element = 1,
7889 AO_Property_Expansion = 2,
7890 AO_Register_Variable = 3,
7891 AO_No_Error = 4
7892 };
7893}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007894/// \brief Diagnose invalid operand for address of operations.
7895///
7896/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007897static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7898 Expr *E, unsigned Type) {
7899 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7900}
7901
Reid Spencer5f016e22007-07-11 17:01:13 +00007902/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007903/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007904/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007905/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007906/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007907/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007908/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007909static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007910 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007911 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7912 if (PTy->getKind() == BuiltinType::Overload) {
7913 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7914 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7915 << OrigOp.get()->getSourceRange();
7916 return QualType();
7917 }
7918
7919 return S.Context.OverloadTy;
7920 }
7921
7922 if (PTy->getKind() == BuiltinType::UnknownAny)
7923 return S.Context.UnknownAnyTy;
7924
7925 if (PTy->getKind() == BuiltinType::BoundMember) {
7926 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7927 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007928 return QualType();
7929 }
John McCall3c3b7f92011-10-25 17:37:35 +00007930
7931 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7932 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007933 }
John McCall9c72c602010-08-27 09:08:28 +00007934
John McCall3c3b7f92011-10-25 17:37:35 +00007935 if (OrigOp.get()->isTypeDependent())
7936 return S.Context.DependentTy;
7937
7938 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007939
John McCall9c72c602010-08-27 09:08:28 +00007940 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007941 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007942
David Blaikie4e4d0842012-03-11 07:00:24 +00007943 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007944 // Implement C99-only parts of addressof rules.
7945 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007946 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007947 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7948 // (assuming the deref expression is valid).
7949 return uOp->getSubExpr()->getType();
7950 }
7951 // Technically, there should be a check for array subscript
7952 // expressions here, but the result of one is always an lvalue anyway.
7953 }
John McCall5808ce42011-02-03 08:15:49 +00007954 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007955 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007956 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007957
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007958 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007959 bool sfinae = S.isSFINAEContext();
7960 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7961 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007962 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007963 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007964 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007965 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007966 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007967 } else if (lval == Expr::LV_MemberFunction) {
7968 // If it's an instance method, make a member pointer.
7969 // The expression must have exactly the form &A::foo.
7970
7971 // If the underlying expression isn't a decl ref, give up.
7972 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007973 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007974 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007975 return QualType();
7976 }
7977 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7978 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7979
7980 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007981 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007982 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007983 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007984
7985 // The method was named without a qualifier.
7986 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007987 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007988 << op->getSourceRange();
7989 }
7990
John McCall09431682010-11-18 19:01:18 +00007991 return S.Context.getMemberPointerType(op->getType(),
7992 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007993 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007994 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007995 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007996 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007997 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007998 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007999 AddressOfError = AO_Property_Expansion;
8000 } else {
8001 // FIXME: emit more specific diag...
8002 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8003 << op->getSourceRange();
8004 return QualType();
8005 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008006 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008007 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008008 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008009 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008010 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008011 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008012 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008013 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008014 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008015 // with the register storage-class specifier.
8016 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008017 // in C++ it is not error to take address of a register
8018 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008019 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008020 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008021 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008022 }
John McCallba135432009-11-21 08:51:07 +00008023 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008024 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008025 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008026 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008027 // Could be a pointer to member, though, if there is an explicit
8028 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008029 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008030 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008031 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008032 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008033 S.Diag(OpLoc,
8034 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008035 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008036 return QualType();
8037 }
Mike Stump1eb44332009-09-09 15:08:12 +00008038
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008039 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8040 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008041 return S.Context.getMemberPointerType(op->getType(),
8042 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008043 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008044 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008045 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008046 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008047 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008048
Richard Trieu5520f232011-09-07 21:46:33 +00008049 if (AddressOfError != AO_No_Error) {
8050 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8051 return QualType();
8052 }
8053
Eli Friedman441cf102009-05-16 23:27:50 +00008054 if (lval == Expr::LV_IncompleteVoidType) {
8055 // Taking the address of a void variable is technically illegal, but we
8056 // allow it in cases which are otherwise valid.
8057 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008058 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008059 }
8060
Reid Spencer5f016e22007-07-11 17:01:13 +00008061 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008062 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008063 return S.Context.getObjCObjectPointerType(op->getType());
8064 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008065}
8066
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008067/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008068static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8069 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008070 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008071 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008072
John Wiegley429bb272011-04-08 18:41:53 +00008073 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8074 if (ConvResult.isInvalid())
8075 return QualType();
8076 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008077 QualType OpTy = Op->getType();
8078 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008079
8080 if (isa<CXXReinterpretCastExpr>(Op)) {
8081 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8082 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8083 Op->getSourceRange());
8084 }
8085
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008086 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8087 // is an incomplete type or void. It would be possible to warn about
8088 // dereferencing a void pointer, but it's completely well-defined, and such a
8089 // warning is unlikely to catch any mistakes.
8090 if (const PointerType *PT = OpTy->getAs<PointerType>())
8091 Result = PT->getPointeeType();
8092 else if (const ObjCObjectPointerType *OPT =
8093 OpTy->getAs<ObjCObjectPointerType>())
8094 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008095 else {
John McCallfb8721c2011-04-10 19:13:55 +00008096 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008097 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008098 if (PR.take() != Op)
8099 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008100 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008101
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008102 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008103 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008104 << OpTy << Op->getSourceRange();
8105 return QualType();
8106 }
John McCall09431682010-11-18 19:01:18 +00008107
8108 // Dereferences are usually l-values...
8109 VK = VK_LValue;
8110
8111 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008112 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008113 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008114
8115 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008116}
8117
John McCall2de56d12010-08-25 11:45:40 +00008118static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008119 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008120 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008121 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008122 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008123 case tok::periodstar: Opc = BO_PtrMemD; break;
8124 case tok::arrowstar: Opc = BO_PtrMemI; break;
8125 case tok::star: Opc = BO_Mul; break;
8126 case tok::slash: Opc = BO_Div; break;
8127 case tok::percent: Opc = BO_Rem; break;
8128 case tok::plus: Opc = BO_Add; break;
8129 case tok::minus: Opc = BO_Sub; break;
8130 case tok::lessless: Opc = BO_Shl; break;
8131 case tok::greatergreater: Opc = BO_Shr; break;
8132 case tok::lessequal: Opc = BO_LE; break;
8133 case tok::less: Opc = BO_LT; break;
8134 case tok::greaterequal: Opc = BO_GE; break;
8135 case tok::greater: Opc = BO_GT; break;
8136 case tok::exclaimequal: Opc = BO_NE; break;
8137 case tok::equalequal: Opc = BO_EQ; break;
8138 case tok::amp: Opc = BO_And; break;
8139 case tok::caret: Opc = BO_Xor; break;
8140 case tok::pipe: Opc = BO_Or; break;
8141 case tok::ampamp: Opc = BO_LAnd; break;
8142 case tok::pipepipe: Opc = BO_LOr; break;
8143 case tok::equal: Opc = BO_Assign; break;
8144 case tok::starequal: Opc = BO_MulAssign; break;
8145 case tok::slashequal: Opc = BO_DivAssign; break;
8146 case tok::percentequal: Opc = BO_RemAssign; break;
8147 case tok::plusequal: Opc = BO_AddAssign; break;
8148 case tok::minusequal: Opc = BO_SubAssign; break;
8149 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8150 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8151 case tok::ampequal: Opc = BO_AndAssign; break;
8152 case tok::caretequal: Opc = BO_XorAssign; break;
8153 case tok::pipeequal: Opc = BO_OrAssign; break;
8154 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008155 }
8156 return Opc;
8157}
8158
John McCall2de56d12010-08-25 11:45:40 +00008159static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008160 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008161 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008162 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008163 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008164 case tok::plusplus: Opc = UO_PreInc; break;
8165 case tok::minusminus: Opc = UO_PreDec; break;
8166 case tok::amp: Opc = UO_AddrOf; break;
8167 case tok::star: Opc = UO_Deref; break;
8168 case tok::plus: Opc = UO_Plus; break;
8169 case tok::minus: Opc = UO_Minus; break;
8170 case tok::tilde: Opc = UO_Not; break;
8171 case tok::exclaim: Opc = UO_LNot; break;
8172 case tok::kw___real: Opc = UO_Real; break;
8173 case tok::kw___imag: Opc = UO_Imag; break;
8174 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008175 }
8176 return Opc;
8177}
8178
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008179/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8180/// This warning is only emitted for builtin assignment operations. It is also
8181/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008182static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008183 SourceLocation OpLoc) {
8184 if (!S.ActiveTemplateInstantiations.empty())
8185 return;
8186 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8187 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008188 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8189 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8190 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8191 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8192 if (!LHSDeclRef || !RHSDeclRef ||
8193 LHSDeclRef->getLocation().isMacroID() ||
8194 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008195 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008196 const ValueDecl *LHSDecl =
8197 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8198 const ValueDecl *RHSDecl =
8199 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8200 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008201 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008202 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008203 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008204 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008205 if (RefTy->getPointeeType().isVolatileQualified())
8206 return;
8207
8208 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008209 << LHSDeclRef->getType()
8210 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008211}
8212
Douglas Gregoreaebc752008-11-06 23:29:22 +00008213/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8214/// operator @p Opc at location @c TokLoc. This routine only supports
8215/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008216ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008217 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008218 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008219 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008220 // The syntax only allows initializer lists on the RHS of assignment,
8221 // so we don't need to worry about accepting invalid code for
8222 // non-assignment operators.
8223 // C++11 5.17p9:
8224 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8225 // of x = {} is x = T().
8226 InitializationKind Kind =
8227 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8228 InitializedEntity Entity =
8229 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8230 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008231 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008232 if (Init.isInvalid())
8233 return Init;
8234 RHSExpr = Init.take();
8235 }
8236
Richard Trieu78ea78b2011-09-07 01:49:20 +00008237 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008238 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008239 // The following two variables are used for compound assignment operators
8240 QualType CompLHSTy; // Type of LHS after promotions for computation
8241 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008242 ExprValueKind VK = VK_RValue;
8243 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008244
8245 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008246 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008247 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008248 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008249 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8250 VK = LHS.get()->getValueKind();
8251 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008252 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008253 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008254 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008255 break;
John McCall2de56d12010-08-25 11:45:40 +00008256 case BO_PtrMemD:
8257 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008258 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008259 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008260 break;
John McCall2de56d12010-08-25 11:45:40 +00008261 case BO_Mul:
8262 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008263 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008264 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008265 break;
John McCall2de56d12010-08-25 11:45:40 +00008266 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008267 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008268 break;
John McCall2de56d12010-08-25 11:45:40 +00008269 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008270 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008271 break;
John McCall2de56d12010-08-25 11:45:40 +00008272 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008273 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008274 break;
John McCall2de56d12010-08-25 11:45:40 +00008275 case BO_Shl:
8276 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008277 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008278 break;
John McCall2de56d12010-08-25 11:45:40 +00008279 case BO_LE:
8280 case BO_LT:
8281 case BO_GE:
8282 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008283 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008284 break;
John McCall2de56d12010-08-25 11:45:40 +00008285 case BO_EQ:
8286 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008287 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008288 break;
John McCall2de56d12010-08-25 11:45:40 +00008289 case BO_And:
8290 case BO_Xor:
8291 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008292 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008293 break;
John McCall2de56d12010-08-25 11:45:40 +00008294 case BO_LAnd:
8295 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008296 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008297 break;
John McCall2de56d12010-08-25 11:45:40 +00008298 case BO_MulAssign:
8299 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008300 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008301 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008302 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008303 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8304 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008305 break;
John McCall2de56d12010-08-25 11:45:40 +00008306 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008307 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008308 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008309 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8310 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008311 break;
John McCall2de56d12010-08-25 11:45:40 +00008312 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008313 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
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_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008318 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8319 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8320 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008321 break;
John McCall2de56d12010-08-25 11:45:40 +00008322 case BO_ShlAssign:
8323 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008324 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008325 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008326 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8327 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008328 break;
John McCall2de56d12010-08-25 11:45:40 +00008329 case BO_AndAssign:
8330 case BO_XorAssign:
8331 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008332 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008333 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008334 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8335 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008336 break;
John McCall2de56d12010-08-25 11:45:40 +00008337 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008338 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008339 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008340 VK = RHS.get()->getValueKind();
8341 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008342 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008343 break;
8344 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008345 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008346 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008347
8348 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008349 CheckArrayAccess(LHS.get());
8350 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008351
Eli Friedmanab3a8522009-03-28 01:22:36 +00008352 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008353 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008354 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008355 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008356 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008357 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008358 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008359 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008360 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008361 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008362 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008363}
8364
Sebastian Redlaee3c932009-10-27 12:10:02 +00008365/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8366/// operators are mixed in a way that suggests that the programmer forgot that
8367/// comparison operators have higher precedence. The most typical example of
8368/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008369static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008370 SourceLocation OpLoc, Expr *LHSExpr,
8371 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008372 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008373 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8374 RHSopc = static_cast<BinOp::Opcode>(-1);
8375 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8376 LHSopc = BO->getOpcode();
8377 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8378 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008379
8380 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008381 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008382 return;
8383
8384 // Bitwise operations are sometimes used as eager logical ops.
8385 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008386 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8387 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008388 return;
8389
Richard Trieu78ea78b2011-09-07 01:49:20 +00008390 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8391 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008392 if (!isLeftComp && !isRightComp) return;
8393
Richard Trieu78ea78b2011-09-07 01:49:20 +00008394 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8395 OpLoc)
8396 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8397 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8398 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008399 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008400 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8401 RHSExpr->getLocEnd())
8402 : SourceRange(LHSExpr->getLocStart(),
8403 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008404
8405 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8406 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8407 SuggestParentheses(Self, OpLoc,
8408 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008409 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008410 SuggestParentheses(Self, OpLoc,
8411 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8412 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008413}
8414
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008415/// \brief It accepts a '&' expr that is inside a '|' one.
8416/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8417/// in parentheses.
8418static void
8419EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8420 BinaryOperator *Bop) {
8421 assert(Bop->getOpcode() == BO_And);
8422 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8423 << Bop->getSourceRange() << OpLoc;
8424 SuggestParentheses(Self, Bop->getOperatorLoc(),
8425 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8426 Bop->getSourceRange());
8427}
8428
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008429/// \brief It accepts a '&&' expr that is inside a '||' one.
8430/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8431/// in parentheses.
8432static void
8433EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008434 BinaryOperator *Bop) {
8435 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008436 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8437 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008438 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008439 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008440 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008441}
8442
8443/// \brief Returns true if the given expression can be evaluated as a constant
8444/// 'true'.
8445static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8446 bool Res;
8447 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8448}
8449
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008450/// \brief Returns true if the given expression can be evaluated as a constant
8451/// 'false'.
8452static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8453 bool Res;
8454 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8455}
8456
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008457/// \brief Look for '&&' in the left hand of a '||' expr.
8458static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008459 Expr *LHSExpr, Expr *RHSExpr) {
8460 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008461 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008462 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008463 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008464 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008465 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8466 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8467 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8468 } else if (Bop->getOpcode() == BO_LOr) {
8469 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8470 // If it's "a || b && 1 || c" we didn't warn earlier for
8471 // "a || b && 1", but warn now.
8472 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8473 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8474 }
8475 }
8476 }
8477}
8478
8479/// \brief Look for '&&' in the right hand of a '||' expr.
8480static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008481 Expr *LHSExpr, Expr *RHSExpr) {
8482 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008483 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008484 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008485 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008486 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008487 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8488 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8489 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008490 }
8491 }
8492}
8493
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008494/// \brief Look for '&' in the left or right hand of a '|' expr.
8495static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8496 Expr *OrArg) {
8497 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8498 if (Bop->getOpcode() == BO_And)
8499 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8500 }
8501}
8502
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008503/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008504/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008505static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008506 SourceLocation OpLoc, Expr *LHSExpr,
8507 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008508 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008509 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008510 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008511
8512 // Diagnose "arg1 & arg2 | arg3"
8513 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008514 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8515 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008516 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008517
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008518 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8519 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008520 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008521 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8522 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008523 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008524}
8525
Reid Spencer5f016e22007-07-11 17:01:13 +00008526// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008527ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008528 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008529 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008530 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008531 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8532 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008533
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008534 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008535 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008536
Richard Trieubefece12011-09-07 02:02:10 +00008537 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008538}
8539
John McCall3c3b7f92011-10-25 17:37:35 +00008540/// Build an overloaded binary operator expression in the given scope.
8541static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8542 BinaryOperatorKind Opc,
8543 Expr *LHS, Expr *RHS) {
8544 // Find all of the overloaded operators visible from this
8545 // point. We perform both an operator-name lookup from the local
8546 // scope and an argument-dependent lookup based on the types of
8547 // the arguments.
8548 UnresolvedSet<16> Functions;
8549 OverloadedOperatorKind OverOp
8550 = BinaryOperator::getOverloadedOperator(Opc);
8551 if (Sc && OverOp != OO_None)
8552 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8553 RHS->getType(), Functions);
8554
8555 // Build the (potentially-overloaded, potentially-dependent)
8556 // binary operation.
8557 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8558}
8559
John McCall60d7b3a2010-08-24 06:29:42 +00008560ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008561 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008562 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008563 // We want to end up calling one of checkPseudoObjectAssignment
8564 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8565 // both expressions are overloadable or either is type-dependent),
8566 // or CreateBuiltinBinOp (in any other case). We also want to get
8567 // any placeholder types out of the way.
8568
John McCall3c3b7f92011-10-25 17:37:35 +00008569 // Handle pseudo-objects in the LHS.
8570 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8571 // Assignments with a pseudo-object l-value need special analysis.
8572 if (pty->getKind() == BuiltinType::PseudoObject &&
8573 BinaryOperator::isAssignmentOp(Opc))
8574 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8575
8576 // Don't resolve overloads if the other type is overloadable.
8577 if (pty->getKind() == BuiltinType::Overload) {
8578 // We can't actually test that if we still have a placeholder,
8579 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008580 // code below are valid when the LHS is an overload set. Note
8581 // that an overload set can be dependently-typed, but it never
8582 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008583 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8584 if (resolvedRHS.isInvalid()) return ExprError();
8585 RHSExpr = resolvedRHS.take();
8586
John McCallac516502011-10-28 01:04:34 +00008587 if (RHSExpr->isTypeDependent() ||
8588 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008589 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8590 }
8591
8592 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8593 if (LHS.isInvalid()) return ExprError();
8594 LHSExpr = LHS.take();
8595 }
8596
8597 // Handle pseudo-objects in the RHS.
8598 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8599 // An overload in the RHS can potentially be resolved by the type
8600 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008601 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8602 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8603 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8604
Eli Friedman87884912012-01-17 21:27:43 +00008605 if (LHSExpr->getType()->isOverloadableType())
8606 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8607
John McCall3c3b7f92011-10-25 17:37:35 +00008608 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008609 }
John McCall3c3b7f92011-10-25 17:37:35 +00008610
8611 // Don't resolve overloads if the other type is overloadable.
8612 if (pty->getKind() == BuiltinType::Overload &&
8613 LHSExpr->getType()->isOverloadableType())
8614 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8615
8616 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8617 if (!resolvedRHS.isUsable()) return ExprError();
8618 RHSExpr = resolvedRHS.take();
8619 }
8620
David Blaikie4e4d0842012-03-11 07:00:24 +00008621 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008622 // If either expression is type-dependent, always build an
8623 // overloaded op.
8624 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8625 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008626
John McCallac516502011-10-28 01:04:34 +00008627 // Otherwise, build an overloaded op if either expression has an
8628 // overloadable type.
8629 if (LHSExpr->getType()->isOverloadableType() ||
8630 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008631 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008632 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008633
Douglas Gregoreaebc752008-11-06 23:29:22 +00008634 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008635 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008636}
8637
John McCall60d7b3a2010-08-24 06:29:42 +00008638ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008639 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008640 Expr *InputExpr) {
8641 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008642 ExprValueKind VK = VK_RValue;
8643 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008644 QualType resultType;
8645 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008646 case UO_PreInc:
8647 case UO_PreDec:
8648 case UO_PostInc:
8649 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008650 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008651 Opc == UO_PreInc ||
8652 Opc == UO_PostInc,
8653 Opc == UO_PreInc ||
8654 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008655 break;
John McCall2de56d12010-08-25 11:45:40 +00008656 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008657 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008658 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008659 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008660 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008661 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008662 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008663 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008664 }
John McCall2de56d12010-08-25 11:45:40 +00008665 case UO_Plus:
8666 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008667 Input = UsualUnaryConversions(Input.take());
8668 if (Input.isInvalid()) return ExprError();
8669 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008670 if (resultType->isDependentType())
8671 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008672 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8673 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008674 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008675 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008676 resultType->isEnumeralType())
8677 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008678 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008679 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008680 resultType->isPointerType())
8681 break;
8682
Sebastian Redl0eb23302009-01-19 00:08:26 +00008683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008684 << resultType << Input.get()->getSourceRange());
8685
John McCall2de56d12010-08-25 11:45:40 +00008686 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008687 Input = UsualUnaryConversions(Input.take());
8688 if (Input.isInvalid()) return ExprError();
8689 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008690 if (resultType->isDependentType())
8691 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008692 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8693 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8694 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008695 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008696 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008697 else if (resultType->hasIntegerRepresentation())
8698 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008699 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008700 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008701 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008702 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008703 break;
John Wiegley429bb272011-04-08 18:41:53 +00008704
John McCall2de56d12010-08-25 11:45:40 +00008705 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008706 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008707 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8708 if (Input.isInvalid()) return ExprError();
8709 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008710
8711 // Though we still have to promote half FP to float...
8712 if (resultType->isHalfType()) {
8713 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8714 resultType = Context.FloatTy;
8715 }
8716
Sebastian Redl28507842009-02-26 14:39:58 +00008717 if (resultType->isDependentType())
8718 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008719 if (resultType->isScalarType()) {
8720 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008721 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008722 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8723 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008724 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8725 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008726 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008727 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008728 // Vector logical not returns the signed variant of the operand type.
8729 resultType = GetSignedVectorType(resultType);
8730 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008731 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008732 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008733 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008734 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008735
Reid Spencer5f016e22007-07-11 17:01:13 +00008736 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008737 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008738 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008739 break;
John McCall2de56d12010-08-25 11:45:40 +00008740 case UO_Real:
8741 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008742 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008743 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8744 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008745 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008746 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8747 if (Input.get()->getValueKind() != VK_RValue &&
8748 Input.get()->getObjectKind() == OK_Ordinary)
8749 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008750 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008751 // In C, a volatile scalar is read by __imag. In C++, it is not.
8752 Input = DefaultLvalueConversion(Input.take());
8753 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008754 break;
John McCall2de56d12010-08-25 11:45:40 +00008755 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008756 resultType = Input.get()->getType();
8757 VK = Input.get()->getValueKind();
8758 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008759 break;
8760 }
John Wiegley429bb272011-04-08 18:41:53 +00008761 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008762 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008763
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008764 // Check for array bounds violations in the operand of the UnaryOperator,
8765 // except for the '*' and '&' operators that have to be handled specially
8766 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8767 // that are explicitly defined as valid by the standard).
8768 if (Opc != UO_AddrOf && Opc != UO_Deref)
8769 CheckArrayAccess(Input.get());
8770
John Wiegley429bb272011-04-08 18:41:53 +00008771 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008772 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008773}
8774
Douglas Gregord3d08532011-12-14 21:23:13 +00008775/// \brief Determine whether the given expression is a qualified member
8776/// access expression, of a form that could be turned into a pointer to member
8777/// with the address-of operator.
8778static bool isQualifiedMemberAccess(Expr *E) {
8779 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8780 if (!DRE->getQualifier())
8781 return false;
8782
8783 ValueDecl *VD = DRE->getDecl();
8784 if (!VD->isCXXClassMember())
8785 return false;
8786
8787 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8788 return true;
8789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8790 return Method->isInstance();
8791
8792 return false;
8793 }
8794
8795 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8796 if (!ULE->getQualifier())
8797 return false;
8798
8799 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8800 DEnd = ULE->decls_end();
8801 D != DEnd; ++D) {
8802 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8803 if (Method->isInstance())
8804 return true;
8805 } else {
8806 // Overload set does not contain methods.
8807 break;
8808 }
8809 }
8810
8811 return false;
8812 }
8813
8814 return false;
8815}
8816
John McCall60d7b3a2010-08-24 06:29:42 +00008817ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008818 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008819 // First things first: handle placeholders so that the
8820 // overloaded-operator check considers the right type.
8821 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8822 // Increment and decrement of pseudo-object references.
8823 if (pty->getKind() == BuiltinType::PseudoObject &&
8824 UnaryOperator::isIncrementDecrementOp(Opc))
8825 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8826
8827 // extension is always a builtin operator.
8828 if (Opc == UO_Extension)
8829 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8830
8831 // & gets special logic for several kinds of placeholder.
8832 // The builtin code knows what to do.
8833 if (Opc == UO_AddrOf &&
8834 (pty->getKind() == BuiltinType::Overload ||
8835 pty->getKind() == BuiltinType::UnknownAny ||
8836 pty->getKind() == BuiltinType::BoundMember))
8837 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8838
8839 // Anything else needs to be handled now.
8840 ExprResult Result = CheckPlaceholderExpr(Input);
8841 if (Result.isInvalid()) return ExprError();
8842 Input = Result.take();
8843 }
8844
David Blaikie4e4d0842012-03-11 07:00:24 +00008845 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008846 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8847 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008848 // Find all of the overloaded operators visible from this
8849 // point. We perform both an operator-name lookup from the local
8850 // scope and an argument-dependent lookup based on the types of
8851 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008852 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008853 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008854 if (S && OverOp != OO_None)
8855 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8856 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008857
John McCall9ae2f072010-08-23 23:25:46 +00008858 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008859 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008860
John McCall9ae2f072010-08-23 23:25:46 +00008861 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008862}
8863
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008864// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008865ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008866 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008867 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008868}
8869
Steve Naroff1b273c42007-09-16 14:56:35 +00008870/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008871ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008872 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008873 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008874 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008875 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008876 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008877}
8878
John McCallf85e1932011-06-15 23:02:42 +00008879/// Given the last statement in a statement-expression, check whether
8880/// the result is a producing expression (like a call to an
8881/// ns_returns_retained function) and, if so, rebuild it to hoist the
8882/// release out of the full-expression. Otherwise, return null.
8883/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008884static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008885 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008886 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008887 if (!cleanups) return 0;
8888
8889 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008890 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008891 return 0;
8892
8893 // Splice out the cast. This shouldn't modify any interesting
8894 // features of the statement.
8895 Expr *producer = cast->getSubExpr();
8896 assert(producer->getType() == cast->getType());
8897 assert(producer->getValueKind() == cast->getValueKind());
8898 cleanups->setSubExpr(producer);
8899 return cleanups;
8900}
8901
John McCall73f428c2012-04-04 01:27:53 +00008902void Sema::ActOnStartStmtExpr() {
8903 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8904}
8905
8906void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008907 // Note that function is also called by TreeTransform when leaving a
8908 // StmtExpr scope without rebuilding anything.
8909
John McCall73f428c2012-04-04 01:27:53 +00008910 DiscardCleanupsInEvaluationContext();
8911 PopExpressionEvaluationContext();
8912}
8913
John McCall60d7b3a2010-08-24 06:29:42 +00008914ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008915Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008916 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008917 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8918 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8919
John McCall73f428c2012-04-04 01:27:53 +00008920 if (hasAnyUnrecoverableErrorsInThisFunction())
8921 DiscardCleanupsInEvaluationContext();
8922 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8923 PopExpressionEvaluationContext();
8924
Douglas Gregordd8f5692010-03-10 04:54:39 +00008925 bool isFileScope
8926 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008927 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008928 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008929
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008930 // FIXME: there are a variety of strange constraints to enforce here, for
8931 // example, it is not possible to goto into a stmt expression apparently.
8932 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008933
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008934 // If there are sub stmts in the compound stmt, take the type of the last one
8935 // as the type of the stmtexpr.
8936 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008937 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008938 if (!Compound->body_empty()) {
8939 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008940 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008941 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008942 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8943 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008944 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008945 }
John McCallf85e1932011-06-15 23:02:42 +00008946
John Wiegley429bb272011-04-08 18:41:53 +00008947 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008948 // Do function/array conversion on the last expression, but not
8949 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008950 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8951 if (LastExpr.isInvalid())
8952 return ExprError();
8953 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008954
John Wiegley429bb272011-04-08 18:41:53 +00008955 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008956 // In ARC, if the final expression ends in a consume, splice
8957 // the consume out and bind it later. In the alternate case
8958 // (when dealing with a retainable type), the result
8959 // initialization will create a produce. In both cases the
8960 // result will be +1, and we'll need to balance that out with
8961 // a bind.
8962 if (Expr *rebuiltLastStmt
8963 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8964 LastExpr = rebuiltLastStmt;
8965 } else {
8966 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008967 InitializedEntity::InitializeResult(LPLoc,
8968 Ty,
8969 false),
8970 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008971 LastExpr);
8972 }
8973
John Wiegley429bb272011-04-08 18:41:53 +00008974 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008975 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008976 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008977 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008978 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008979 else
John Wiegley429bb272011-04-08 18:41:53 +00008980 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008981 StmtExprMayBindToTemp = true;
8982 }
8983 }
8984 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008985 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008986
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008987 // FIXME: Check that expression type is complete/non-abstract; statement
8988 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008989 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8990 if (StmtExprMayBindToTemp)
8991 return MaybeBindToTemporary(ResStmtExpr);
8992 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008993}
Steve Naroffd34e9152007-08-01 22:05:33 +00008994
John McCall60d7b3a2010-08-24 06:29:42 +00008995ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008996 TypeSourceInfo *TInfo,
8997 OffsetOfComponent *CompPtr,
8998 unsigned NumComponents,
8999 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009000 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009001 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009002 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009003
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009004 // We must have at least one component that refers to the type, and the first
9005 // one is known to be a field designator. Verify that the ArgTy represents
9006 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009007 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009008 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9009 << ArgTy << TypeRange);
9010
9011 // Type must be complete per C99 7.17p3 because a declaring a variable
9012 // with an incomplete type would be ill-formed.
9013 if (!Dependent
9014 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009015 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009016 return ExprError();
9017
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009018 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9019 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009020 // FIXME: This diagnostic isn't actually visible because the location is in
9021 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009022 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009023 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9024 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009025
9026 bool DidWarnAboutNonPOD = false;
9027 QualType CurrentType = ArgTy;
9028 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009029 SmallVector<OffsetOfNode, 4> Comps;
9030 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009031 for (unsigned i = 0; i != NumComponents; ++i) {
9032 const OffsetOfComponent &OC = CompPtr[i];
9033 if (OC.isBrackets) {
9034 // Offset of an array sub-field. TODO: Should we allow vector elements?
9035 if (!CurrentType->isDependentType()) {
9036 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9037 if(!AT)
9038 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9039 << CurrentType);
9040 CurrentType = AT->getElementType();
9041 } else
9042 CurrentType = Context.DependentTy;
9043
Richard Smithea011432011-10-17 23:29:39 +00009044 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9045 if (IdxRval.isInvalid())
9046 return ExprError();
9047 Expr *Idx = IdxRval.take();
9048
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009049 // The expression must be an integral expression.
9050 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009051 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9052 !Idx->getType()->isIntegerType())
9053 return ExprError(Diag(Idx->getLocStart(),
9054 diag::err_typecheck_subscript_not_integer)
9055 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009056
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009057 // Record this array index.
9058 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009059 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009060 continue;
9061 }
9062
9063 // Offset of a field.
9064 if (CurrentType->isDependentType()) {
9065 // We have the offset of a field, but we can't look into the dependent
9066 // type. Just record the identifier of the field.
9067 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9068 CurrentType = Context.DependentTy;
9069 continue;
9070 }
9071
9072 // We need to have a complete type to look into.
9073 if (RequireCompleteType(OC.LocStart, CurrentType,
9074 diag::err_offsetof_incomplete_type))
9075 return ExprError();
9076
9077 // Look for the designated field.
9078 const RecordType *RC = CurrentType->getAs<RecordType>();
9079 if (!RC)
9080 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9081 << CurrentType);
9082 RecordDecl *RD = RC->getDecl();
9083
9084 // C++ [lib.support.types]p5:
9085 // The macro offsetof accepts a restricted set of type arguments in this
9086 // International Standard. type shall be a POD structure or a POD union
9087 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009088 // C++11 [support.types]p4:
9089 // If type is not a standard-layout class (Clause 9), the results are
9090 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009091 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009092 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9093 unsigned DiagID =
9094 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9095 : diag::warn_offsetof_non_pod_type;
9096
9097 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009098 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009099 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009100 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9101 << CurrentType))
9102 DidWarnAboutNonPOD = true;
9103 }
9104
9105 // Look for the field.
9106 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9107 LookupQualifiedName(R, RD);
9108 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009109 IndirectFieldDecl *IndirectMemberDecl = 0;
9110 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009111 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009112 MemberDecl = IndirectMemberDecl->getAnonField();
9113 }
9114
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009115 if (!MemberDecl)
9116 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9117 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9118 OC.LocEnd));
9119
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009120 // C99 7.17p3:
9121 // (If the specified member is a bit-field, the behavior is undefined.)
9122 //
9123 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009124 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009125 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9126 << MemberDecl->getDeclName()
9127 << SourceRange(BuiltinLoc, RParenLoc);
9128 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9129 return ExprError();
9130 }
Eli Friedman19410a72010-08-05 10:11:36 +00009131
9132 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009133 if (IndirectMemberDecl)
9134 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009135
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009136 // If the member was found in a base class, introduce OffsetOfNodes for
9137 // the base class indirections.
9138 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9139 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009140 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009141 CXXBasePath &Path = Paths.front();
9142 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9143 B != BEnd; ++B)
9144 Comps.push_back(OffsetOfNode(B->Base));
9145 }
Eli Friedman19410a72010-08-05 10:11:36 +00009146
Francois Pichet87c2e122010-11-21 06:08:52 +00009147 if (IndirectMemberDecl) {
9148 for (IndirectFieldDecl::chain_iterator FI =
9149 IndirectMemberDecl->chain_begin(),
9150 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9151 assert(isa<FieldDecl>(*FI));
9152 Comps.push_back(OffsetOfNode(OC.LocStart,
9153 cast<FieldDecl>(*FI), OC.LocEnd));
9154 }
9155 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009156 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009157
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009158 CurrentType = MemberDecl->getType().getNonReferenceType();
9159 }
9160
9161 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009162 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009163}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009164
John McCall60d7b3a2010-08-24 06:29:42 +00009165ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009166 SourceLocation BuiltinLoc,
9167 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009168 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009169 OffsetOfComponent *CompPtr,
9170 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009171 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009172
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009173 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009174 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009175 if (ArgTy.isNull())
9176 return ExprError();
9177
Eli Friedman5a15dc12010-08-05 10:15:45 +00009178 if (!ArgTInfo)
9179 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9180
9181 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009182 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009183}
9184
9185
John McCall60d7b3a2010-08-24 06:29:42 +00009186ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009187 Expr *CondExpr,
9188 Expr *LHSExpr, Expr *RHSExpr,
9189 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009190 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9191
John McCallf89e55a2010-11-18 06:31:45 +00009192 ExprValueKind VK = VK_RValue;
9193 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009194 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009195 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009196 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009197 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009198 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009199 } else {
9200 // The conditional expression is required to be a constant expression.
9201 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009202 ExprResult CondICE
9203 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9204 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009205 if (CondICE.isInvalid())
9206 return ExprError();
9207 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009208
Sebastian Redl28507842009-02-26 14:39:58 +00009209 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009210 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9211
9212 resType = ActiveExpr->getType();
9213 ValueDependent = ActiveExpr->isValueDependent();
9214 VK = ActiveExpr->getValueKind();
9215 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009216 }
9217
Sebastian Redlf53597f2009-03-15 17:47:39 +00009218 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009219 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009220 resType->isDependentType(),
9221 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009222}
9223
Steve Naroff4eb206b2008-09-03 18:15:37 +00009224//===----------------------------------------------------------------------===//
9225// Clang Extensions.
9226//===----------------------------------------------------------------------===//
9227
9228/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009229void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009230 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009231 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009232 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009233 if (CurScope)
9234 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009235 else
9236 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009237
Eli Friedman84b007f2012-01-26 03:00:14 +00009238 getCurBlock()->HasImplicitReturnType = true;
9239
John McCall538773c2011-11-11 03:19:12 +00009240 // Enter a new evaluation context to insulate the block from any
9241 // cleanups from the enclosing full-expression.
9242 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009243}
9244
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009245void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9246 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009247 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009248 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009249 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009250
John McCallbf1a0282010-06-04 23:28:52 +00009251 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009252 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009253
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009254 // FIXME: We should allow unexpanded parameter packs here, but that would,
9255 // in turn, make the block expression contain unexpanded parameter packs.
9256 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9257 // Drop the parameters.
9258 FunctionProtoType::ExtProtoInfo EPI;
9259 EPI.HasTrailingReturn = false;
9260 EPI.TypeQuals |= DeclSpec::TQ_const;
9261 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9262 EPI);
9263 Sig = Context.getTrivialTypeSourceInfo(T);
9264 }
9265
John McCall711c52b2011-01-05 12:14:39 +00009266 // GetTypeForDeclarator always produces a function type for a block
9267 // literal signature. Furthermore, it is always a FunctionProtoType
9268 // unless the function was written with a typedef.
9269 assert(T->isFunctionType() &&
9270 "GetTypeForDeclarator made a non-function block signature");
9271
9272 // Look for an explicit signature in that function type.
9273 FunctionProtoTypeLoc ExplicitSignature;
9274
9275 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9276 if (isa<FunctionProtoTypeLoc>(tmp)) {
9277 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9278
9279 // Check whether that explicit signature was synthesized by
9280 // GetTypeForDeclarator. If so, don't save that as part of the
9281 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009282 if (ExplicitSignature.getLocalRangeBegin() ==
9283 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009284 // This would be much cheaper if we stored TypeLocs instead of
9285 // TypeSourceInfos.
9286 TypeLoc Result = ExplicitSignature.getResultLoc();
9287 unsigned Size = Result.getFullDataSize();
9288 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9289 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9290
9291 ExplicitSignature = FunctionProtoTypeLoc();
9292 }
John McCall82dc0092010-06-04 11:21:44 +00009293 }
Mike Stump1eb44332009-09-09 15:08:12 +00009294
John McCall711c52b2011-01-05 12:14:39 +00009295 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9296 CurBlock->FunctionType = T;
9297
9298 const FunctionType *Fn = T->getAs<FunctionType>();
9299 QualType RetTy = Fn->getResultType();
9300 bool isVariadic =
9301 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9302
John McCallc71a4912010-06-04 19:02:56 +00009303 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009304
John McCall82dc0092010-06-04 11:21:44 +00009305 // Don't allow returning a objc interface by value.
9306 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009307 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009308 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9309 return;
9310 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009311
John McCall82dc0092010-06-04 11:21:44 +00009312 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009313 // return type. TODO: what should we do with declarators like:
9314 // ^ * { ... }
9315 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009316 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009317 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009318 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009319 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009320 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009321
John McCall82dc0092010-06-04 11:21:44 +00009322 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009323 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009324 if (ExplicitSignature) {
9325 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9326 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009327 if (Param->getIdentifier() == 0 &&
9328 !Param->isImplicit() &&
9329 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009330 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009331 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009332 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009333 }
John McCall82dc0092010-06-04 11:21:44 +00009334
9335 // Fake up parameter variables if we have a typedef, like
9336 // ^ fntype { ... }
9337 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9338 for (FunctionProtoType::arg_type_iterator
9339 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9340 ParmVarDecl *Param =
9341 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009342 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009343 *I);
John McCallc71a4912010-06-04 19:02:56 +00009344 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009345 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009346 }
John McCall82dc0092010-06-04 11:21:44 +00009347
John McCallc71a4912010-06-04 19:02:56 +00009348 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009349 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009350 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009351 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9352 CurBlock->TheDecl->param_end(),
9353 /*CheckParameterNames=*/false);
9354 }
9355
John McCall82dc0092010-06-04 11:21:44 +00009356 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009357 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009358
John McCall82dc0092010-06-04 11:21:44 +00009359 // Put the parameter variables in scope. We can bail out immediately
9360 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009361 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009362 return;
9363
Steve Naroff090276f2008-10-10 01:28:17 +00009364 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009365 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9366 (*AI)->setOwningFunction(CurBlock->TheDecl);
9367
Steve Naroff090276f2008-10-10 01:28:17 +00009368 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009369 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009370 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009371
Steve Naroff090276f2008-10-10 01:28:17 +00009372 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009373 }
John McCall7a9813c2010-01-22 00:28:27 +00009374 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009375}
9376
9377/// ActOnBlockError - If there is an error parsing a block, this callback
9378/// is invoked to pop the information about the block from the action impl.
9379void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009380 // Leave the expression-evaluation context.
9381 DiscardCleanupsInEvaluationContext();
9382 PopExpressionEvaluationContext();
9383
Steve Naroff4eb206b2008-09-03 18:15:37 +00009384 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009385 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009386 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009387}
9388
9389/// ActOnBlockStmtExpr - This is called when the body of a block statement
9390/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009391ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009392 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009393 // If blocks are disabled, emit an error.
9394 if (!LangOpts.Blocks)
9395 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009396
John McCall538773c2011-11-11 03:19:12 +00009397 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009398 if (hasAnyUnrecoverableErrorsInThisFunction())
9399 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009400 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9401 PopExpressionEvaluationContext();
9402
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009403 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009404
9405 if (BSI->HasImplicitReturnType)
9406 deduceClosureReturnType(*BSI);
9407
Steve Naroff090276f2008-10-10 01:28:17 +00009408 PopDeclContext();
9409
Steve Naroff4eb206b2008-09-03 18:15:37 +00009410 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009411 if (!BSI->ReturnType.isNull())
9412 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009413
Mike Stump56925862009-07-28 22:04:01 +00009414 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009415 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009416
John McCall469a1eb2011-02-02 13:00:07 +00009417 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009418 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9419 SmallVector<BlockDecl::Capture, 4> Captures;
9420 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9421 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9422 if (Cap.isThisCapture())
9423 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009424 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009425 Cap.isNested(), Cap.getCopyExpr());
9426 Captures.push_back(NewCap);
9427 }
9428 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9429 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009430
John McCallc71a4912010-06-04 19:02:56 +00009431 // If the user wrote a function type in some form, try to use that.
9432 if (!BSI->FunctionType.isNull()) {
9433 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9434
9435 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9436 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9437
9438 // Turn protoless block types into nullary block types.
9439 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009440 FunctionProtoType::ExtProtoInfo EPI;
9441 EPI.ExtInfo = Ext;
9442 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009443
9444 // Otherwise, if we don't need to change anything about the function type,
9445 // preserve its sugar structure.
9446 } else if (FTy->getResultType() == RetTy &&
9447 (!NoReturn || FTy->getNoReturnAttr())) {
9448 BlockTy = BSI->FunctionType;
9449
9450 // Otherwise, make the minimal modifications to the function type.
9451 } else {
9452 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009453 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9454 EPI.TypeQuals = 0; // FIXME: silently?
9455 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009456 BlockTy = Context.getFunctionType(RetTy,
9457 FPT->arg_type_begin(),
9458 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009459 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009460 }
9461
9462 // If we don't have a function type, just build one from nothing.
9463 } else {
John McCalle23cf432010-12-14 08:05:40 +00009464 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009465 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009466 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009467 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009468
John McCallc71a4912010-06-04 19:02:56 +00009469 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9470 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009471 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009472
Chris Lattner17a78302009-04-19 05:28:12 +00009473 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009474 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009475 !hasAnyUnrecoverableErrorsInThisFunction() &&
9476 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009477 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009478
Chris Lattnere476bdc2011-02-17 23:58:47 +00009479 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009480
Jordan Rose7dd900e2012-07-02 21:19:23 +00009481 // Try to apply the named return value optimization. We have to check again
9482 // if we can do this, though, because blocks keep return statements around
9483 // to deduce an implicit return type.
9484 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9485 !BSI->TheDecl->isDependentContext())
9486 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009487
Benjamin Kramerd2486192011-07-12 14:11:05 +00009488 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9489 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009490 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009491
John McCall80ee6e82011-11-10 05:35:25 +00009492 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009493 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009494 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009495 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009496 ExprCleanupObjects.push_back(Result->getBlockDecl());
9497 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009498
9499 // It also gets a branch-protected scope if any of the captured
9500 // variables needs destruction.
9501 for (BlockDecl::capture_const_iterator
9502 ci = Result->getBlockDecl()->capture_begin(),
9503 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9504 const VarDecl *var = ci->getVariable();
9505 if (var->getType().isDestructedType() != QualType::DK_none) {
9506 getCurFunction()->setHasBranchProtectedScope();
9507 break;
9508 }
9509 }
John McCall80ee6e82011-11-10 05:35:25 +00009510 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009511
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009512 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009513}
9514
John McCall60d7b3a2010-08-24 06:29:42 +00009515ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009516 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009517 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009518 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009519 GetTypeFromParser(Ty, &TInfo);
9520 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009521}
9522
John McCall60d7b3a2010-08-24 06:29:42 +00009523ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009524 Expr *E, TypeSourceInfo *TInfo,
9525 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009526 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009527
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009528 // Get the va_list type
9529 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009530 if (VaListType->isArrayType()) {
9531 // Deal with implicit array decay; for example, on x86-64,
9532 // va_list is an array, but it's supposed to decay to
9533 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009534 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009535 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009536 ExprResult Result = UsualUnaryConversions(E);
9537 if (Result.isInvalid())
9538 return ExprError();
9539 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009540 } else {
9541 // Otherwise, the va_list argument must be an l-value because
9542 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009543 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009544 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009545 return ExprError();
9546 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009547
Douglas Gregordd027302009-05-19 23:10:31 +00009548 if (!E->isTypeDependent() &&
9549 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009550 return ExprError(Diag(E->getLocStart(),
9551 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009552 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009553 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009554
David Majnemer0adde122011-06-14 05:17:32 +00009555 if (!TInfo->getType()->isDependentType()) {
9556 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009557 diag::err_second_parameter_to_va_arg_incomplete,
9558 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009559 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009560
David Majnemer0adde122011-06-14 05:17:32 +00009561 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009562 TInfo->getType(),
9563 diag::err_second_parameter_to_va_arg_abstract,
9564 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009565 return ExprError();
9566
Douglas Gregor4eb75222011-07-30 06:45:27 +00009567 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009568 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009569 TInfo->getType()->isObjCLifetimeType()
9570 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9571 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009572 << TInfo->getType()
9573 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009574 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009575
9576 // Check for va_arg where arguments of the given type will be promoted
9577 // (i.e. this va_arg is guaranteed to have undefined behavior).
9578 QualType PromoteType;
9579 if (TInfo->getType()->isPromotableIntegerType()) {
9580 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9581 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9582 PromoteType = QualType();
9583 }
9584 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9585 PromoteType = Context.DoubleTy;
9586 if (!PromoteType.isNull())
9587 Diag(TInfo->getTypeLoc().getBeginLoc(),
9588 diag::warn_second_parameter_to_va_arg_never_compatible)
9589 << TInfo->getType()
9590 << PromoteType
9591 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009592 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009593
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009594 QualType T = TInfo->getType().getNonLValueExprType(Context);
9595 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009596}
9597
John McCall60d7b3a2010-08-24 06:29:42 +00009598ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009599 // The type of __null will be int or long, depending on the size of
9600 // pointers on the target.
9601 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009602 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9603 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009604 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009605 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009606 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009607 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009608 Ty = Context.LongLongTy;
9609 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009610 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009611 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009612
Sebastian Redlf53597f2009-03-15 17:47:39 +00009613 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009614}
9615
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009616static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009617 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009618 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009619 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009620
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009621 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9622 if (!PT)
9623 return;
9624
9625 // Check if the destination is of type 'id'.
9626 if (!PT->isObjCIdType()) {
9627 // Check if the destination is the 'NSString' interface.
9628 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9629 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9630 return;
9631 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009632
John McCall4b9c2d22011-11-06 09:01:30 +00009633 // Ignore any parens, implicit casts (should only be
9634 // array-to-pointer decays), and not-so-opaque values. The last is
9635 // important for making this trigger for property assignments.
9636 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9637 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9638 if (OV->getSourceExpr())
9639 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9640
9641 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009642 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009643 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009644
Douglas Gregor849b2432010-03-31 17:46:05 +00009645 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009646}
9647
Chris Lattner5cf216b2008-01-04 18:04:52 +00009648bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9649 SourceLocation Loc,
9650 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009651 Expr *SrcExpr, AssignmentAction Action,
9652 bool *Complained) {
9653 if (Complained)
9654 *Complained = false;
9655
Chris Lattner5cf216b2008-01-04 18:04:52 +00009656 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009657 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009658 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009659 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009660 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009661 ConversionFixItGenerator ConvHints;
9662 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009663 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009664
Chris Lattner5cf216b2008-01-04 18:04:52 +00009665 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009666 case Compatible:
9667 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9668 return false;
9669
Chris Lattnerb7b61152008-01-04 18:22:42 +00009670 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009671 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009672 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9673 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009674 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009675 case IntToPointer:
9676 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009677 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9678 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009679 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009680 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009681 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009682 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009683 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9684 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009685 if (Hint.isNull() && !CheckInferredResultType) {
9686 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9687 }
9688 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009689 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009690 case IncompatiblePointerSign:
9691 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9692 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009693 case FunctionVoidPointer:
9694 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9695 break;
John McCall86c05f32011-02-01 00:10:29 +00009696 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009697 // Perform array-to-pointer decay if necessary.
9698 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9699
John McCall86c05f32011-02-01 00:10:29 +00009700 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9701 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9702 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9703 DiagKind = diag::err_typecheck_incompatible_address_space;
9704 break;
John McCallf85e1932011-06-15 23:02:42 +00009705
9706
9707 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009708 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009709 break;
John McCall86c05f32011-02-01 00:10:29 +00009710 }
9711
9712 llvm_unreachable("unknown error case for discarding qualifiers!");
9713 // fallthrough
9714 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009715 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009716 // If the qualifiers lost were because we were applying the
9717 // (deprecated) C++ conversion from a string literal to a char*
9718 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9719 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009720 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009721 // bit of refactoring (so that the second argument is an
9722 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009723 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009724 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009725 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009726 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9727 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009728 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9729 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009730 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009731 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009732 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009733 case IntToBlockPointer:
9734 DiagKind = diag::err_int_to_block_pointer;
9735 break;
9736 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009737 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009738 break;
Steve Naroff39579072008-10-14 22:18:38 +00009739 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009740 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009741 // it can give a more specific diagnostic.
9742 DiagKind = diag::warn_incompatible_qualified_id;
9743 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009744 case IncompatibleVectors:
9745 DiagKind = diag::warn_incompatible_vectors;
9746 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009747 case IncompatibleObjCWeakRef:
9748 DiagKind = diag::err_arc_weak_unavailable_assign;
9749 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009750 case Incompatible:
9751 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009752 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9753 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009754 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009755 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009756 break;
9757 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009758
Douglas Gregord4eea832010-04-09 00:35:39 +00009759 QualType FirstType, SecondType;
9760 switch (Action) {
9761 case AA_Assigning:
9762 case AA_Initializing:
9763 // The destination type comes first.
9764 FirstType = DstType;
9765 SecondType = SrcType;
9766 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009767
Douglas Gregord4eea832010-04-09 00:35:39 +00009768 case AA_Returning:
9769 case AA_Passing:
9770 case AA_Converting:
9771 case AA_Sending:
9772 case AA_Casting:
9773 // The source type comes first.
9774 FirstType = SrcType;
9775 SecondType = DstType;
9776 break;
9777 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009778
Anna Zaks67221552011-07-28 19:51:27 +00009779 PartialDiagnostic FDiag = PDiag(DiagKind);
9780 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9781
9782 // If we can fix the conversion, suggest the FixIts.
9783 assert(ConvHints.isNull() || Hint.isNull());
9784 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009785 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9786 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009787 FDiag << *HI;
9788 } else {
9789 FDiag << Hint;
9790 }
9791 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9792
Richard Trieu6efd4c52011-11-23 22:32:32 +00009793 if (MayHaveFunctionDiff)
9794 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9795
Anna Zaks67221552011-07-28 19:51:27 +00009796 Diag(Loc, FDiag);
9797
Richard Trieu6efd4c52011-11-23 22:32:32 +00009798 if (SecondType == Context.OverloadTy)
9799 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9800 FirstType);
9801
Douglas Gregor926df6c2011-06-11 01:09:30 +00009802 if (CheckInferredResultType)
9803 EmitRelatedResultTypeNote(SrcExpr);
9804
Douglas Gregora41a8c52010-04-22 00:20:18 +00009805 if (Complained)
9806 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009807 return isInvalid;
9808}
Anders Carlssone21555e2008-11-30 19:50:32 +00009809
Richard Smith282e7e62012-02-04 09:53:13 +00009810ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9811 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009812 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9813 public:
9814 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9815 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9816 }
9817 } Diagnoser;
9818
9819 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9820}
9821
9822ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9823 llvm::APSInt *Result,
9824 unsigned DiagID,
9825 bool AllowFold) {
9826 class IDDiagnoser : public VerifyICEDiagnoser {
9827 unsigned DiagID;
9828
9829 public:
9830 IDDiagnoser(unsigned DiagID)
9831 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9832
9833 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9834 S.Diag(Loc, DiagID) << SR;
9835 }
9836 } Diagnoser(DiagID);
9837
9838 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9839}
9840
9841void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9842 SourceRange SR) {
9843 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009844}
9845
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009846ExprResult
9847Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009848 VerifyICEDiagnoser &Diagnoser,
9849 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009850 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009851
David Blaikie4e4d0842012-03-11 07:00:24 +00009852 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009853 // C++11 [expr.const]p5:
9854 // If an expression of literal class type is used in a context where an
9855 // integral constant expression is required, then that class type shall
9856 // have a single non-explicit conversion function to an integral or
9857 // unscoped enumeration type
9858 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009859 if (!Diagnoser.Suppress) {
9860 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9861 public:
9862 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9863
9864 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9865 QualType T) {
9866 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9867 }
9868
9869 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9870 SourceLocation Loc,
9871 QualType T) {
9872 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9873 }
9874
9875 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9876 SourceLocation Loc,
9877 QualType T,
9878 QualType ConvTy) {
9879 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9880 }
9881
9882 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9883 CXXConversionDecl *Conv,
9884 QualType ConvTy) {
9885 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9886 << ConvTy->isEnumeralType() << ConvTy;
9887 }
9888
9889 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9890 QualType T) {
9891 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9892 }
9893
9894 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9895 CXXConversionDecl *Conv,
9896 QualType ConvTy) {
9897 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9898 << ConvTy->isEnumeralType() << ConvTy;
9899 }
9900
9901 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9902 SourceLocation Loc,
9903 QualType T,
9904 QualType ConvTy) {
9905 return DiagnosticBuilder::getEmpty();
9906 }
9907 } ConvertDiagnoser;
9908
9909 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9910 ConvertDiagnoser,
9911 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009912 } else {
9913 // The caller wants to silently enquire whether this is an ICE. Don't
9914 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009915 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9916 public:
9917 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9918
9919 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9920 QualType T) {
9921 return DiagnosticBuilder::getEmpty();
9922 }
9923
9924 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9925 SourceLocation Loc,
9926 QualType T) {
9927 return DiagnosticBuilder::getEmpty();
9928 }
9929
9930 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9931 SourceLocation Loc,
9932 QualType T,
9933 QualType ConvTy) {
9934 return DiagnosticBuilder::getEmpty();
9935 }
9936
9937 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9938 CXXConversionDecl *Conv,
9939 QualType ConvTy) {
9940 return DiagnosticBuilder::getEmpty();
9941 }
9942
9943 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9944 QualType T) {
9945 return DiagnosticBuilder::getEmpty();
9946 }
9947
9948 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9949 CXXConversionDecl *Conv,
9950 QualType ConvTy) {
9951 return DiagnosticBuilder::getEmpty();
9952 }
9953
9954 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9955 SourceLocation Loc,
9956 QualType T,
9957 QualType ConvTy) {
9958 return DiagnosticBuilder::getEmpty();
9959 }
9960 } ConvertDiagnoser;
9961
9962 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9963 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009964 }
9965 if (Converted.isInvalid())
9966 return Converted;
9967 E = Converted.take();
9968 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9969 return ExprError();
9970 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9971 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009972 if (!Diagnoser.Suppress)
9973 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009974 return ExprError();
9975 }
9976
Richard Smithdaaefc52011-12-14 23:32:26 +00009977 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9978 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009979 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009980 if (Result)
9981 *Result = E->EvaluateKnownConstInt(Context);
9982 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009983 }
9984
Anders Carlssone21555e2008-11-30 19:50:32 +00009985 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009986 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9987 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009988
Richard Smithdaaefc52011-12-14 23:32:26 +00009989 // Try to evaluate the expression, and produce diagnostics explaining why it's
9990 // not a constant expression as a side-effect.
9991 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9992 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9993
9994 // In C++11, we can rely on diagnostics being produced for any expression
9995 // which is not a constant expression. If no diagnostics were produced, then
9996 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009997 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009998 if (Result)
9999 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010000 return Owned(E);
10001 }
10002
10003 // If our only note is the usual "invalid subexpression" note, just point
10004 // the caret at its location rather than producing an essentially
10005 // redundant note.
10006 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10007 diag::note_invalid_subexpr_in_const_expr) {
10008 DiagLoc = Notes[0].first;
10009 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010010 }
10011
10012 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010013 if (!Diagnoser.Suppress) {
10014 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010015 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10016 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010017 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010018
Richard Smith282e7e62012-02-04 09:53:13 +000010019 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010020 }
10021
Douglas Gregorab41fe92012-05-04 22:38:52 +000010022 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010023 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10024 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010025
Anders Carlssone21555e2008-11-30 19:50:32 +000010026 if (Result)
10027 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010028 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010029}
Douglas Gregore0762c92009-06-19 23:52:42 +000010030
Eli Friedmanef331b72012-01-20 01:26:23 +000010031namespace {
10032 // Handle the case where we conclude a expression which we speculatively
10033 // considered to be unevaluated is actually evaluated.
10034 class TransformToPE : public TreeTransform<TransformToPE> {
10035 typedef TreeTransform<TransformToPE> BaseTransform;
10036
10037 public:
10038 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10039
10040 // Make sure we redo semantic analysis
10041 bool AlwaysRebuild() { return true; }
10042
Eli Friedman56ff2832012-02-06 23:29:57 +000010043 // Make sure we handle LabelStmts correctly.
10044 // FIXME: This does the right thing, but maybe we need a more general
10045 // fix to TreeTransform?
10046 StmtResult TransformLabelStmt(LabelStmt *S) {
10047 S->getDecl()->setStmt(0);
10048 return BaseTransform::TransformLabelStmt(S);
10049 }
10050
Eli Friedmanef331b72012-01-20 01:26:23 +000010051 // We need to special-case DeclRefExprs referring to FieldDecls which
10052 // are not part of a member pointer formation; normal TreeTransforming
10053 // doesn't catch this case because of the way we represent them in the AST.
10054 // FIXME: This is a bit ugly; is it really the best way to handle this
10055 // case?
10056 //
10057 // Error on DeclRefExprs referring to FieldDecls.
10058 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10059 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010060 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010061 return SemaRef.Diag(E->getLocation(),
10062 diag::err_invalid_non_static_member_use)
10063 << E->getDecl() << E->getSourceRange();
10064
10065 return BaseTransform::TransformDeclRefExpr(E);
10066 }
10067
10068 // Exception: filter out member pointer formation
10069 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10070 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10071 return E;
10072
10073 return BaseTransform::TransformUnaryOperator(E);
10074 }
10075
Douglas Gregore2c59132012-02-09 08:14:43 +000010076 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10077 // Lambdas never need to be transformed.
10078 return E;
10079 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010080 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010081}
10082
Eli Friedmanef331b72012-01-20 01:26:23 +000010083ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010084 assert(ExprEvalContexts.back().Context == Unevaluated &&
10085 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010086 ExprEvalContexts.back().Context =
10087 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10088 if (ExprEvalContexts.back().Context == Unevaluated)
10089 return E;
10090 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010091}
10092
Douglas Gregor2afce722009-11-26 00:44:06 +000010093void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010094Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010095 Decl *LambdaContextDecl,
10096 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010097 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010098 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010099 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010100 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010101 LambdaContextDecl,
10102 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010103 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010104 if (!MaybeODRUseExprs.empty())
10105 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010106}
10107
Richard Trieu67e29332011-08-02 04:35:43 +000010108void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010109 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010110
Douglas Gregore2c59132012-02-09 08:14:43 +000010111 if (!Rec.Lambdas.empty()) {
10112 if (Rec.Context == Unevaluated) {
10113 // C++11 [expr.prim.lambda]p2:
10114 // A lambda-expression shall not appear in an unevaluated operand
10115 // (Clause 5).
10116 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10117 Diag(Rec.Lambdas[I]->getLocStart(),
10118 diag::err_lambda_unevaluated_operand);
10119 } else {
10120 // Mark the capture expressions odr-used. This was deferred
10121 // during lambda expression creation.
10122 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10123 LambdaExpr *Lambda = Rec.Lambdas[I];
10124 for (LambdaExpr::capture_init_iterator
10125 C = Lambda->capture_init_begin(),
10126 CEnd = Lambda->capture_init_end();
10127 C != CEnd; ++C) {
10128 MarkDeclarationsReferencedInExpr(*C);
10129 }
10130 }
10131 }
10132 }
10133
Douglas Gregor2afce722009-11-26 00:44:06 +000010134 // When are coming out of an unevaluated context, clear out any
10135 // temporaries that we may have created as part of the evaluation of
10136 // the expression in that context: they aren't relevant because they
10137 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010138 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010139 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10140 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010141 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010142 CleanupVarDeclMarking();
10143 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010144 // Otherwise, merge the contexts together.
10145 } else {
10146 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010147 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10148 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010149 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010150
10151 // Pop the current expression evaluation context off the stack.
10152 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010153}
Douglas Gregore0762c92009-06-19 23:52:42 +000010154
John McCallf85e1932011-06-15 23:02:42 +000010155void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010156 ExprCleanupObjects.erase(
10157 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10158 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010159 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010160 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010161}
10162
Eli Friedman71b8fb52012-01-21 01:01:51 +000010163ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10164 if (!E->getType()->isVariablyModifiedType())
10165 return E;
10166 return TranformToPotentiallyEvaluated(E);
10167}
10168
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010169static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010170 // Do not mark anything as "used" within a dependent context; wait for
10171 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010172 if (SemaRef.CurContext->isDependentContext())
10173 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010174
Eli Friedman5f2987c2012-02-02 03:46:19 +000010175 switch (SemaRef.ExprEvalContexts.back().Context) {
10176 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010177 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010178 // (Depending on how you read the standard, we actually do need to do
10179 // something here for null pointer constants, but the standard's
10180 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010181 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010182
Eli Friedman5f2987c2012-02-02 03:46:19 +000010183 case Sema::ConstantEvaluated:
10184 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010185 // We are in a potentially evaluated expression (or a constant-expression
10186 // in C++03); we need to do implicit template instantiation, implicitly
10187 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010188 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010189
Eli Friedman5f2987c2012-02-02 03:46:19 +000010190 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010191 // Referenced declarations will only be used if the construct in the
10192 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010193 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010194 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010195 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010196}
10197
10198/// \brief Mark a function referenced, and check whether it is odr-used
10199/// (C++ [basic.def.odr]p2, C99 6.9p3)
10200void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10201 assert(Func && "No function?");
10202
10203 Func->setReferenced();
10204
Richard Smith57b9c4e2012-02-14 22:25:15 +000010205 // Don't mark this function as used multiple times, unless it's a constexpr
10206 // function which we need to instantiate.
10207 if (Func->isUsed(false) &&
10208 !(Func->isConstexpr() && !Func->getBody() &&
10209 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010210 return;
10211
10212 if (!IsPotentiallyEvaluatedContext(*this))
10213 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010214
Douglas Gregore0762c92009-06-19 23:52:42 +000010215 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010216 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010217 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010218 if (Constructor->isDefaultConstructor()) {
10219 if (Constructor->isTrivial())
10220 return;
10221 if (!Constructor->isUsed(false))
10222 DefineImplicitDefaultConstructor(Loc, Constructor);
10223 } else if (Constructor->isCopyConstructor()) {
10224 if (!Constructor->isUsed(false))
10225 DefineImplicitCopyConstructor(Loc, Constructor);
10226 } else if (Constructor->isMoveConstructor()) {
10227 if (!Constructor->isUsed(false))
10228 DefineImplicitMoveConstructor(Loc, Constructor);
10229 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010230 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010231
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010232 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010233 } else if (CXXDestructorDecl *Destructor =
10234 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010235 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10236 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010237 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010238 if (Destructor->isVirtual())
10239 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010240 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010241 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10242 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010243 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010244 if (!MethodDecl->isUsed(false)) {
10245 if (MethodDecl->isCopyAssignmentOperator())
10246 DefineImplicitCopyAssignment(Loc, MethodDecl);
10247 else
10248 DefineImplicitMoveAssignment(Loc, MethodDecl);
10249 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010250 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10251 MethodDecl->getParent()->isLambda()) {
10252 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10253 if (Conversion->isLambdaToBlockPointerConversion())
10254 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10255 else
10256 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010257 } else if (MethodDecl->isVirtual())
10258 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010259 }
John McCall15e310a2011-02-19 02:53:41 +000010260
Eli Friedman5f2987c2012-02-02 03:46:19 +000010261 // Recursive functions should be marked when used from another function.
10262 // FIXME: Is this really right?
10263 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010264
Richard Smithb9d0b762012-07-27 04:22:15 +000010265 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010266 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010267 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010268 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10269 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010270
Eli Friedman5f2987c2012-02-02 03:46:19 +000010271 // Implicit instantiation of function templates and member functions of
10272 // class templates.
10273 if (Func->isImplicitlyInstantiable()) {
10274 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010275 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010276 if (FunctionTemplateSpecializationInfo *SpecInfo
10277 = Func->getTemplateSpecializationInfo()) {
10278 if (SpecInfo->getPointOfInstantiation().isInvalid())
10279 SpecInfo->setPointOfInstantiation(Loc);
10280 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010281 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010282 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010283 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10284 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010285 } else if (MemberSpecializationInfo *MSInfo
10286 = Func->getMemberSpecializationInfo()) {
10287 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010288 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010289 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010290 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010291 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010292 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10293 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010294 }
Mike Stump1eb44332009-09-09 15:08:12 +000010295
Richard Smith57b9c4e2012-02-14 22:25:15 +000010296 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010297 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10298 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010299 PendingLocalImplicitInstantiations.push_back(
10300 std::make_pair(Func, PointOfInstantiation));
10301 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010302 // Do not defer instantiations of constexpr functions, to avoid the
10303 // expression evaluator needing to call back into Sema if it sees a
10304 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010305 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010306 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010307 PendingInstantiations.push_back(std::make_pair(Func,
10308 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010309 // Notify the consumer that a function was implicitly instantiated.
10310 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10311 }
John McCall15e310a2011-02-19 02:53:41 +000010312 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010313 } else {
10314 // Walk redefinitions, as some of them may be instantiable.
10315 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10316 e(Func->redecls_end()); i != e; ++i) {
10317 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10318 MarkFunctionReferenced(Loc, *i);
10319 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010320 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010321
10322 // Keep track of used but undefined functions.
10323 if (!Func->isPure() && !Func->hasBody() &&
10324 Func->getLinkage() != ExternalLinkage) {
10325 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10326 if (old.isInvalid()) old = Loc;
10327 }
10328
10329 Func->setUsed(true);
10330}
10331
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010332static void
10333diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10334 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010335 DeclContext *VarDC = var->getDeclContext();
10336
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010337 // If the parameter still belongs to the translation unit, then
10338 // we're actually just using one parameter in the declaration of
10339 // the next.
10340 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010341 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010342 return;
10343
Eli Friedman0a294222012-02-07 00:15:00 +000010344 // For C code, don't diagnose about capture if we're not actually in code
10345 // right now; it's impossible to write a non-constant expression outside of
10346 // function context, so we'll get other (more useful) diagnostics later.
10347 //
10348 // For C++, things get a bit more nasty... it would be nice to suppress this
10349 // diagnostic for certain cases like using a local variable in an array bound
10350 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010351 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010352 return;
10353
Eli Friedman0a294222012-02-07 00:15:00 +000010354 if (isa<CXXMethodDecl>(VarDC) &&
10355 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10356 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10357 << var->getIdentifier();
10358 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10359 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10360 << var->getIdentifier() << fn->getDeclName();
10361 } else if (isa<BlockDecl>(VarDC)) {
10362 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10363 << var->getIdentifier();
10364 } else {
10365 // FIXME: Is there any other context where a local variable can be
10366 // declared?
10367 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10368 << var->getIdentifier();
10369 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010370
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010371 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10372 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010373
10374 // FIXME: Add additional diagnostic info about class etc. which prevents
10375 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010376}
10377
Douglas Gregorf8af9822012-02-12 18:42:33 +000010378/// \brief Capture the given variable in the given lambda expression.
10379static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010380 VarDecl *Var, QualType FieldType,
10381 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010382 SourceLocation Loc,
10383 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010384 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010385
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010386 // Build the non-static data member.
10387 FieldDecl *Field
10388 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10389 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010390 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010391 Field->setImplicit(true);
10392 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010393 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010394
10395 // C++11 [expr.prim.lambda]p21:
10396 // When the lambda-expression is evaluated, the entities that
10397 // are captured by copy are used to direct-initialize each
10398 // corresponding non-static data member of the resulting closure
10399 // object. (For array members, the array elements are
10400 // direct-initialized in increasing subscript order.) These
10401 // initializations are performed in the (unspecified) order in
10402 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010403
Douglas Gregore2c59132012-02-09 08:14:43 +000010404 // Introduce a new evaluation context for the initialization, so
10405 // that temporaries introduced as part of the capture are retained
10406 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010407 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10408
Douglas Gregor73d90922012-02-10 09:26:04 +000010409 // C++ [expr.prim.labda]p12:
10410 // An entity captured by a lambda-expression is odr-used (3.2) in
10411 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010412 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10413 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010414 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010415 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010416
10417 // When the field has array type, create index variables for each
10418 // dimension of the array. We use these index variables to subscript
10419 // the source array, and other clients (e.g., CodeGen) will perform
10420 // the necessary iteration with these index variables.
10421 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010422 QualType BaseType = FieldType;
10423 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010424 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010425 while (const ConstantArrayType *Array
10426 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010427 // Create the iteration variable for this array index.
10428 IdentifierInfo *IterationVarName = 0;
10429 {
10430 SmallString<8> Str;
10431 llvm::raw_svector_ostream OS(Str);
10432 OS << "__i" << IndexVariables.size();
10433 IterationVarName = &S.Context.Idents.get(OS.str());
10434 }
10435 VarDecl *IterationVar
10436 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10437 IterationVarName, SizeType,
10438 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10439 SC_None, SC_None);
10440 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010441 LSI->ArrayIndexVars.push_back(IterationVar);
10442
Douglas Gregor18fe0842012-02-09 02:45:47 +000010443 // Create a reference to the iteration variable.
10444 ExprResult IterationVarRef
10445 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10446 assert(!IterationVarRef.isInvalid() &&
10447 "Reference to invented variable cannot fail!");
10448 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10449 assert(!IterationVarRef.isInvalid() &&
10450 "Conversion of invented variable cannot fail!");
10451
10452 // Subscript the array with this iteration variable.
10453 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10454 Ref, Loc, IterationVarRef.take(), Loc);
10455 if (Subscript.isInvalid()) {
10456 S.CleanupVarDeclMarking();
10457 S.DiscardCleanupsInEvaluationContext();
10458 S.PopExpressionEvaluationContext();
10459 return ExprError();
10460 }
10461
10462 Ref = Subscript.take();
10463 BaseType = Array->getElementType();
10464 }
10465
10466 // Construct the entity that we will be initializing. For an array, this
10467 // will be first element in the array, which may require several levels
10468 // of array-subscript entities.
10469 SmallVector<InitializedEntity, 4> Entities;
10470 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010471 Entities.push_back(
10472 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010473 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10474 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10475 0,
10476 Entities.back()));
10477
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010478 InitializationKind InitKind
10479 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010480 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010481 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010482 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010483 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010484
10485 // If this initialization requires any cleanups (e.g., due to a
10486 // default argument to a copy constructor), note that for the
10487 // lambda.
10488 if (S.ExprNeedsCleanups)
10489 LSI->ExprNeedsCleanups = true;
10490
10491 // Exit the expression evaluation context used for the capture.
10492 S.CleanupVarDeclMarking();
10493 S.DiscardCleanupsInEvaluationContext();
10494 S.PopExpressionEvaluationContext();
10495 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010496}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010497
Douglas Gregor999713e2012-02-18 09:37:24 +000010498bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10499 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10500 bool BuildAndDiagnose,
10501 QualType &CaptureType,
10502 QualType &DeclRefType) {
10503 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010504
Eli Friedmanb942cb22012-02-03 22:47:37 +000010505 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010506 if (Var->getDeclContext() == DC) return true;
10507 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010508
Douglas Gregorf8af9822012-02-12 18:42:33 +000010509 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010510
Douglas Gregor999713e2012-02-18 09:37:24 +000010511 // Walk up the stack to determine whether we can capture the variable,
10512 // performing the "simple" checks that don't depend on type. We stop when
10513 // we've either hit the declared scope of the variable or find an existing
10514 // capture of that variable.
10515 CaptureType = Var->getType();
10516 DeclRefType = CaptureType.getNonReferenceType();
10517 bool Explicit = (Kind != TryCapture_Implicit);
10518 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010519 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010520 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010521 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010522 DeclContext *ParentDC;
10523 if (isa<BlockDecl>(DC))
10524 ParentDC = DC->getParent();
10525 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010526 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010527 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10528 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010529 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010530 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010531 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010532 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010533 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010534
Eli Friedmanb942cb22012-02-03 22:47:37 +000010535 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010536 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010537
Eli Friedmanb942cb22012-02-03 22:47:37 +000010538 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010539 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010540 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010541 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010542
10543 // Retrieve the capture type for this variable.
10544 CaptureType = CSI->getCapture(Var).getCaptureType();
10545
10546 // Compute the type of an expression that refers to this variable.
10547 DeclRefType = CaptureType.getNonReferenceType();
10548
10549 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10550 if (Cap.isCopyCapture() &&
10551 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10552 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010553 break;
10554 }
10555
Douglas Gregorf8af9822012-02-12 18:42:33 +000010556 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010557 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010558
10559 // Lambdas are not allowed to capture unnamed variables
10560 // (e.g. anonymous unions).
10561 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10562 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010563 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010564 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010565 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10566 Diag(Var->getLocation(), diag::note_declared_at);
10567 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010568 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010569 }
10570
10571 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010572 if (Var->getType()->isVariablyModifiedType()) {
10573 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010574 if (IsBlock)
10575 Diag(Loc, diag::err_ref_vm_type);
10576 else
10577 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10578 Diag(Var->getLocation(), diag::note_previous_decl)
10579 << Var->getDeclName();
10580 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010581 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010582 }
10583
Eli Friedmanb942cb22012-02-03 22:47:37 +000010584 // Lambdas are not allowed to capture __block variables; they don't
10585 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010586 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010587 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010588 Diag(Loc, diag::err_lambda_capture_block)
10589 << Var->getDeclName();
10590 Diag(Var->getLocation(), diag::note_previous_decl)
10591 << Var->getDeclName();
10592 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010593 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010594 }
10595
Douglas Gregorf8af9822012-02-12 18:42:33 +000010596 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10597 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010598 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010599 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10600 Diag(Var->getLocation(), diag::note_previous_decl)
10601 << Var->getDeclName();
10602 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10603 diag::note_lambda_decl);
10604 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010605 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010606 }
10607
10608 FunctionScopesIndex--;
10609 DC = ParentDC;
10610 Explicit = false;
10611 } while (!Var->getDeclContext()->Equals(DC));
10612
Douglas Gregor999713e2012-02-18 09:37:24 +000010613 // Walk back down the scope stack, computing the type of the capture at
10614 // each step, checking type-specific requirements, and adding captures if
10615 // requested.
10616 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10617 ++I) {
10618 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010619
Douglas Gregor999713e2012-02-18 09:37:24 +000010620 // Compute the type of the capture and of a reference to the capture within
10621 // this scope.
10622 if (isa<BlockScopeInfo>(CSI)) {
10623 Expr *CopyExpr = 0;
10624 bool ByRef = false;
10625
10626 // Blocks are not allowed to capture arrays.
10627 if (CaptureType->isArrayType()) {
10628 if (BuildAndDiagnose) {
10629 Diag(Loc, diag::err_ref_array_type);
10630 Diag(Var->getLocation(), diag::note_previous_decl)
10631 << Var->getDeclName();
10632 }
10633 return true;
10634 }
10635
John McCall100c6492012-03-30 05:23:48 +000010636 // Forbid the block-capture of autoreleasing variables.
10637 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10638 if (BuildAndDiagnose) {
10639 Diag(Loc, diag::err_arc_autoreleasing_capture)
10640 << /*block*/ 0;
10641 Diag(Var->getLocation(), diag::note_previous_decl)
10642 << Var->getDeclName();
10643 }
10644 return true;
10645 }
10646
Douglas Gregor999713e2012-02-18 09:37:24 +000010647 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10648 // Block capture by reference does not change the capture or
10649 // declaration reference types.
10650 ByRef = true;
10651 } else {
10652 // Block capture by copy introduces 'const'.
10653 CaptureType = CaptureType.getNonReferenceType().withConst();
10654 DeclRefType = CaptureType;
10655
David Blaikie4e4d0842012-03-11 07:00:24 +000010656 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010657 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10658 // The capture logic needs the destructor, so make sure we mark it.
10659 // Usually this is unnecessary because most local variables have
10660 // their destructors marked at declaration time, but parameters are
10661 // an exception because it's technically only the call site that
10662 // actually requires the destructor.
10663 if (isa<ParmVarDecl>(Var))
10664 FinalizeVarWithDestructor(Var, Record);
10665
10666 // According to the blocks spec, the capture of a variable from
10667 // the stack requires a const copy constructor. This is not true
10668 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010669 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010670 DeclRefType.withConst(),
10671 VK_LValue, Loc);
10672 ExprResult Result
10673 = PerformCopyInitialization(
10674 InitializedEntity::InitializeBlock(Var->getLocation(),
10675 CaptureType, false),
10676 Loc, Owned(DeclRef));
10677
10678 // Build a full-expression copy expression if initialization
10679 // succeeded and used a non-trivial constructor. Recover from
10680 // errors by pretending that the copy isn't necessary.
10681 if (!Result.isInvalid() &&
10682 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10683 ->isTrivial()) {
10684 Result = MaybeCreateExprWithCleanups(Result);
10685 CopyExpr = Result.take();
10686 }
10687 }
10688 }
10689 }
10690
10691 // Actually capture the variable.
10692 if (BuildAndDiagnose)
10693 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10694 SourceLocation(), CaptureType, CopyExpr);
10695 Nested = true;
10696 continue;
10697 }
Douglas Gregor68932842012-02-18 05:51:20 +000010698
Douglas Gregor999713e2012-02-18 09:37:24 +000010699 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10700
10701 // Determine whether we are capturing by reference or by value.
10702 bool ByRef = false;
10703 if (I == N - 1 && Kind != TryCapture_Implicit) {
10704 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010705 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010706 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010707 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010708
10709 // Compute the type of the field that will capture this variable.
10710 if (ByRef) {
10711 // C++11 [expr.prim.lambda]p15:
10712 // An entity is captured by reference if it is implicitly or
10713 // explicitly captured but not captured by copy. It is
10714 // unspecified whether additional unnamed non-static data
10715 // members are declared in the closure type for entities
10716 // captured by reference.
10717 //
10718 // FIXME: It is not clear whether we want to build an lvalue reference
10719 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10720 // to do the former, while EDG does the latter. Core issue 1249 will
10721 // clarify, but for now we follow GCC because it's a more permissive and
10722 // easily defensible position.
10723 CaptureType = Context.getLValueReferenceType(DeclRefType);
10724 } else {
10725 // C++11 [expr.prim.lambda]p14:
10726 // For each entity captured by copy, an unnamed non-static
10727 // data member is declared in the closure type. The
10728 // declaration order of these members is unspecified. The type
10729 // of such a data member is the type of the corresponding
10730 // captured entity if the entity is not a reference to an
10731 // object, or the referenced type otherwise. [Note: If the
10732 // captured entity is a reference to a function, the
10733 // corresponding data member is also a reference to a
10734 // function. - end note ]
10735 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10736 if (!RefType->getPointeeType()->isFunctionType())
10737 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010738 }
John McCall100c6492012-03-30 05:23:48 +000010739
10740 // Forbid the lambda copy-capture of autoreleasing variables.
10741 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10742 if (BuildAndDiagnose) {
10743 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10744 Diag(Var->getLocation(), diag::note_previous_decl)
10745 << Var->getDeclName();
10746 }
10747 return true;
10748 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010749 }
10750
Douglas Gregor999713e2012-02-18 09:37:24 +000010751 // Capture this variable in the lambda.
10752 Expr *CopyExpr = 0;
10753 if (BuildAndDiagnose) {
10754 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010755 DeclRefType, Loc,
10756 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010757 if (!Result.isInvalid())
10758 CopyExpr = Result.take();
10759 }
10760
10761 // Compute the type of a reference to this captured variable.
10762 if (ByRef)
10763 DeclRefType = CaptureType.getNonReferenceType();
10764 else {
10765 // C++ [expr.prim.lambda]p5:
10766 // The closure type for a lambda-expression has a public inline
10767 // function call operator [...]. This function call operator is
10768 // declared const (9.3.1) if and only if the lambda-expression’s
10769 // parameter-declaration-clause is not followed by mutable.
10770 DeclRefType = CaptureType.getNonReferenceType();
10771 if (!LSI->Mutable && !CaptureType->isReferenceType())
10772 DeclRefType.addConst();
10773 }
10774
10775 // Add the capture.
10776 if (BuildAndDiagnose)
10777 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10778 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010779 Nested = true;
10780 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010781
10782 return false;
10783}
10784
10785bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10786 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10787 QualType CaptureType;
10788 QualType DeclRefType;
10789 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10790 /*BuildAndDiagnose=*/true, CaptureType,
10791 DeclRefType);
10792}
10793
10794QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10795 QualType CaptureType;
10796 QualType DeclRefType;
10797
10798 // Determine whether we can capture this variable.
10799 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10800 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10801 return QualType();
10802
10803 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010804}
10805
Eli Friedmand2cce132012-02-02 23:15:15 +000010806static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10807 SourceLocation Loc) {
10808 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010809 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010810 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010811 Var->getLinkage() != ExternalLinkage &&
10812 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010813 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10814 if (old.isInvalid()) old = Loc;
10815 }
10816
Douglas Gregor999713e2012-02-18 09:37:24 +000010817 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010818
Eli Friedmand2cce132012-02-02 23:15:15 +000010819 Var->setUsed(true);
10820}
10821
10822void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10823 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10824 // an object that satisfies the requirements for appearing in a
10825 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10826 // is immediately applied." This function handles the lvalue-to-rvalue
10827 // conversion part.
10828 MaybeODRUseExprs.erase(E->IgnoreParens());
10829}
10830
Eli Friedmanac626012012-02-29 03:16:56 +000010831ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10832 if (!Res.isUsable())
10833 return Res;
10834
10835 // If a constant-expression is a reference to a variable where we delay
10836 // deciding whether it is an odr-use, just assume we will apply the
10837 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10838 // (a non-type template argument), we have special handling anyway.
10839 UpdateMarkingForLValueToRValue(Res.get());
10840 return Res;
10841}
10842
Eli Friedmand2cce132012-02-02 23:15:15 +000010843void Sema::CleanupVarDeclMarking() {
10844 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10845 e = MaybeODRUseExprs.end();
10846 i != e; ++i) {
10847 VarDecl *Var;
10848 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010850 Var = cast<VarDecl>(DRE->getDecl());
10851 Loc = DRE->getLocation();
10852 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10853 Var = cast<VarDecl>(ME->getMemberDecl());
10854 Loc = ME->getMemberLoc();
10855 } else {
10856 llvm_unreachable("Unexpcted expression");
10857 }
10858
10859 MarkVarDeclODRUsed(*this, Var, Loc);
10860 }
10861
10862 MaybeODRUseExprs.clear();
10863}
10864
10865// Mark a VarDecl referenced, and perform the necessary handling to compute
10866// odr-uses.
10867static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10868 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010869 Var->setReferenced();
10870
Eli Friedmand2cce132012-02-02 23:15:15 +000010871 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010872 return;
10873
10874 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010875 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010876 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10877 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010878 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10879 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010880 (!AlreadyInstantiated ||
10881 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010882 if (!AlreadyInstantiated) {
10883 // This is a modification of an existing AST node. Notify listeners.
10884 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10885 L->StaticDataMemberInstantiated(Var);
10886 MSInfo->setPointOfInstantiation(Loc);
10887 }
10888 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010889 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010890 // Do not defer instantiations of variables which could be used in a
10891 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010892 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010893 else
Richard Smith37ce0102012-02-15 02:42:50 +000010894 SemaRef.PendingInstantiations.push_back(
10895 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010896 }
10897 }
10898
Eli Friedmand2cce132012-02-02 23:15:15 +000010899 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10900 // an object that satisfies the requirements for appearing in a
10901 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10902 // is immediately applied." We check the first part here, and
10903 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10904 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010905 // C++03 depends on whether we get the C++03 version correct. This does not
10906 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010907 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010908 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010909 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010910 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10911 SemaRef.MaybeODRUseExprs.insert(E);
10912 else
10913 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10914}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010915
Eli Friedmand2cce132012-02-02 23:15:15 +000010916/// \brief Mark a variable referenced, and check whether it is odr-used
10917/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10918/// used directly for normal expressions referring to VarDecl.
10919void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10920 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010921}
10922
10923static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10924 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010925 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10926 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10927 return;
10928 }
10929
Eli Friedman5f2987c2012-02-02 03:46:19 +000010930 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010931
10932 // If this is a call to a method via a cast, also mark the method in the
10933 // derived class used in case codegen can devirtualize the call.
10934 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10935 if (!ME)
10936 return;
10937 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10938 if (!MD)
10939 return;
10940 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010941 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010942 if (!MostDerivedClassDecl)
10943 return;
10944 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010945 if (!DM)
10946 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010947 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010948}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010949
Eli Friedman5f2987c2012-02-02 03:46:19 +000010950/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10951void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10952 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10953}
10954
10955/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10956void Sema::MarkMemberReferenced(MemberExpr *E) {
10957 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10958}
10959
Douglas Gregor73d90922012-02-10 09:26:04 +000010960/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010961/// marks the declaration referenced, and performs odr-use checking for functions
10962/// and variables. This method should not be used when building an normal
10963/// expression which refers to a variable.
10964void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10965 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10966 MarkVariableReferenced(Loc, VD);
10967 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10968 MarkFunctionReferenced(Loc, FD);
10969 else
10970 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010971}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010972
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010973namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010974 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010975 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010976 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010977 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10978 Sema &S;
10979 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010980
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010981 public:
10982 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010983
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010984 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010985
10986 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10987 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010988 };
10989}
10990
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010991bool MarkReferencedDecls::TraverseTemplateArgument(
10992 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010993 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010994 if (Decl *D = Arg.getAsDecl())
10995 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010996 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010997
10998 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010999}
11000
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011001bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011002 if (ClassTemplateSpecializationDecl *Spec
11003 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11004 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011005 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011006 }
11007
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011008 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011009}
11010
11011void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11012 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011013 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011014}
11015
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011016namespace {
11017 /// \brief Helper class that marks all of the declarations referenced by
11018 /// potentially-evaluated subexpressions as "referenced".
11019 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11020 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011021 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011022
11023 public:
11024 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11025
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011026 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11027 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011028
11029 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011030 // If we were asked not to visit local variables, don't.
11031 if (SkipLocalVariables) {
11032 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11033 if (VD->hasLocalStorage())
11034 return;
11035 }
11036
Eli Friedman5f2987c2012-02-02 03:46:19 +000011037 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011038 }
11039
11040 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011041 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011042 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011043 }
11044
John McCall80ee6e82011-11-10 05:35:25 +000011045 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011046 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011047 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11048 Visit(E->getSubExpr());
11049 }
11050
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011051 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011052 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011053 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011054 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011055 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011056 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011057 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011058
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011059 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11060 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011061 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011062 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11063 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11064 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011065 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011066 S.LookupDestructor(Record));
11067 }
11068
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011069 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011070 }
11071
11072 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011073 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011074 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011075 }
11076
Douglas Gregor102ff972010-10-19 17:17:35 +000011077 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11078 Visit(E->getExpr());
11079 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011080
11081 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11082 Inherited::VisitImplicitCastExpr(E);
11083
11084 if (E->getCastKind() == CK_LValueToRValue)
11085 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11086 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011087 };
11088}
11089
11090/// \brief Mark any declarations that appear within this expression or any
11091/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011092///
11093/// \param SkipLocalVariables If true, don't mark local variables as
11094/// 'referenced'.
11095void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11096 bool SkipLocalVariables) {
11097 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011098}
11099
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011100/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11101/// of the program being compiled.
11102///
11103/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011104/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011105/// possibility that the code will actually be executable. Code in sizeof()
11106/// expressions, code used only during overload resolution, etc., are not
11107/// potentially evaluated. This routine will suppress such diagnostics or,
11108/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011109/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011110/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011111///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011112/// This routine should be used for all diagnostics that describe the run-time
11113/// behavior of a program, such as passing a non-POD value through an ellipsis.
11114/// Failure to do so will likely result in spurious diagnostics or failures
11115/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011116bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011117 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011118 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011119 case Unevaluated:
11120 // The argument will never be evaluated, so don't complain.
11121 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011122
Richard Smithf6702a32011-12-20 02:08:33 +000011123 case ConstantEvaluated:
11124 // Relevant diagnostics should be produced by constant evaluation.
11125 break;
11126
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011127 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011128 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011129 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011130 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011131 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011132 }
11133 else
11134 Diag(Loc, PD);
11135
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011136 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011137 }
11138
11139 return false;
11140}
11141
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011142bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11143 CallExpr *CE, FunctionDecl *FD) {
11144 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11145 return false;
11146
Richard Smith76f3f692012-02-22 02:04:18 +000011147 // If we're inside a decltype's expression, don't check for a valid return
11148 // type or construct temporaries until we know whether this is the last call.
11149 if (ExprEvalContexts.back().IsDecltype) {
11150 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11151 return false;
11152 }
11153
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011154 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011155 FunctionDecl *FD;
11156 CallExpr *CE;
11157
11158 public:
11159 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11160 : FD(FD), CE(CE) { }
11161
11162 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11163 if (!FD) {
11164 S.Diag(Loc, diag::err_call_incomplete_return)
11165 << T << CE->getSourceRange();
11166 return;
11167 }
11168
11169 S.Diag(Loc, diag::err_call_function_incomplete_return)
11170 << CE->getSourceRange() << FD->getDeclName() << T;
11171 S.Diag(FD->getLocation(),
11172 diag::note_function_with_incomplete_return_type_declared_here)
11173 << FD->getDeclName();
11174 }
11175 } Diagnoser(FD, CE);
11176
11177 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011178 return true;
11179
11180 return false;
11181}
11182
Douglas Gregor92c3a042011-01-19 16:50:08 +000011183// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011184// will prevent this condition from triggering, which is what we want.
11185void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11186 SourceLocation Loc;
11187
John McCalla52ef082009-11-11 02:41:58 +000011188 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011189 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011190
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011191 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011192 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011193 return;
11194
Douglas Gregor92c3a042011-01-19 16:50:08 +000011195 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11196
John McCallc8d8ac52009-11-12 00:06:05 +000011197 // Greylist some idioms by putting them into a warning subcategory.
11198 if (ObjCMessageExpr *ME
11199 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11200 Selector Sel = ME->getSelector();
11201
John McCallc8d8ac52009-11-12 00:06:05 +000011202 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011203 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011204 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11205
11206 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011207 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011208 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11209 }
John McCalla52ef082009-11-11 02:41:58 +000011210
John McCall5a881bb2009-10-12 21:59:07 +000011211 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011212 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011213 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011214 return;
11215
Douglas Gregor92c3a042011-01-19 16:50:08 +000011216 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011217 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011218 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11219 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11220 else {
John McCall5a881bb2009-10-12 21:59:07 +000011221 // Not an assignment.
11222 return;
11223 }
11224
Douglas Gregor55b38842010-04-14 16:09:52 +000011225 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011226
Daniel Dunbar96a00142012-03-09 18:35:03 +000011227 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011228 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11229 Diag(Loc, diag::note_condition_assign_silence)
11230 << FixItHint::CreateInsertion(Open, "(")
11231 << FixItHint::CreateInsertion(Close, ")");
11232
Douglas Gregor92c3a042011-01-19 16:50:08 +000011233 if (IsOrAssign)
11234 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11235 << FixItHint::CreateReplacement(Loc, "!=");
11236 else
11237 Diag(Loc, diag::note_condition_assign_to_comparison)
11238 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011239}
11240
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011241/// \brief Redundant parentheses over an equality comparison can indicate
11242/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011243void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011244 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011245 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011246 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11247 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011248 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011249 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011250 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011251
Richard Trieuccd891a2011-09-09 01:45:06 +000011252 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011253
11254 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011255 if (opE->getOpcode() == BO_EQ &&
11256 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11257 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011258 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011259
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011260 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011261 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011262 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011263 << FixItHint::CreateRemoval(ParenERange.getBegin())
11264 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011265 Diag(Loc, diag::note_equality_comparison_to_assign)
11266 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011267 }
11268}
11269
John Wiegley429bb272011-04-08 18:41:53 +000011270ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011271 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011272 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11273 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011274
John McCall864c0412011-04-26 20:42:42 +000011275 ExprResult result = CheckPlaceholderExpr(E);
11276 if (result.isInvalid()) return ExprError();
11277 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011278
John McCall864c0412011-04-26 20:42:42 +000011279 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011280 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011281 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11282
John Wiegley429bb272011-04-08 18:41:53 +000011283 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11284 if (ERes.isInvalid())
11285 return ExprError();
11286 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011287
11288 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011289 if (!T->isScalarType()) { // C99 6.8.4.1p1
11290 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11291 << T << E->getSourceRange();
11292 return ExprError();
11293 }
John McCall5a881bb2009-10-12 21:59:07 +000011294 }
11295
John Wiegley429bb272011-04-08 18:41:53 +000011296 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011297}
Douglas Gregor586596f2010-05-06 17:25:47 +000011298
John McCall60d7b3a2010-08-24 06:29:42 +000011299ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011300 Expr *SubExpr) {
11301 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011302 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011303
Richard Trieuccd891a2011-09-09 01:45:06 +000011304 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011305}
John McCall2a984ca2010-10-12 00:20:44 +000011306
John McCall1de4d4e2011-04-07 08:22:57 +000011307namespace {
John McCall755d8492011-04-12 00:42:48 +000011308 /// A visitor for rebuilding a call to an __unknown_any expression
11309 /// to have an appropriate type.
11310 struct RebuildUnknownAnyFunction
11311 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11312
11313 Sema &S;
11314
11315 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11316
11317 ExprResult VisitStmt(Stmt *S) {
11318 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011319 }
11320
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011321 ExprResult VisitExpr(Expr *E) {
11322 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11323 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011324 return ExprError();
11325 }
11326
11327 /// Rebuild an expression which simply semantically wraps another
11328 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011329 template <class T> ExprResult rebuildSugarExpr(T *E) {
11330 ExprResult SubResult = Visit(E->getSubExpr());
11331 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011332
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011333 Expr *SubExpr = SubResult.take();
11334 E->setSubExpr(SubExpr);
11335 E->setType(SubExpr->getType());
11336 E->setValueKind(SubExpr->getValueKind());
11337 assert(E->getObjectKind() == OK_Ordinary);
11338 return E;
John McCall755d8492011-04-12 00:42:48 +000011339 }
11340
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011341 ExprResult VisitParenExpr(ParenExpr *E) {
11342 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011343 }
11344
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011345 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11346 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011347 }
11348
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011349 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11350 ExprResult SubResult = Visit(E->getSubExpr());
11351 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011352
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011353 Expr *SubExpr = SubResult.take();
11354 E->setSubExpr(SubExpr);
11355 E->setType(S.Context.getPointerType(SubExpr->getType()));
11356 assert(E->getValueKind() == VK_RValue);
11357 assert(E->getObjectKind() == OK_Ordinary);
11358 return E;
John McCall755d8492011-04-12 00:42:48 +000011359 }
11360
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011361 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11362 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011363
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011364 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011365
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011366 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011367 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011368 !(isa<CXXMethodDecl>(VD) &&
11369 cast<CXXMethodDecl>(VD)->isInstance()))
11370 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011371
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011372 return E;
John McCall755d8492011-04-12 00:42:48 +000011373 }
11374
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011375 ExprResult VisitMemberExpr(MemberExpr *E) {
11376 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011377 }
11378
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011379 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11380 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011381 }
11382 };
11383}
11384
11385/// Given a function expression of unknown-any type, try to rebuild it
11386/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011387static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11388 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11389 if (Result.isInvalid()) return ExprError();
11390 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011391}
11392
11393namespace {
John McCall379b5152011-04-11 07:02:50 +000011394 /// A visitor for rebuilding an expression of type __unknown_anytype
11395 /// into one which resolves the type directly on the referring
11396 /// expression. Strict preservation of the original source
11397 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011398 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011399 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011400
11401 Sema &S;
11402
11403 /// The current destination type.
11404 QualType DestType;
11405
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011406 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11407 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011408
John McCalla5fc4722011-04-09 22:50:59 +000011409 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011410 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011411 }
11412
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011413 ExprResult VisitExpr(Expr *E) {
11414 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11415 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011416 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011417 }
11418
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011419 ExprResult VisitCallExpr(CallExpr *E);
11420 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011421
John McCalla5fc4722011-04-09 22:50:59 +000011422 /// Rebuild an expression which simply semantically wraps another
11423 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011424 template <class T> ExprResult rebuildSugarExpr(T *E) {
11425 ExprResult SubResult = Visit(E->getSubExpr());
11426 if (SubResult.isInvalid()) return ExprError();
11427 Expr *SubExpr = SubResult.take();
11428 E->setSubExpr(SubExpr);
11429 E->setType(SubExpr->getType());
11430 E->setValueKind(SubExpr->getValueKind());
11431 assert(E->getObjectKind() == OK_Ordinary);
11432 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011433 }
John McCall1de4d4e2011-04-07 08:22:57 +000011434
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011435 ExprResult VisitParenExpr(ParenExpr *E) {
11436 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011437 }
11438
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011439 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11440 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011441 }
11442
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011443 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11444 const PointerType *Ptr = DestType->getAs<PointerType>();
11445 if (!Ptr) {
11446 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11447 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011448 return ExprError();
11449 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011450 assert(E->getValueKind() == VK_RValue);
11451 assert(E->getObjectKind() == OK_Ordinary);
11452 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011453
11454 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011455 DestType = Ptr->getPointeeType();
11456 ExprResult SubResult = Visit(E->getSubExpr());
11457 if (SubResult.isInvalid()) return ExprError();
11458 E->setSubExpr(SubResult.take());
11459 return E;
John McCall755d8492011-04-12 00:42:48 +000011460 }
11461
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011462 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011463
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011464 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011465
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011466 ExprResult VisitMemberExpr(MemberExpr *E) {
11467 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011468 }
John McCalla5fc4722011-04-09 22:50:59 +000011469
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011470 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11471 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011472 }
11473 };
11474}
11475
John McCall379b5152011-04-11 07:02:50 +000011476/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011477ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11478 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011479
11480 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011481 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011482 FK_FunctionPointer,
11483 FK_BlockPointer
11484 };
11485
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011486 FnKind Kind;
11487 QualType CalleeType = CalleeExpr->getType();
11488 if (CalleeType == S.Context.BoundMemberTy) {
11489 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11490 Kind = FK_MemberFunction;
11491 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11492 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11493 CalleeType = Ptr->getPointeeType();
11494 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011495 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011496 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11497 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011498 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011499 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011500
11501 // Verify that this is a legal result type of a function.
11502 if (DestType->isArrayType() || DestType->isFunctionType()) {
11503 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011504 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011505 diagID = diag::err_block_returning_array_function;
11506
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011507 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011508 << DestType->isFunctionType() << DestType;
11509 return ExprError();
11510 }
11511
11512 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011513 E->setType(DestType.getNonLValueExprType(S.Context));
11514 E->setValueKind(Expr::getValueKindForType(DestType));
11515 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011516
11517 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011518 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011519 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011520 Proto->arg_type_begin(),
11521 Proto->getNumArgs(),
11522 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011523 else
11524 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011525 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011526
11527 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011528 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011529 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011530 // Nothing to do.
11531 break;
11532
11533 case FK_FunctionPointer:
11534 DestType = S.Context.getPointerType(DestType);
11535 break;
11536
11537 case FK_BlockPointer:
11538 DestType = S.Context.getBlockPointerType(DestType);
11539 break;
11540 }
11541
11542 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011543 ExprResult CalleeResult = Visit(CalleeExpr);
11544 if (!CalleeResult.isUsable()) return ExprError();
11545 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011546
11547 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011548 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011549}
11550
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011551ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011552 // Verify that this is a legal result type of a call.
11553 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011555 << DestType->isFunctionType() << DestType;
11556 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011557 }
11558
John McCall48218c62011-07-13 17:56:40 +000011559 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011560 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11561 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11562 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011563 }
John McCall755d8492011-04-12 00:42:48 +000011564
John McCall379b5152011-04-11 07:02:50 +000011565 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011566 E->setType(DestType.getNonReferenceType());
11567 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011568
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011569 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011570}
11571
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011572ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011573 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011574 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011575 assert(E->getValueKind() == VK_RValue);
11576 assert(E->getObjectKind() == OK_Ordinary);
11577
11578 E->setType(DestType);
11579
11580 // Rebuild the sub-expression as the pointee (function) type.
11581 DestType = DestType->castAs<PointerType>()->getPointeeType();
11582
11583 ExprResult Result = Visit(E->getSubExpr());
11584 if (!Result.isUsable()) return ExprError();
11585
11586 E->setSubExpr(Result.take());
11587 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011588 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011589 assert(E->getValueKind() == VK_RValue);
11590 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011591
Sean Callanance9c8312012-03-06 21:34:12 +000011592 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011593
Sean Callanance9c8312012-03-06 21:34:12 +000011594 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011595
Sean Callanance9c8312012-03-06 21:34:12 +000011596 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11597 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011598
Sean Callanance9c8312012-03-06 21:34:12 +000011599 ExprResult Result = Visit(E->getSubExpr());
11600 if (!Result.isUsable()) return ExprError();
11601
11602 E->setSubExpr(Result.take());
11603 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011604 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011605 llvm_unreachable("Unhandled cast type!");
11606 }
John McCall379b5152011-04-11 07:02:50 +000011607}
11608
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011609ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11610 ExprValueKind ValueKind = VK_LValue;
11611 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011612
11613 // We know how to make this work for certain kinds of decls:
11614
11615 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11617 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11618 DestType = Ptr->getPointeeType();
11619 ExprResult Result = resolveDecl(E, VD);
11620 if (Result.isInvalid()) return ExprError();
11621 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011622 CK_FunctionToPointerDecay, VK_RValue);
11623 }
11624
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011625 if (!Type->isFunctionType()) {
11626 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11627 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011628 return ExprError();
11629 }
John McCall379b5152011-04-11 07:02:50 +000011630
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011631 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11632 if (MD->isInstance()) {
11633 ValueKind = VK_RValue;
11634 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011635 }
11636
John McCall379b5152011-04-11 07:02:50 +000011637 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011638 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011639 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011640
11641 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011642 } else if (isa<VarDecl>(VD)) {
11643 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11644 Type = RefTy->getPointeeType();
11645 } else if (Type->isFunctionType()) {
11646 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11647 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011648 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011649 }
11650
11651 // - nothing else
11652 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011653 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11654 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011655 return ExprError();
11656 }
11657
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011658 VD->setType(DestType);
11659 E->setType(Type);
11660 E->setValueKind(ValueKind);
11661 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011662}
11663
John McCall1de4d4e2011-04-07 08:22:57 +000011664/// Check a cast of an unknown-any type. We intentionally only
11665/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011666ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11667 Expr *CastExpr, CastKind &CastKind,
11668 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011669 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011670 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011671 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011672
Richard Trieuccd891a2011-09-09 01:45:06 +000011673 CastExpr = result.take();
11674 VK = CastExpr->getValueKind();
11675 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011676
Richard Trieuccd891a2011-09-09 01:45:06 +000011677 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011678}
11679
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011680ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11681 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11682}
11683
Richard Trieuccd891a2011-09-09 01:45:06 +000011684static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11685 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011686 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011687 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011688 E = E->IgnoreParenImpCasts();
11689 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11690 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011691 diagID = diag::err_uncasted_call_of_unknown_any;
11692 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011693 break;
John McCall379b5152011-04-11 07:02:50 +000011694 }
John McCall1de4d4e2011-04-07 08:22:57 +000011695 }
11696
John McCall379b5152011-04-11 07:02:50 +000011697 SourceLocation loc;
11698 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011699 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011700 loc = ref->getLocation();
11701 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011702 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011703 loc = mem->getMemberLoc();
11704 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011705 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011706 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011707 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011708 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011709 if (!d) {
11710 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11711 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11712 << orig->getSourceRange();
11713 return ExprError();
11714 }
John McCall379b5152011-04-11 07:02:50 +000011715 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011716 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11717 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011718 return ExprError();
11719 }
11720
11721 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011722
11723 // Never recoverable.
11724 return ExprError();
11725}
11726
John McCall2a984ca2010-10-12 00:20:44 +000011727/// Check for operands with placeholder types and complain if found.
11728/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011729ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011730 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11731 if (!placeholderType) return Owned(E);
11732
11733 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011734
John McCall1de4d4e2011-04-07 08:22:57 +000011735 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011736 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011737 // Try to resolve a single function template specialization.
11738 // This is obligatory.
11739 ExprResult result = Owned(E);
11740 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11741 return result;
11742
11743 // If that failed, try to recover with a call.
11744 } else {
11745 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11746 /*complain*/ true);
11747 return result;
11748 }
11749 }
John McCall1de4d4e2011-04-07 08:22:57 +000011750
John McCall864c0412011-04-26 20:42:42 +000011751 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011752 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011753 ExprResult result = Owned(E);
11754 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11755 /*complain*/ true);
11756 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011757 }
11758
11759 // ARC unbridged casts.
11760 case BuiltinType::ARCUnbridgedCast: {
11761 Expr *realCast = stripARCUnbridgedCast(E);
11762 diagnoseARCUnbridgedCast(realCast);
11763 return Owned(realCast);
11764 }
John McCall864c0412011-04-26 20:42:42 +000011765
John McCall1de4d4e2011-04-07 08:22:57 +000011766 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011767 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011768 return diagnoseUnknownAnyExpr(*this, E);
11769
John McCall3c3b7f92011-10-25 17:37:35 +000011770 // Pseudo-objects.
11771 case BuiltinType::PseudoObject:
11772 return checkPseudoObjectRValue(E);
11773
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011774 case BuiltinType::BuiltinFn:
11775 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11776 return ExprError();
11777
John McCalle0a22d02011-10-18 21:02:43 +000011778 // Everything else should be impossible.
11779#define BUILTIN_TYPE(Id, SingletonId) \
11780 case BuiltinType::Id:
11781#define PLACEHOLDER_TYPE(Id, SingletonId)
11782#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011783 break;
11784 }
11785
11786 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011787}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011788
Richard Trieuccd891a2011-09-09 01:45:06 +000011789bool Sema::CheckCaseExpression(Expr *E) {
11790 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011791 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011792 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11793 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011794 return false;
11795}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011796
11797/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11798ExprResult
11799Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11800 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11801 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011802 QualType BoolT = Context.ObjCBuiltinBoolTy;
11803 if (!Context.getBOOLDecl()) {
11804 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11805 Sema::LookupOrdinaryName);
11806 if (LookupName(Result, getCurScope())) {
11807 NamedDecl *ND = Result.getFoundDecl();
11808 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11809 Context.setBOOLDecl(TD);
11810 }
11811 }
11812 if (Context.getBOOLDecl())
11813 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011814 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011815 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011816}