blob: 74ee87001247672ce2a2e39fa3024ac33eb68f50 [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 }
Jordan Rose04bec392012-10-10 16:42:54 +000090
Fariborz Jahanianfd090882012-09-21 20:46:37 +000091 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000092 if (Result == AR_Deprecated || Result == AR_Unavailable) {
93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95 AvailabilityResult PDeclResult = PD->getAvailability(0);
96 if (PDeclResult == Result)
97 ObjCPDecl = PD;
98 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000099 }
Jordan Rose04bec392012-10-10 16:42:54 +0000100 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000101
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 switch (Result) {
103 case AR_Available:
104 case AR_NotYetIntroduced:
105 break;
106
107 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000109 break;
110
111 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000112 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000114 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000116 if (ObjCPDecl)
117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118 << ObjCPDecl->getDeclName() << 1;
119 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000120 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000122 << D->getDeclName();
123 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000124 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000125 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000126 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000127 S.Diag(D->getLocation(), diag::note_unavailable_here)
128 << isa<FunctionDecl>(D) << false;
129 if (ObjCPDecl)
130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000132 }
133 break;
134 }
135 return Result;
136}
137
Richard Smith6c4c36c2012-03-30 20:53:28 +0000138/// \brief Emit a note explaining that this function is deleted or unavailable.
139void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141
Richard Smith5bdaac52012-04-02 20:59:25 +0000142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143 // If the method was explicitly defaulted, point at that declaration.
144 if (!Method->isImplicit())
145 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146
147 // Try to diagnose why this special member function was implicitly
148 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000149 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000150 if (CSM != CXXInvalid)
151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
152
153 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000154 }
155
156 Diag(Decl->getLocation(), diag::note_unavailable_here)
157 << 1 << Decl->isDeleted();
158}
159
Jordan Rose0eb3f452012-06-18 22:09:19 +0000160/// \brief Determine whether a FunctionDecl was ever declared with an
161/// explicit storage class.
162static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164 E = D->redecls_end();
165 I != E; ++I) {
166 if (I->getStorageClassAsWritten() != SC_None)
167 return true;
168 }
169 return false;
170}
171
172/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000173/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000175/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000176/// in many cases it will not behave correctly. This is not enabled in C++ mode
177/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178/// and so while there may still be user mistakes, most of the time we can't
179/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000180static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181 const NamedDecl *D,
182 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000183 // This is disabled under C++; there are too many ways for this to fire in
184 // contexts where the warning is a false positive, or where it is technically
185 // correct but benign.
186 if (S.getLangOpts().CPlusPlus)
187 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000188
189 // Check if this is an inlined function or method.
190 FunctionDecl *Current = S.getCurFunctionDecl();
191 if (!Current)
192 return;
193 if (!Current->isInlined())
194 return;
195 if (Current->getLinkage() != ExternalLinkage)
196 return;
197
198 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000199 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000200 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000201
Jordan Rose05233272012-06-21 05:54:50 +0000202 // Downgrade from ExtWarn to Extension if
203 // (1) the supposedly external inline function is in the main file,
204 // and probably won't be included anywhere else.
205 // (2) the thing we're referencing is a pure function.
206 // (3) the thing we're referencing is another inline function.
207 // This last can give us false negatives, but it's better than warning on
208 // wrappers for simple C library functions.
209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211 if (!DowngradeWarning && UsedFn)
212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213
214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215 : diag::warn_internal_in_extern_inline)
216 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000217
218 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000219 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
224 }
225
226 S.Diag(D->getCanonicalDecl()->getLocation(),
227 diag::note_internal_decl_declared_here)
228 << D;
229}
230
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000231/// \brief Determine whether the use of this declaration is valid, and
232/// emit any corresponding diagnostics.
233///
234/// This routine diagnoses various problems with referencing
235/// declarations that can occur when using a declaration. For example,
236/// it might warn if a deprecated or unavailable declaration is being
237/// used, or produce an error (and return true) if a C++0x deleted
238/// function is being used.
239///
240/// \returns true if there was an error (this declaration cannot be
241/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000242///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000243bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000244 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000246 // If there were any diagnostics suppressed by template argument deduction,
247 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253 Diag(Suppressed[I].first, Suppressed[I].second);
254
255 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000256 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000257 // entry from the table, because we want to avoid ever emitting these
258 // diagnostics again.
259 Suppressed.clear();
260 }
261 }
262
Richard Smith34b41d92011-02-20 03:19:35 +0000263 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000264 if (ParsingInitForAutoVars.count(D)) {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << D->getDeclName();
267 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000268 }
269
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000270 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000272 if (FD->isDeleted()) {
273 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000274 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000275 return true;
276 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000277 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000279
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000280 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000281
Jordan Rose0eb3f452012-06-18 22:09:19 +0000282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000283
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000284 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000285}
286
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000287/// \brief Retrieve the message suffix that should be added to a
288/// diagnostic complaining about the given function being deleted or
289/// unavailable.
290std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291 // FIXME: C++0x implicitly-deleted special member functions could be
292 // detected here so that we could improve diagnostics to say, e.g.,
293 // "base class 'A' had a deleted copy constructor".
294 if (FD->isDeleted())
295 return std::string();
296
297 std::string Message;
298 if (FD->getAvailability(&Message))
299 return ": " + Message;
300
301 return std::string();
302}
303
John McCall3323fad2011-09-09 07:56:05 +0000304/// DiagnoseSentinelCalls - This routine checks whether a call or
305/// message-send is to a declaration with the sentinel attribute, and
306/// if so, it checks that the requirements of the sentinel are
307/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000308void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000309 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000310 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000311 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000312 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000313
John McCall3323fad2011-09-09 07:56:05 +0000314 // The number of formal parameters of the declaration.
315 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCall3323fad2011-09-09 07:56:05 +0000317 // The kind of declaration. This is also an index into a %select in
318 // the diagnostic.
319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
320
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000322 numFormalParams = MD->param_size();
323 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000325 numFormalParams = FD->param_size();
326 calleeType = CT_Function;
327 } else if (isa<VarDecl>(D)) {
328 QualType type = cast<ValueDecl>(D)->getType();
329 const FunctionType *fn = 0;
330 if (const PointerType *ptr = type->getAs<PointerType>()) {
331 fn = ptr->getPointeeType()->getAs<FunctionType>();
332 if (!fn) return;
333 calleeType = CT_Function;
334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335 fn = ptr->getPointeeType()->castAs<FunctionType>();
336 calleeType = CT_Block;
337 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000338 return;
John McCall3323fad2011-09-09 07:56:05 +0000339 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000340
John McCall3323fad2011-09-09 07:56:05 +0000341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342 numFormalParams = proto->getNumArgs();
343 } else {
344 numFormalParams = 0;
345 }
346 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000347 return;
348 }
John McCall3323fad2011-09-09 07:56:05 +0000349
350 // "nullPos" is the number of formal parameters at the end which
351 // effectively count as part of the variadic arguments. This is
352 // useful if you would prefer to not have *any* formal parameters,
353 // but the language forces you to have at least one.
354 unsigned nullPos = attr->getNullPos();
355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
357
358 // The number of arguments which should follow the sentinel.
359 unsigned numArgsAfterSentinel = attr->getSentinel();
360
361 // If there aren't enough arguments for all the formal parameters,
362 // the sentinel, and the args after the sentinel, complain.
363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000366 return;
367 }
John McCall3323fad2011-09-09 07:56:05 +0000368
369 // Otherwise, find the sentinel expression.
370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000371 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000372 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000373 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000374
John McCall3323fad2011-09-09 07:56:05 +0000375 // Pick a reasonable string to insert. Optimistically use 'nil' or
376 // 'NULL' if those are actually defined in the context. Only use
377 // 'nil' for ObjC methods, where it's much more likely that the
378 // variadic arguments form a list of object pointers.
379 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000382 if (calleeType == CT_Method &&
383 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000384 NullValue = "nil";
385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000387 else
John McCall3323fad2011-09-09 07:56:05 +0000388 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000389
390 if (MissingNilLoc.isInvalid())
391 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
392 else
393 Diag(MissingNilLoc, diag::warn_missing_sentinel)
394 << calleeType
395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000397}
398
Richard Trieuccd891a2011-09-09 01:45:06 +0000399SourceRange Sema::getExprRange(Expr *E) const {
400 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000401}
402
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403//===----------------------------------------------------------------------===//
404// Standard Promotions and Conversions
405//===----------------------------------------------------------------------===//
406
Chris Lattnere7a2e912008-07-25 21:10:04 +0000407/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000408ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000409 // Handle any placeholder expressions which made it here.
410 if (E->getType()->isPlaceholderType()) {
411 ExprResult result = CheckPlaceholderExpr(E);
412 if (result.isInvalid()) return ExprError();
413 E = result.take();
414 }
415
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416 QualType Ty = E->getType();
417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
418
Chris Lattnere7a2e912008-07-25 21:10:04 +0000419 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000420 E = ImpCastExprToType(E, Context.getPointerType(Ty),
421 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000422 else if (Ty->isArrayType()) {
423 // In C90 mode, arrays only promote to pointers if the array expression is
424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425 // type 'array of type' is converted to an expression that has type 'pointer
426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
427 // that has type 'array of type' ...". The relevant change is "an lvalue"
428 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000429 //
430 // C++ 4.2p1:
431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432 // T" can be converted to an rvalue of type "pointer to T".
433 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000437 }
John Wiegley429bb272011-04-08 18:41:53 +0000438 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000439}
440
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000441static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442 // Check to see if we are dereferencing a null pointer. If so,
443 // and if not volatile-qualified, this is undefined behavior that the
444 // optimizer will delete, so warn about it. People sometimes try to use this
445 // to get a deterministic trap and are surprised by clang's behavior. This
446 // only handles the pattern "*null", which is a very syntactic check.
447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448 if (UO->getOpcode() == UO_Deref &&
449 UO->getSubExpr()->IgnoreParenCasts()->
450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451 !UO->getType().isVolatileQualified()) {
452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453 S.PDiag(diag::warn_indirection_through_null)
454 << UO->getSubExpr()->getSourceRange());
455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456 S.PDiag(diag::note_indirection_through_null));
457 }
458}
459
John Wiegley429bb272011-04-08 18:41:53 +0000460ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000461 // Handle any placeholder expressions which made it here.
462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
465 E = result.take();
466 }
467
John McCall0ae287a2010-12-01 04:43:34 +0000468 // C++ [conv.lval]p1:
469 // A glvalue of a non-function, non-array type T can be
470 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000472
John McCall409fa9a2010-12-06 20:48:59 +0000473 QualType T = E->getType();
474 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000475
John McCall409fa9a2010-12-06 20:48:59 +0000476 // We don't want to throw lvalue-to-rvalue casts on top of
477 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000479 (E->getType() == Context.OverloadTy ||
480 T->isDependentType() ||
481 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000482 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000483
484 // The C standard is actually really unclear on this point, and
485 // DR106 tells us what the result should be but not why. It's
486 // generally best to say that void types just doesn't undergo
487 // lvalue-to-rvalue at all. Note that expressions of unqualified
488 // 'void' type are never l-values, but qualified void can be.
489 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000490 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000491
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000492 CheckForNullPointerDereference(*this, E);
493
John McCall409fa9a2010-12-06 20:48:59 +0000494 // C++ [conv.lval]p1:
495 // [...] If T is a non-class type, the type of the prvalue is the
496 // cv-unqualified version of T. Otherwise, the type of the
497 // rvalue is T.
498 //
499 // C99 6.3.2.1p2:
500 // If the lvalue has qualified type, the value has the unqualified
501 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000502 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000503 if (T.hasQualifiers())
504 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000505
Eli Friedmand2cce132012-02-02 23:15:15 +0000506 UpdateMarkingForLValueToRValue(E);
507
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000508 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
509 E, 0, VK_RValue));
510
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000511 // C11 6.3.2.1p2:
512 // ... if the lvalue has atomic type, the value has the non-atomic version
513 // of the type of the lvalue ...
514 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
515 T = Atomic->getValueType().getUnqualifiedType();
516 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
517 Res.get(), 0, VK_RValue));
518 }
519
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000521}
522
John Wiegley429bb272011-04-08 18:41:53 +0000523ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
524 ExprResult Res = DefaultFunctionArrayConversion(E);
525 if (Res.isInvalid())
526 return ExprError();
527 Res = DefaultLvalueConversion(Res.take());
528 if (Res.isInvalid())
529 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000530 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000531}
532
533
Chris Lattnere7a2e912008-07-25 21:10:04 +0000534/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000535/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000536/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000537/// apply if the array is an argument to the sizeof or address (&) operators.
538/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000539ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000540 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000541 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
542 if (Res.isInvalid())
543 return Owned(E);
544 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000547 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000548
549 // Half FP is a bit different: it's a storage-only type, meaning that any
550 // "use" of it should be promoted to float.
551 if (Ty->isHalfType())
552 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
553
John McCall0ae287a2010-12-01 04:43:34 +0000554 // Try to perform integral promotions if the object has a theoretically
555 // promotable type.
556 if (Ty->isIntegralOrUnscopedEnumerationType()) {
557 // C99 6.3.1.1p2:
558 //
559 // The following may be used in an expression wherever an int or
560 // unsigned int may be used:
561 // - an object or expression with an integer type whose integer
562 // conversion rank is less than or equal to the rank of int
563 // and unsigned int.
564 // - A bit-field of type _Bool, int, signed int, or unsigned int.
565 //
566 // If an int can represent all values of the original type, the
567 // value is converted to an int; otherwise, it is converted to an
568 // unsigned int. These are called the integer promotions. All
569 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000570
John McCall0ae287a2010-12-01 04:43:34 +0000571 QualType PTy = Context.isPromotableBitField(E);
572 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000573 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
574 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000575 }
576 if (Ty->isPromotableIntegerType()) {
577 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000578 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
579 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000580 }
Eli Friedman04e83572009-08-20 04:21:42 +0000581 }
John Wiegley429bb272011-04-08 18:41:53 +0000582 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000583}
584
Chris Lattner05faf172008-07-25 22:25:12 +0000585/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000586/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000587/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000588ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
589 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000590 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000591
John Wiegley429bb272011-04-08 18:41:53 +0000592 ExprResult Res = UsualUnaryConversions(E);
593 if (Res.isInvalid())
594 return Owned(E);
595 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000596
Chris Lattner05faf172008-07-25 22:25:12 +0000597 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000598 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000599 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
600
John McCall96a914a2011-08-27 22:06:17 +0000601 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000602 // promotion, even on class types, but note:
603 // C++11 [conv.lval]p2:
604 // When an lvalue-to-rvalue conversion occurs in an unevaluated
605 // operand or a subexpression thereof the value contained in the
606 // referenced object is not accessed. Otherwise, if the glvalue
607 // has a class type, the conversion copy-initializes a temporary
608 // of type T from the glvalue and the result of the conversion
609 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000610 // FIXME: add some way to gate this entire thing for correctness in
611 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000612 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000613 ExprResult Temp = PerformCopyInitialization(
614 InitializedEntity::InitializeTemporary(E->getType()),
615 E->getExprLoc(),
616 Owned(E));
617 if (Temp.isInvalid())
618 return ExprError();
619 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000620 }
621
John Wiegley429bb272011-04-08 18:41:53 +0000622 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000623}
624
Richard Smith831421f2012-06-25 20:30:08 +0000625/// Determine the degree of POD-ness for an expression.
626/// Incomplete types are considered POD, since this check can be performed
627/// when we're in an unevaluated context.
628Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000629 if (Ty->isIncompleteType()) {
630 if (Ty->isObjCObjectType())
631 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000632 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000633 }
634
635 if (Ty.isCXX98PODType(Context))
636 return VAK_Valid;
637
Richard Smith831421f2012-06-25 20:30:08 +0000638 // C++0x [expr.call]p7:
639 // Passing a potentially-evaluated argument of class type (Clause 9)
640 // having a non-trivial copy constructor, a non-trivial move constructor,
641 // or a non-trivial destructor, with no corresponding parameter,
642 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000643 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
644 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
645 if (Record->hasTrivialCopyConstructor() &&
646 Record->hasTrivialMoveConstructor() &&
647 Record->hasTrivialDestructor())
648 return VAK_ValidInCXX11;
649
650 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
651 return VAK_Valid;
652 return VAK_Invalid;
653}
654
655bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
656 // Don't allow one to pass an Objective-C interface to a vararg.
657 const QualType & Ty = E->getType();
658
659 // Complain about passing non-POD types through varargs.
660 switch (isValidVarArgType(Ty)) {
661 case VAK_Valid:
662 break;
663 case VAK_ValidInCXX11:
664 DiagRuntimeBehavior(E->getLocStart(), 0,
665 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
666 << E->getType() << CT);
667 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000668 case VAK_Invalid: {
669 if (Ty->isObjCObjectType())
670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
672 << Ty << CT);
673
Richard Smith831421f2012-06-25 20:30:08 +0000674 return DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
676 << getLangOpts().CPlusPlus0x << Ty << CT);
677 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000678 }
Richard Smith831421f2012-06-25 20:30:08 +0000679 // c++ rules are enforced elsewhere.
680 return false;
681}
682
Chris Lattner312531a2009-04-12 08:11:20 +0000683/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000684/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000685ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000686 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000687 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000688 // Strip the unbridged-cast placeholder expression off, if applicable.
689 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
690 (CT == VariadicMethod ||
691 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
692 E = stripARCUnbridgedCast(E);
693
694 // Otherwise, do normal placeholder checking.
695 } else {
696 ExprResult ExprRes = CheckPlaceholderExpr(E);
697 if (ExprRes.isInvalid())
698 return ExprError();
699 E = ExprRes.take();
700 }
701 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000702
John McCall5acb0c92011-10-17 18:40:02 +0000703 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000704 if (ExprRes.isInvalid())
705 return ExprError();
706 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Richard Smith831421f2012-06-25 20:30:08 +0000708 // Diagnostics regarding non-POD argument types are
709 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000710 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000711 // Turn this into a trap.
712 CXXScopeSpec SS;
713 SourceLocation TemplateKWLoc;
714 UnqualifiedId Name;
715 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
716 E->getLocStart());
717 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
718 Name, true, false);
719 if (TrapFn.isInvalid())
720 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000721
Richard Smith831421f2012-06-25 20:30:08 +0000722 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
723 E->getLocStart(), MultiExprArg(),
724 E->getLocEnd());
725 if (Call.isInvalid())
726 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000727
Richard Smith831421f2012-06-25 20:30:08 +0000728 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
729 Call.get(), E);
730 if (Comma.isInvalid())
731 return ExprError();
732 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000733 }
Richard Smith831421f2012-06-25 20:30:08 +0000734
David Blaikie4e4d0842012-03-11 07:00:24 +0000735 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000736 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000737 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000738 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000739
John Wiegley429bb272011-04-08 18:41:53 +0000740 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000741}
742
Richard Trieu8289f492011-09-02 20:58:51 +0000743/// \brief Converts an integer to complex float type. Helper function of
744/// UsualArithmeticConversions()
745///
746/// \return false if the integer expression is an integer type and is
747/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000748static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
749 ExprResult &ComplexExpr,
750 QualType IntTy,
751 QualType ComplexTy,
752 bool SkipCast) {
753 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
754 if (SkipCast) return false;
755 if (IntTy->isIntegerType()) {
756 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
757 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000759 CK_FloatingRealToComplex);
760 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000761 assert(IntTy->isComplexIntegerType());
762 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000763 CK_IntegralComplexToFloatingComplex);
764 }
765 return false;
766}
767
768/// \brief Takes two complex float types and converts them to the same type.
769/// Helper function of UsualArithmeticConversions()
770static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000771handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
772 ExprResult &RHS, QualType LHSType,
773 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000774 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000776
777 if (order < 0) {
778 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783 if (order > 0)
784 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000785 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
786 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000787}
788
789/// \brief Converts otherExpr to complex float and promotes complexExpr if
790/// necessary. Helper function of UsualArithmeticConversions()
791static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 ExprResult &ComplexExpr,
793 ExprResult &OtherExpr,
794 QualType ComplexTy,
795 QualType OtherTy,
796 bool ConvertComplexExpr,
797 bool ConvertOtherExpr) {
798 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000799
800 // If just the complexExpr is complex, the otherExpr needs to be converted,
801 // and the complexExpr might need to be promoted.
802 if (order > 0) { // complexExpr is wider
803 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000804 if (ConvertOtherExpr) {
805 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
807 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000808 CK_FloatingRealToComplex);
809 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000811 }
812
813 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000814 QualType result = (order == 0 ? ComplexTy :
815 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000816
817 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000818 if (ConvertOtherExpr)
819 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000820 CK_FloatingRealToComplex);
821
822 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000823 if (ConvertComplexExpr && order < 0)
824 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000825 CK_FloatingComplexCast);
826
827 return result;
828}
829
830/// \brief Handle arithmetic conversion with complex types. Helper function of
831/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000832static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
833 ExprResult &RHS, QualType LHSType,
834 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000835 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000836 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000837 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000838 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000839 return LHSType;
840 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000841 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000842 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000843
844 // This handles complex/complex, complex/float, or float/complex.
845 // When both operands are complex, the shorter operand is converted to the
846 // type of the longer, and that is the type of the result. This corresponds
847 // to what is done when combining two real floating-point operands.
848 // The fun begins when size promotion occur across type domains.
849 // From H&S 6.3.4: When one operand is complex and the other is a real
850 // floating-point type, the less precise type is converted, within it's
851 // real or complex domain, to the precision of the other type. For example,
852 // when combining a "long double" with a "double _Complex", the
853 // "double _Complex" is promoted to "long double _Complex".
854
Richard Trieucafd30b2011-09-06 18:25:09 +0000855 bool LHSComplexFloat = LHSType->isComplexType();
856 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000857
858 // If both are complex, just cast to the more precise type.
859 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000860 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
861 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000862 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000863
864 // If only one operand is complex, promote it if necessary and convert the
865 // other operand to complex.
866 if (LHSComplexFloat)
867 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000868 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000869 /*convertOtherExpr*/ true);
870
871 assert(RHSComplexFloat);
872 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000873 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000874 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000875}
876
877/// \brief Hande arithmetic conversion from integer to float. Helper function
878/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000879static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
880 ExprResult &IntExpr,
881 QualType FloatTy, QualType IntTy,
882 bool ConvertFloat, bool ConvertInt) {
883 if (IntTy->isIntegerType()) {
884 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000885 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000886 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000887 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000889 }
890
891 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000892 assert(IntTy->isComplexIntegerType());
893 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000894
895 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000896 if (ConvertInt)
897 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000898 CK_IntegralComplexToFloatingComplex);
899
900 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (ConvertFloat)
902 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000903 CK_FloatingRealToComplex);
904
905 return result;
906}
907
908/// \brief Handle arithmethic conversion with floating point types. Helper
909/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000910static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
911 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000912 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000913 bool LHSFloat = LHSType->isRealFloatingType();
914 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000915
916 // If we have two real floating types, convert the smaller operand
917 // to the bigger result.
918 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000919 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000920 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000921 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
922 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000923 }
924
925 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000926 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
928 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000929 }
930
931 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000933 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000934 /*convertInt=*/ true);
935 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000936 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000937 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000938 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000939}
940
941/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000942/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000943// FIXME: if the operands are (int, _Complex long), we currently
944// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000945static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
946 ExprResult &RHS, QualType LHSType,
947 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000948 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000949 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
950 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000951
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000952 if (LHSComplexInt && RHSComplexInt) {
953 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
954 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000955 assert(order && "inequal types with equal element ordering");
956 if (order > 0) {
957 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000958 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
959 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960 }
961
Richard Trieuccd891a2011-09-09 01:45:06 +0000962 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000963 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
964 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000965 }
966
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000967 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000968 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000969 // FIXME: This needs to take integer ranks into account
970 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
971 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000972 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
973 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000974 }
975
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000976 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000977 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000978 // FIXME: This needs to take integer ranks into account
979 if (!IsCompAssign) {
980 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
981 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000983 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000984 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000985}
986
987/// \brief Handle integer arithmetic conversions. Helper function of
988/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
990 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000991 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000992 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000993 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
994 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
995 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
996 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000997 // Same signedness; use the higher-ranked type
998 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1000 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001001 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001002 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1003 return RHSType;
1004 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001005 // The unsigned type has greater than or equal rank to the
1006 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 if (RHSSigned) {
1008 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1009 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001010 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001011 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1012 return RHSType;
1013 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001014 // The two types are different widths; if we are here, that
1015 // means the signed type is larger than the unsigned type, so
1016 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001017 if (LHSSigned) {
1018 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1019 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001020 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1022 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001023 } else {
1024 // The signed type is higher-ranked than the unsigned type,
1025 // but isn't actually any bigger (like unsigned int and long
1026 // on most 32-bit systems). Use the unsigned type corresponding
1027 // to the signed type.
1028 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001029 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1030 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001031 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001033 return result;
1034 }
1035}
1036
Chris Lattnere7a2e912008-07-25 21:10:04 +00001037/// UsualArithmeticConversions - Performs various conversions that are common to
1038/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001039/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001040/// responsible for emitting appropriate error diagnostics.
1041/// FIXME: verify the conversion rules for "complex int" are consistent with
1042/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001043QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001044 bool IsCompAssign) {
1045 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001046 LHS = UsualUnaryConversions(LHS.take());
1047 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001048 return QualType();
1049 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001050
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 RHS = UsualUnaryConversions(RHS.take());
1052 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001053 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001054
Mike Stump1eb44332009-09-09 15:08:12 +00001055 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001056 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001057 QualType LHSType =
1058 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1059 QualType RHSType =
1060 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001061
Eli Friedman860a3192012-06-16 02:19:17 +00001062 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1063 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1064 LHSType = AtomicLHS->getValueType();
1065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001066 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType == RHSType)
1068 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001069
1070 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1071 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001073 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001074
John McCallcf33b242010-11-13 08:17:45 +00001075 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001076 QualType LHSUnpromotedType = LHSType;
1077 if (LHSType->isPromotableIntegerType())
1078 LHSType = Context.getPromotedIntegerType(LHSType);
1079 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001080 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001081 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001082 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001083 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001084
John McCallcf33b242010-11-13 08:17:45 +00001085 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001086 if (LHSType == RHSType)
1087 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001088
1089 // At this point, we have two different arithmetic types.
1090
1091 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001092 if (LHSType->isComplexType() || RHSType->isComplexType())
1093 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001094 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001095
1096 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001097 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1098 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001099 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001100
1101 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001102 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001103 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001104 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001105
1106 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001107 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001108 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001109}
1110
Chris Lattnere7a2e912008-07-25 21:10:04 +00001111//===----------------------------------------------------------------------===//
1112// Semantic Analysis for various Expression Types
1113//===----------------------------------------------------------------------===//
1114
1115
Peter Collingbournef111d932011-04-15 00:35:48 +00001116ExprResult
1117Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1118 SourceLocation DefaultLoc,
1119 SourceLocation RParenLoc,
1120 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001121 MultiTypeArg ArgTypes,
1122 MultiExprArg ArgExprs) {
1123 unsigned NumAssocs = ArgTypes.size();
1124 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001125
Benjamin Kramer5354e772012-08-23 23:38:35 +00001126 ParsedType *ParsedTypes = ArgTypes.data();
1127 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001128
1129 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1130 for (unsigned i = 0; i < NumAssocs; ++i) {
1131 if (ParsedTypes[i])
1132 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1133 else
1134 Types[i] = 0;
1135 }
1136
1137 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1138 ControllingExpr, Types, Exprs,
1139 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001140 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001141 return ER;
1142}
1143
1144ExprResult
1145Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1146 SourceLocation DefaultLoc,
1147 SourceLocation RParenLoc,
1148 Expr *ControllingExpr,
1149 TypeSourceInfo **Types,
1150 Expr **Exprs,
1151 unsigned NumAssocs) {
1152 bool TypeErrorFound = false,
1153 IsResultDependent = ControllingExpr->isTypeDependent(),
1154 ContainsUnexpandedParameterPack
1155 = ControllingExpr->containsUnexpandedParameterPack();
1156
1157 for (unsigned i = 0; i < NumAssocs; ++i) {
1158 if (Exprs[i]->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]) {
1162 if (Types[i]->getType()->containsUnexpandedParameterPack())
1163 ContainsUnexpandedParameterPack = true;
1164
1165 if (Types[i]->getType()->isDependentType()) {
1166 IsResultDependent = true;
1167 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001168 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001169 // complete object type other than a variably modified type."
1170 unsigned D = 0;
1171 if (Types[i]->getType()->isIncompleteType())
1172 D = diag::err_assoc_type_incomplete;
1173 else if (!Types[i]->getType()->isObjectType())
1174 D = diag::err_assoc_type_nonobject;
1175 else if (Types[i]->getType()->isVariablyModifiedType())
1176 D = diag::err_assoc_type_variably_modified;
1177
1178 if (D != 0) {
1179 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1180 << Types[i]->getTypeLoc().getSourceRange()
1181 << Types[i]->getType();
1182 TypeErrorFound = true;
1183 }
1184
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001185 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001186 // selection shall specify compatible types."
1187 for (unsigned j = i+1; j < NumAssocs; ++j)
1188 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1189 Context.typesAreCompatible(Types[i]->getType(),
1190 Types[j]->getType())) {
1191 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1192 diag::err_assoc_compatible_types)
1193 << Types[j]->getTypeLoc().getSourceRange()
1194 << Types[j]->getType()
1195 << Types[i]->getType();
1196 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1197 diag::note_compat_assoc)
1198 << Types[i]->getTypeLoc().getSourceRange()
1199 << Types[i]->getType();
1200 TypeErrorFound = true;
1201 }
1202 }
1203 }
1204 }
1205 if (TypeErrorFound)
1206 return ExprError();
1207
1208 // If we determined that the generic selection is result-dependent, don't
1209 // try to compute the result expression.
1210 if (IsResultDependent)
1211 return Owned(new (Context) GenericSelectionExpr(
1212 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001213 llvm::makeArrayRef(Types, NumAssocs),
1214 llvm::makeArrayRef(Exprs, NumAssocs),
1215 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001216
Chris Lattner5f9e2722011-07-23 10:55:15 +00001217 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001218 unsigned DefaultIndex = -1U;
1219 for (unsigned i = 0; i < NumAssocs; ++i) {
1220 if (!Types[i])
1221 DefaultIndex = i;
1222 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1223 Types[i]->getType()))
1224 CompatIndices.push_back(i);
1225 }
1226
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001227 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001228 // type compatible with at most one of the types named in its generic
1229 // association list."
1230 if (CompatIndices.size() > 1) {
1231 // We strip parens here because the controlling expression is typically
1232 // parenthesized in macro definitions.
1233 ControllingExpr = ControllingExpr->IgnoreParens();
1234 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1235 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1236 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001237 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001238 E = CompatIndices.end(); I != E; ++I) {
1239 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1240 diag::note_compat_assoc)
1241 << Types[*I]->getTypeLoc().getSourceRange()
1242 << Types[*I]->getType();
1243 }
1244 return ExprError();
1245 }
1246
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001247 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001248 // its controlling expression shall have type compatible with exactly one of
1249 // the types named in its generic association list."
1250 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1251 // We strip parens here because the controlling expression is typically
1252 // parenthesized in macro definitions.
1253 ControllingExpr = ControllingExpr->IgnoreParens();
1254 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1255 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1256 return ExprError();
1257 }
1258
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001259 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001260 // type name that is compatible with the type of the controlling expression,
1261 // then the result expression of the generic selection is the expression
1262 // in that generic association. Otherwise, the result expression of the
1263 // generic selection is the expression in the default generic association."
1264 unsigned ResultIndex =
1265 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1266
1267 return Owned(new (Context) GenericSelectionExpr(
1268 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001269 llvm::makeArrayRef(Types, NumAssocs),
1270 llvm::makeArrayRef(Exprs, NumAssocs),
1271 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001272 ResultIndex));
1273}
1274
Richard Smithdd66be72012-03-08 01:34:56 +00001275/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1276/// location of the token and the offset of the ud-suffix within it.
1277static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1278 unsigned Offset) {
1279 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001281}
1282
Richard Smith36f5cfe2012-03-09 08:00:36 +00001283/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1284/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1285static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1286 IdentifierInfo *UDSuffix,
1287 SourceLocation UDSuffixLoc,
1288 ArrayRef<Expr*> Args,
1289 SourceLocation LitEndLoc) {
1290 assert(Args.size() <= 2 && "too many arguments for literal operator");
1291
1292 QualType ArgTy[2];
1293 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1294 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1295 if (ArgTy[ArgIdx]->isArrayType())
1296 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1297 }
1298
1299 DeclarationName OpName =
1300 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1301 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1302 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1303
1304 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1305 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1306 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1307 return ExprError();
1308
1309 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1310}
1311
Steve Narofff69936d2007-09-16 03:34:24 +00001312/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001313/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1314/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1315/// multiple tokens. However, the common case is that StringToks points to one
1316/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001317///
John McCall60d7b3a2010-08-24 06:29:42 +00001318ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001319Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1320 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 assert(NumStringToks && "Must have at least one string!");
1322
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001323 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001325 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Chris Lattner5f9e2722011-07-23 10:55:15 +00001327 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 for (unsigned i = 0; i != NumStringToks; ++i)
1329 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001330
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001331 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001332 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001333 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001334 else if (Literal.isUTF16())
1335 StrTy = Context.Char16Ty;
1336 else if (Literal.isUTF32())
1337 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001338 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001339 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001340
Douglas Gregor5cee1192011-07-27 05:40:30 +00001341 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1342 if (Literal.isWide())
1343 Kind = StringLiteral::Wide;
1344 else if (Literal.isUTF8())
1345 Kind = StringLiteral::UTF8;
1346 else if (Literal.isUTF16())
1347 Kind = StringLiteral::UTF16;
1348 else if (Literal.isUTF32())
1349 Kind = StringLiteral::UTF32;
1350
Douglas Gregor77a52232008-09-12 00:47:35 +00001351 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001353 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001354
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001355 // Get an array type for the string, according to C99 6.4.5. This includes
1356 // the nul terminator character as well as the string length for pascal
1357 // strings.
1358 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001359 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001360 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001363 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1364 Kind, Literal.Pascal, StrTy,
1365 &StringTokLocs[0],
1366 StringTokLocs.size());
1367 if (Literal.getUDSuffix().empty())
1368 return Owned(Lit);
1369
1370 // We're building a user-defined literal.
1371 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001372 SourceLocation UDSuffixLoc =
1373 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1374 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001375
Richard Smith36f5cfe2012-03-09 08:00:36 +00001376 // Make sure we're allowed user-defined literals here.
1377 if (!UDLScope)
1378 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1379
Richard Smith9fcce652012-03-07 08:35:16 +00001380 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1381 // operator "" X (str, len)
1382 QualType SizeType = Context.getSizeType();
1383 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1384 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1385 StringTokLocs[0]);
1386 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001387 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1388 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
1390
John McCall60d7b3a2010-08-24 06:29:42 +00001391ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001392Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001393 SourceLocation Loc,
1394 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001395 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001396 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001397}
1398
John McCall76a40212011-02-09 01:13:10 +00001399/// BuildDeclRefExpr - Build an expression that references a
1400/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001401ExprResult
John McCall76a40212011-02-09 01:13:10 +00001402Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001403 const DeclarationNameInfo &NameInfo,
1404 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001406 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1407 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1408 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1409 CalleeTarget = IdentifyCUDATarget(Callee);
1410 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1411 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1412 << CalleeTarget << D->getIdentifier() << CallerTarget;
1413 Diag(D->getLocation(), diag::note_previous_decl)
1414 << D->getIdentifier();
1415 return ExprError();
1416 }
1417 }
1418
John McCallf4b88a42012-03-10 09:33:50 +00001419 bool refersToEnclosingScope =
1420 (CurContext != D->getDeclContext() &&
1421 D->getDeclContext()->isFunctionOrMethod());
1422
Eli Friedman5f2987c2012-02-02 03:46:19 +00001423 DeclRefExpr *E = DeclRefExpr::Create(Context,
1424 SS ? SS->getWithLocInContext(Context)
1425 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001426 SourceLocation(),
1427 D, refersToEnclosingScope,
1428 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Eli Friedman5f2987c2012-02-02 03:46:19 +00001430 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001431
Jordan Rose7a270482012-09-28 22:21:35 +00001432 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1433 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1434 DiagnosticsEngine::Level Level =
1435 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1436 E->getLocStart());
1437 if (Level != DiagnosticsEngine::Ignored)
1438 getCurFunction()->recordUseOfWeak(E);
1439 }
1440
John McCall7eb0a9e2010-11-24 05:12:34 +00001441 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001442 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1443 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001444 E->setObjectKind(OK_BitField);
1445
1446 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001447}
1448
Abramo Bagnara25777432010-08-11 22:01:17 +00001449/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001450/// possibly a list of template arguments.
1451///
1452/// If this produces template arguments, it is permitted to call
1453/// DecomposeTemplateName.
1454///
1455/// This actually loses a lot of source location information for
1456/// non-standard name kinds; we should consider preserving that in
1457/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001458void
1459Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1460 TemplateArgumentListInfo &Buffer,
1461 DeclarationNameInfo &NameInfo,
1462 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001463 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1464 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1465 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1466
Benjamin Kramer5354e772012-08-23 23:38:35 +00001467 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001468 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001469 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001470
John McCall2b5289b2010-08-23 07:28:44 +00001471 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001472 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001473 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001474 TemplateArgs = &Buffer;
1475 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001477 TemplateArgs = 0;
1478 }
1479}
1480
John McCall578b69b2009-12-16 08:11:27 +00001481/// Diagnose an empty lookup.
1482///
1483/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001484bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001485 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001486 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001487 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001488 DeclarationName Name = R.getLookupName();
1489
John McCall578b69b2009-12-16 08:11:27 +00001490 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001491 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001492 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1493 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001494 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001495 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001496 diagnostic_suggest = diag::err_undeclared_use_suggest;
1497 }
John McCall578b69b2009-12-16 08:11:27 +00001498
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001499 // If the original lookup was an unqualified lookup, fake an
1500 // unqualified lookup. This is useful when (for example) the
1501 // original lookup would not have found something because it was a
1502 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001503 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1504 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001505 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001506 if (isa<CXXRecordDecl>(DC)) {
1507 LookupQualifiedName(R, DC);
1508
1509 if (!R.empty()) {
1510 // Don't give errors about ambiguities in this lookup.
1511 R.suppressDiagnostics();
1512
Francois Pichete6226ae2011-11-17 03:44:24 +00001513 // During a default argument instantiation the CurContext points
1514 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1515 // function parameter list, hence add an explicit check.
1516 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1517 ActiveTemplateInstantiations.back().Kind ==
1518 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001519 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1520 bool isInstance = CurMethod &&
1521 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001522 DC == CurMethod->getParent() && !isDefaultArgument;
1523
John McCall578b69b2009-12-16 08:11:27 +00001524
1525 // Give a code modification hint to insert 'this->'.
1526 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1527 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001528 if (getLangOpts().MicrosoftMode)
1529 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001530 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001531 Diag(R.getNameLoc(), diagnostic) << Name
1532 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001533 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1534 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001535
1536
1537 CXXMethodDecl *DepMethod;
1538 if (CurMethod->getTemplatedKind() ==
1539 FunctionDecl::TK_FunctionTemplateSpecialization)
1540 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1541 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1542 else
1543 DepMethod = cast<CXXMethodDecl>(
1544 CurMethod->getInstantiatedFromMemberFunction());
1545 assert(DepMethod && "No template pattern found");
1546
1547 QualType DepThisType = DepMethod->getThisType(Context);
1548 CheckCXXThisCapture(R.getNameLoc());
1549 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550 R.getNameLoc(), DepThisType, false);
1551 TemplateArgumentListInfo TList;
1552 if (ULE->hasExplicitTemplateArgs())
1553 ULE->copyTemplateArgumentsInto(TList);
1554
1555 CXXScopeSpec SS;
1556 SS.Adopt(ULE->getQualifierLoc());
1557 CXXDependentScopeMemberExpr *DepExpr =
1558 CXXDependentScopeMemberExpr::Create(
1559 Context, DepThis, DepThisType, true, SourceLocation(),
1560 SS.getWithLocInContext(Context),
1561 ULE->getTemplateKeywordLoc(), 0,
1562 R.getLookupNameInfo(),
1563 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1564 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001565 } else {
John McCall578b69b2009-12-16 08:11:27 +00001566 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001567 }
John McCall578b69b2009-12-16 08:11:27 +00001568
1569 // Do we really want to note all of these?
1570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1572
Francois Pichete6226ae2011-11-17 03:44:24 +00001573 // Return true if we are inside a default argument instantiation
1574 // and the found name refers to an instance member function, otherwise
1575 // the function calling DiagnoseEmptyLookup will try to create an
1576 // implicit member call and this is wrong for default argument.
1577 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1578 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1579 return true;
1580 }
1581
John McCall578b69b2009-12-16 08:11:27 +00001582 // Tell the callee to try to recover.
1583 return false;
1584 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001585
1586 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001587 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001588
1589 // In Microsoft mode, if we are performing lookup from within a friend
1590 // function definition declared at class scope then we must set
1591 // DC to the lexical parent to be able to search into the parent
1592 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001593 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001594 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1595 DC->getLexicalParent()->isRecord())
1596 DC = DC->getLexicalParent();
1597 else
1598 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001599 }
1600
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001601 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001602 TypoCorrection Corrected;
1603 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001604 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001605 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1606 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 R.setLookupName(Corrected.getCorrection());
1608
Hans Wennborg701d1e72011-07-12 08:45:31 +00001609 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001610 if (Corrected.isOverloaded()) {
1611 OverloadCandidateSet OCS(R.getNameLoc());
1612 OverloadCandidateSet::iterator Best;
1613 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1614 CDEnd = Corrected.end();
1615 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001616 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001617 dyn_cast<FunctionTemplateDecl>(*CD))
1618 AddTemplateOverloadCandidate(
1619 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001621 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1622 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1623 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001624 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001625 }
1626 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1627 case OR_Success:
1628 ND = Best->Function;
1629 break;
1630 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001631 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001632 }
1633 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001634 R.addDecl(ND);
1635 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001636 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1638 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001639 else
1640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001641 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001643 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1644 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001645 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001646 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001647
1648 // Tell the callee to try to recover.
1649 return false;
1650 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001651
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001652 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001653 // FIXME: If we ended up with a typo for a type name or
1654 // Objective-C class name, we're in trouble because the parser
1655 // is in the wrong place to recover. Suggest the typo
1656 // correction, but don't make it a fix-it since we're not going
1657 // to recover well anyway.
1658 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001659 Diag(R.getNameLoc(), diagnostic_suggest)
1660 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001661 else
1662 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001663 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001664 << SS.getRange();
1665
1666 // Don't try to recover; it won't work.
1667 return true;
1668 }
1669 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001670 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001671 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001672 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001673 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001674 else
Douglas Gregord203a162010-01-01 00:15:04 +00001675 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001676 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001677 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001678 return true;
1679 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001680 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001681 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001682
1683 // Emit a special diagnostic for failed member lookups.
1684 // FIXME: computing the declaration context might fail here (?)
1685 if (!SS.isEmpty()) {
1686 Diag(R.getNameLoc(), diag::err_no_member)
1687 << Name << computeDeclContext(SS, false)
1688 << SS.getRange();
1689 return true;
1690 }
1691
John McCall578b69b2009-12-16 08:11:27 +00001692 // Give up, we can't recover.
1693 Diag(R.getNameLoc(), diagnostic) << Name;
1694 return true;
1695}
1696
John McCall60d7b3a2010-08-24 06:29:42 +00001697ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001698 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001699 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001700 UnqualifiedId &Id,
1701 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001702 bool IsAddressOfOperand,
1703 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001704 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001705 "cannot be direct & operand and have a trailing lparen");
1706
1707 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001708 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001709
John McCall129e2df2009-11-30 22:42:35 +00001710 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001711
1712 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001713 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001714 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001715 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001716
Abramo Bagnara25777432010-08-11 22:01:17 +00001717 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001718 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001719 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001720
John McCallf7a1a742009-11-24 19:00:30 +00001721 // C++ [temp.dep.expr]p3:
1722 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001723 // -- an identifier that was declared with a dependent type,
1724 // (note: handled after lookup)
1725 // -- a template-id that is dependent,
1726 // (note: handled in BuildTemplateIdExpr)
1727 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001728 // -- a nested-name-specifier that contains a class-name that
1729 // names a dependent type.
1730 // Determine whether this is a member of an unknown specialization;
1731 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001732 bool DependentID = false;
1733 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1734 Name.getCXXNameType()->isDependentType()) {
1735 DependentID = true;
1736 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001737 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001738 if (RequireCompleteDeclContext(SS, DC))
1739 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001740 } else {
1741 DependentID = true;
1742 }
1743 }
1744
Chris Lattner337e5502011-02-18 01:27:55 +00001745 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001746 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1747 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001748
John McCallf7a1a742009-11-24 19:00:30 +00001749 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001750 LookupResult R(*this, NameInfo,
1751 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1752 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001753 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001754 // Lookup the template name again to correctly establish the context in
1755 // which it was found. This is really unfortunate as we already did the
1756 // lookup to determine that it was a template name in the first place. If
1757 // this becomes a performance hit, we can work harder to preserve those
1758 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001759 bool MemberOfUnknownSpecialization;
1760 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1761 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001762
1763 if (MemberOfUnknownSpecialization ||
1764 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001765 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1766 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001767 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001768 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001769 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001771 // If the result might be in a dependent base class, this is a dependent
1772 // id-expression.
1773 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001774 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1775 IsAddressOfOperand, TemplateArgs);
1776
John McCallf7a1a742009-11-24 19:00:30 +00001777 // If this reference is in an Objective-C method, then we need to do
1778 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001779 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001780 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001781 if (E.isInvalid())
1782 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Chris Lattner337e5502011-02-18 01:27:55 +00001784 if (Expr *Ex = E.takeAs<Expr>())
1785 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001786 }
Chris Lattner8a934232008-03-31 00:36:02 +00001787 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001788
John McCallf7a1a742009-11-24 19:00:30 +00001789 if (R.isAmbiguous())
1790 return ExprError();
1791
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001792 // Determine whether this name might be a candidate for
1793 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001794 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001795
John McCallf7a1a742009-11-24 19:00:30 +00001796 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001798 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001799 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001800 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1801 if (D) R.addDecl(D);
1802 }
1803
1804 // If this name wasn't predeclared and if this is not a function
1805 // call, diagnose the problem.
1806 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001807
1808 // In Microsoft mode, if we are inside a template class member function
1809 // and we can't resolve an identifier then assume the identifier is type
1810 // dependent. The goal is to postpone name lookup to instantiation time
1811 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001812 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001813 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001814 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1815 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001816
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001817 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001818 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001819 return ExprError();
1820
1821 assert(!R.empty() &&
1822 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001823
1824 // If we found an Objective-C instance variable, let
1825 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001826 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001827 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1828 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001829 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001830 // In a hopelessly buggy code, Objective-C instance variable
1831 // lookup fails and no expression will be built to reference it.
1832 if (!E.isInvalid() && !E.get())
1833 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001834 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001835 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 }
1837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
John McCallf7a1a742009-11-24 19:00:30 +00001839 // This is guaranteed from this point on.
1840 assert(!R.empty() || ADL);
1841
John McCallaa81e162009-12-01 22:10:20 +00001842 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001843 // C++ [class.mfct.non-static]p3:
1844 // When an id-expression that is not part of a class member access
1845 // syntax and not used to form a pointer to member is used in the
1846 // body of a non-static member function of class X, if name lookup
1847 // resolves the name in the id-expression to a non-static non-type
1848 // member of some class C, the id-expression is transformed into a
1849 // class member access expression using (*this) as the
1850 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001851 //
1852 // But we don't actually need to do this for '&' operands if R
1853 // resolved to a function or overloaded function set, because the
1854 // expression is ill-formed if it actually works out to be a
1855 // non-static member function:
1856 //
1857 // C++ [expr.ref]p4:
1858 // Otherwise, if E1.E2 refers to a non-static member function. . .
1859 // [t]he expression can be used only as the left-hand operand of a
1860 // member function call.
1861 //
1862 // There are other safeguards against such uses, but it's important
1863 // to get this right here so that we don't end up making a
1864 // spuriously dependent expression if we're inside a dependent
1865 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001866 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001867 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001868 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001869 MightBeImplicitMember = true;
1870 else if (!SS.isEmpty())
1871 MightBeImplicitMember = false;
1872 else if (R.isOverloadedResult())
1873 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001874 else if (R.isUnresolvableResult())
1875 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001876 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001877 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1878 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001879
1880 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001881 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1882 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001883 }
1884
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001885 if (TemplateArgs || TemplateKWLoc.isValid())
1886 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001887
John McCallf7a1a742009-11-24 19:00:30 +00001888 return BuildDeclarationNameExpr(SS, R, ADL);
1889}
1890
John McCall129e2df2009-11-30 22:42:35 +00001891/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1892/// declaration name, generally during template instantiation.
1893/// There's a large number of things which don't need to be done along
1894/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001895ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001896Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001897 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001898 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001899 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001900 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1901 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001902
John McCall77bb1aa2010-05-01 00:40:08 +00001903 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001904 return ExprError();
1905
Abramo Bagnara25777432010-08-11 22:01:17 +00001906 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001907 LookupQualifiedName(R, DC);
1908
1909 if (R.isAmbiguous())
1910 return ExprError();
1911
1912 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001913 Diag(NameInfo.getLoc(), diag::err_no_member)
1914 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001915 return ExprError();
1916 }
1917
1918 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1919}
1920
1921/// LookupInObjCMethod - The parser has read a name in, and Sema has
1922/// detected that we're currently inside an ObjC method. Perform some
1923/// additional lookup.
1924///
1925/// Ideally, most of this would be done by lookup, but there's
1926/// actually quite a lot of extra work involved.
1927///
1928/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001929ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001930Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001931 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001932 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001933 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001934
John McCallf7a1a742009-11-24 19:00:30 +00001935 // There are two cases to handle here. 1) scoped lookup could have failed,
1936 // in which case we should look for an ivar. 2) scoped lookup could have
1937 // found a decl, but that decl is outside the current instance method (i.e.
1938 // a global variable). In these two cases, we do a lookup for an ivar with
1939 // this name, if the lookup sucedes, we replace it our current decl.
1940
1941 // If we're in a class method, we don't normally want to look for
1942 // ivars. But if we don't find anything else, and there's an
1943 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001944 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001945
1946 bool LookForIvars;
1947 if (Lookup.empty())
1948 LookForIvars = true;
1949 else if (IsClassMethod)
1950 LookForIvars = false;
1951 else
1952 LookForIvars = (Lookup.isSingleResult() &&
1953 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001954 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001955 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001956 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001957 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001958 ObjCIvarDecl *IV = 0;
1959 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001960 // Diagnose using an ivar in a class method.
1961 if (IsClassMethod)
1962 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1963 << IV->getDeclName());
1964
1965 // If we're referencing an invalid decl, just return this as a silent
1966 // error node. The error diagnostic was already emitted on the decl.
1967 if (IV->isInvalidDecl())
1968 return ExprError();
1969
1970 // Check if referencing a field with __attribute__((deprecated)).
1971 if (DiagnoseUseOfDecl(IV, Loc))
1972 return ExprError();
1973
1974 // Diagnose the use of an ivar outside of the declaring class.
1975 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001976 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001977 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001978 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1979
1980 // FIXME: This should use a new expr for a direct reference, don't
1981 // turn this into Self->ivar, just return a BareIVarExpr or something.
1982 IdentifierInfo &II = Context.Idents.get("self");
1983 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001984 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001985 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001986 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001987 SourceLocation TemplateKWLoc;
1988 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001989 SelfName, false, false);
1990 if (SelfExpr.isInvalid())
1991 return ExprError();
1992
John Wiegley429bb272011-04-08 18:41:53 +00001993 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1994 if (SelfExpr.isInvalid())
1995 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001996
Eli Friedman5f2987c2012-02-02 03:46:19 +00001997 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001998
1999 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2000 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2001 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002002
2003 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2004 Loc,
2005 SelfExpr.take(),
2006 true, true);
2007
2008 if (getLangOpts().ObjCAutoRefCount) {
2009 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2010 DiagnosticsEngine::Level Level =
2011 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2012 if (Level != DiagnosticsEngine::Ignored)
2013 getCurFunction()->recordUseOfWeak(Result);
2014 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002015 if (CurContext->isClosure())
2016 Diag(Loc, diag::warn_implicitly_retains_self)
2017 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002018 }
2019
2020 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002021 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002022 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002023 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002024 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2025 ObjCInterfaceDecl *ClassDeclared;
2026 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2027 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002028 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002029 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2030 }
John McCallf7a1a742009-11-24 19:00:30 +00002031 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002032 } else if (Lookup.isSingleResult() &&
2033 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2034 // If accessing a stand-alone ivar in a class method, this is an error.
2035 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2036 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2037 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002038 }
2039
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002040 if (Lookup.empty() && II && AllowBuiltinCreation) {
2041 // FIXME. Consolidate this with similar code in LookupName.
2042 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002043 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002044 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2045 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2046 S, Lookup.isForRedeclaration(),
2047 Lookup.getNameLoc());
2048 if (D) Lookup.addDecl(D);
2049 }
2050 }
2051 }
John McCallf7a1a742009-11-24 19:00:30 +00002052 // Sentinel value saying that we didn't do anything special.
2053 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002054}
John McCallba135432009-11-21 08:51:07 +00002055
John McCall6bb80172010-03-30 21:47:33 +00002056/// \brief Cast a base object to a member's actual type.
2057///
2058/// Logically this happens in three phases:
2059///
2060/// * First we cast from the base type to the naming class.
2061/// The naming class is the class into which we were looking
2062/// when we found the member; it's the qualifier type if a
2063/// qualifier was provided, and otherwise it's the base type.
2064///
2065/// * Next we cast from the naming class to the declaring class.
2066/// If the member we found was brought into a class's scope by
2067/// a using declaration, this is that class; otherwise it's
2068/// the class declaring the member.
2069///
2070/// * Finally we cast from the declaring class to the "true"
2071/// declaring class of the member. This conversion does not
2072/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002073ExprResult
2074Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002075 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002076 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002077 NamedDecl *Member) {
2078 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2079 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002080 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002081
Douglas Gregor5fccd362010-03-03 23:55:11 +00002082 QualType DestRecordType;
2083 QualType DestType;
2084 QualType FromRecordType;
2085 QualType FromType = From->getType();
2086 bool PointerConversions = false;
2087 if (isa<FieldDecl>(Member)) {
2088 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002089
Douglas Gregor5fccd362010-03-03 23:55:11 +00002090 if (FromType->getAs<PointerType>()) {
2091 DestType = Context.getPointerType(DestRecordType);
2092 FromRecordType = FromType->getPointeeType();
2093 PointerConversions = true;
2094 } else {
2095 DestType = DestRecordType;
2096 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002097 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002098 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2099 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002100 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002101
Douglas Gregor5fccd362010-03-03 23:55:11 +00002102 DestType = Method->getThisType(Context);
2103 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002104
Douglas Gregor5fccd362010-03-03 23:55:11 +00002105 if (FromType->getAs<PointerType>()) {
2106 FromRecordType = FromType->getPointeeType();
2107 PointerConversions = true;
2108 } else {
2109 FromRecordType = FromType;
2110 DestType = DestRecordType;
2111 }
2112 } else {
2113 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002114 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002115 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002116
Douglas Gregor5fccd362010-03-03 23:55:11 +00002117 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002118 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002119
Douglas Gregor5fccd362010-03-03 23:55:11 +00002120 // If the unqualified types are the same, no conversion is necessary.
2121 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002122 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002123
John McCall6bb80172010-03-30 21:47:33 +00002124 SourceRange FromRange = From->getSourceRange();
2125 SourceLocation FromLoc = FromRange.getBegin();
2126
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002127 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002128
Douglas Gregor5fccd362010-03-03 23:55:11 +00002129 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002130 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002131 // class name.
2132 //
2133 // If the member was a qualified name and the qualified referred to a
2134 // specific base subobject type, we'll cast to that intermediate type
2135 // first and then to the object in which the member is declared. That allows
2136 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2137 //
2138 // class Base { public: int x; };
2139 // class Derived1 : public Base { };
2140 // class Derived2 : public Base { };
2141 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2142 //
2143 // void VeryDerived::f() {
2144 // x = 17; // error: ambiguous base subobjects
2145 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2146 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002147 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002148 QualType QType = QualType(Qualifier->getAsType(), 0);
2149 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2150 assert(QType->isRecordType() && "lookup done with non-record type");
2151
2152 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2153
2154 // In C++98, the qualifier type doesn't actually have to be a base
2155 // type of the object type, in which case we just ignore it.
2156 // Otherwise build the appropriate casts.
2157 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002158 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002159 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002160 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002161 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002162
Douglas Gregor5fccd362010-03-03 23:55:11 +00002163 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002164 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002165 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2166 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002167
2168 FromType = QType;
2169 FromRecordType = QRecordType;
2170
2171 // If the qualifier type was the same as the destination type,
2172 // we're done.
2173 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002174 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002175 }
2176 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002177
John McCall6bb80172010-03-30 21:47:33 +00002178 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002179
John McCall6bb80172010-03-30 21:47:33 +00002180 // If we actually found the member through a using declaration, cast
2181 // down to the using declaration's type.
2182 //
2183 // Pointer equality is fine here because only one declaration of a
2184 // class ever has member declarations.
2185 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2186 assert(isa<UsingShadowDecl>(FoundDecl));
2187 QualType URecordType = Context.getTypeDeclType(
2188 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2189
2190 // We only need to do this if the naming-class to declaring-class
2191 // conversion is non-trivial.
2192 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2193 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002194 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002195 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002196 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002197 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002198
John McCall6bb80172010-03-30 21:47:33 +00002199 QualType UType = URecordType;
2200 if (PointerConversions)
2201 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002202 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2203 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002204 FromType = UType;
2205 FromRecordType = URecordType;
2206 }
2207
2208 // We don't do access control for the conversion from the
2209 // declaring class to the true declaring class.
2210 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002211 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002212
John McCallf871d0c2010-08-07 06:22:56 +00002213 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002214 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2215 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002216 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002217 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002218
John Wiegley429bb272011-04-08 18:41:53 +00002219 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2220 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002221}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002222
John McCallf7a1a742009-11-24 19:00:30 +00002223bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002224 const LookupResult &R,
2225 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002226 // Only when used directly as the postfix-expression of a call.
2227 if (!HasTrailingLParen)
2228 return false;
2229
2230 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002231 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002232 return false;
2233
2234 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002235 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002236 return false;
2237
2238 // Turn off ADL when we find certain kinds of declarations during
2239 // normal lookup:
2240 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2241 NamedDecl *D = *I;
2242
2243 // C++0x [basic.lookup.argdep]p3:
2244 // -- a declaration of a class member
2245 // Since using decls preserve this property, we check this on the
2246 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002247 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002248 return false;
2249
2250 // C++0x [basic.lookup.argdep]p3:
2251 // -- a block-scope function declaration that is not a
2252 // using-declaration
2253 // NOTE: we also trigger this for function templates (in fact, we
2254 // don't check the decl type at all, since all other decl types
2255 // turn off ADL anyway).
2256 if (isa<UsingShadowDecl>(D))
2257 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2258 else if (D->getDeclContext()->isFunctionOrMethod())
2259 return false;
2260
2261 // C++0x [basic.lookup.argdep]p3:
2262 // -- a declaration that is neither a function or a function
2263 // template
2264 // And also for builtin functions.
2265 if (isa<FunctionDecl>(D)) {
2266 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2267
2268 // But also builtin functions.
2269 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2270 return false;
2271 } else if (!isa<FunctionTemplateDecl>(D))
2272 return false;
2273 }
2274
2275 return true;
2276}
2277
2278
John McCallba135432009-11-21 08:51:07 +00002279/// Diagnoses obvious problems with the use of the given declaration
2280/// as an expression. This is only actually called for lookups that
2281/// were not overloaded, and it doesn't promise that the declaration
2282/// will in fact be used.
2283static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002284 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002285 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2286 return true;
2287 }
2288
2289 if (isa<ObjCInterfaceDecl>(D)) {
2290 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2291 return true;
2292 }
2293
2294 if (isa<NamespaceDecl>(D)) {
2295 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2296 return true;
2297 }
2298
2299 return false;
2300}
2301
John McCall60d7b3a2010-08-24 06:29:42 +00002302ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002303Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002304 LookupResult &R,
2305 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002306 // If this is a single, fully-resolved result and we don't need ADL,
2307 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002308 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002309 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2310 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002311
2312 // We only need to check the declaration if there's exactly one
2313 // result, because in the overloaded case the results can only be
2314 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002315 if (R.isSingleResult() &&
2316 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002317 return ExprError();
2318
John McCallc373d482010-01-27 01:50:18 +00002319 // Otherwise, just build an unresolved lookup expression. Suppress
2320 // any lookup-related diagnostics; we'll hash these out later, when
2321 // we've picked a target.
2322 R.suppressDiagnostics();
2323
John McCallba135432009-11-21 08:51:07 +00002324 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002325 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002326 SS.getWithLocInContext(Context),
2327 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002328 NeedsADL, R.isOverloadedResult(),
2329 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002330
2331 return Owned(ULE);
2332}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002333
John McCallba135432009-11-21 08:51:07 +00002334/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002335ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002336Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002337 const DeclarationNameInfo &NameInfo,
2338 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002339 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002340 assert(!isa<FunctionTemplateDecl>(D) &&
2341 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002342
Abramo Bagnara25777432010-08-11 22:01:17 +00002343 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002344 if (CheckDeclInExpr(*this, Loc, D))
2345 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002346
Douglas Gregor9af2f522009-12-01 16:58:18 +00002347 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2348 // Specifically diagnose references to class templates that are missing
2349 // a template argument list.
2350 Diag(Loc, diag::err_template_decl_ref)
2351 << Template << SS.getRange();
2352 Diag(Template->getLocation(), diag::note_template_decl_here);
2353 return ExprError();
2354 }
2355
2356 // Make sure that we're referring to a value.
2357 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2358 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002359 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002360 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002361 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002362 return ExprError();
2363 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002364
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002365 // Check whether this declaration can be used. Note that we suppress
2366 // this check when we're going to perform argument-dependent lookup
2367 // on this function name, because this might not be the function
2368 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002369 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002370 return ExprError();
2371
Steve Naroffdd972f22008-09-05 22:11:13 +00002372 // Only create DeclRefExpr's for valid Decl's.
2373 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002374 return ExprError();
2375
John McCall5808ce42011-02-03 08:15:49 +00002376 // Handle members of anonymous structs and unions. If we got here,
2377 // and the reference is to a class member indirect field, then this
2378 // must be the subject of a pointer-to-member expression.
2379 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2380 if (!indirectField->isCXXClassMember())
2381 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2382 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002383
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002384 {
John McCall76a40212011-02-09 01:13:10 +00002385 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002386 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002387
2388 switch (D->getKind()) {
2389 // Ignore all the non-ValueDecl kinds.
2390#define ABSTRACT_DECL(kind)
2391#define VALUE(type, base)
2392#define DECL(type, base) \
2393 case Decl::type:
2394#include "clang/AST/DeclNodes.inc"
2395 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002396
2397 // These shouldn't make it here.
2398 case Decl::ObjCAtDefsField:
2399 case Decl::ObjCIvar:
2400 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002401
2402 // Enum constants are always r-values and never references.
2403 // Unresolved using declarations are dependent.
2404 case Decl::EnumConstant:
2405 case Decl::UnresolvedUsingValue:
2406 valueKind = VK_RValue;
2407 break;
2408
2409 // Fields and indirect fields that got here must be for
2410 // pointer-to-member expressions; we just call them l-values for
2411 // internal consistency, because this subexpression doesn't really
2412 // exist in the high-level semantics.
2413 case Decl::Field:
2414 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002415 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002416 "building reference to field in C?");
2417
2418 // These can't have reference type in well-formed programs, but
2419 // for internal consistency we do this anyway.
2420 type = type.getNonReferenceType();
2421 valueKind = VK_LValue;
2422 break;
2423
2424 // Non-type template parameters are either l-values or r-values
2425 // depending on the type.
2426 case Decl::NonTypeTemplateParm: {
2427 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2428 type = reftype->getPointeeType();
2429 valueKind = VK_LValue; // even if the parameter is an r-value reference
2430 break;
2431 }
2432
2433 // For non-references, we need to strip qualifiers just in case
2434 // the template parameter was declared as 'const int' or whatever.
2435 valueKind = VK_RValue;
2436 type = type.getUnqualifiedType();
2437 break;
2438 }
2439
2440 case Decl::Var:
2441 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002442 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002443 !type.hasQualifiers() &&
2444 type->isVoidType()) {
2445 valueKind = VK_RValue;
2446 break;
2447 }
2448 // fallthrough
2449
2450 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002451 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002452 // These are always l-values.
2453 valueKind = VK_LValue;
2454 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002455
Douglas Gregor68932842012-02-18 05:51:20 +00002456 // FIXME: Does the addition of const really only apply in
2457 // potentially-evaluated contexts? Since the variable isn't actually
2458 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002459 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002460 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2461 if (!CapturedType.isNull())
2462 type = CapturedType;
2463 }
2464
John McCall76a40212011-02-09 01:13:10 +00002465 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002466 }
2467
John McCall76a40212011-02-09 01:13:10 +00002468 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002469 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2470 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2471 type = Context.BuiltinFnTy;
2472 valueKind = VK_RValue;
2473 break;
2474 }
2475 }
2476
John McCall755d8492011-04-12 00:42:48 +00002477 const FunctionType *fty = type->castAs<FunctionType>();
2478
2479 // If we're referring to a function with an __unknown_anytype
2480 // result type, make the entire expression __unknown_anytype.
2481 if (fty->getResultType() == Context.UnknownAnyTy) {
2482 type = Context.UnknownAnyTy;
2483 valueKind = VK_RValue;
2484 break;
2485 }
2486
John McCall76a40212011-02-09 01:13:10 +00002487 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002488 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002489 valueKind = VK_LValue;
2490 break;
2491 }
2492
2493 // C99 DR 316 says that, if a function type comes from a
2494 // function definition (without a prototype), that type is only
2495 // used for checking compatibility. Therefore, when referencing
2496 // the function, we pretend that we don't have the full function
2497 // type.
John McCall755d8492011-04-12 00:42:48 +00002498 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2499 isa<FunctionProtoType>(fty))
2500 type = Context.getFunctionNoProtoType(fty->getResultType(),
2501 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002502
2503 // Functions are r-values in C.
2504 valueKind = VK_RValue;
2505 break;
2506 }
2507
2508 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002509 // If we're referring to a method with an __unknown_anytype
2510 // result type, make the entire expression __unknown_anytype.
2511 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002512 if (const FunctionProtoType *proto
2513 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002514 if (proto->getResultType() == Context.UnknownAnyTy) {
2515 type = Context.UnknownAnyTy;
2516 valueKind = VK_RValue;
2517 break;
2518 }
2519
John McCall76a40212011-02-09 01:13:10 +00002520 // C++ methods are l-values if static, r-values if non-static.
2521 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2522 valueKind = VK_LValue;
2523 break;
2524 }
2525 // fallthrough
2526
2527 case Decl::CXXConversion:
2528 case Decl::CXXDestructor:
2529 case Decl::CXXConstructor:
2530 valueKind = VK_RValue;
2531 break;
2532 }
2533
2534 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2535 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002536}
2537
John McCall755d8492011-04-12 00:42:48 +00002538ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002539 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002540
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002542 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002543 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2544 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002545 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002546 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002548
Chris Lattnerfa28b302008-01-12 08:14:25 +00002549 // Pre-defined identifiers are of type char[x], where x is the length of the
2550 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Anders Carlsson3a082d82009-09-08 18:24:21 +00002552 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002553 if (!currentDecl && getCurBlock())
2554 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002555 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002556 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002557 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002558 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002559
Anders Carlsson773f3972009-09-11 01:22:35 +00002560 QualType ResTy;
2561 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2562 ResTy = Context.DependentTy;
2563 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002564 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002565
Anders Carlsson773f3972009-09-11 01:22:35 +00002566 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002567 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002568 ResTy = Context.WCharTy.withConst();
2569 else
2570 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002571 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2572 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002573 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002574}
2575
Richard Smith36f5cfe2012-03-09 08:00:36 +00002576ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002577 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002578 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002580 if (Invalid)
2581 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002582
Benjamin Kramerddeea562010-02-27 13:44:12 +00002583 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002584 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002586 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002587
Chris Lattnere8337df2009-12-30 21:19:39 +00002588 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002589 if (Literal.isWide())
2590 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002591 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002592 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002593 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002594 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002595 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002596 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002597 else
2598 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002599
Douglas Gregor5cee1192011-07-27 05:40:30 +00002600 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2601 if (Literal.isWide())
2602 Kind = CharacterLiteral::Wide;
2603 else if (Literal.isUTF16())
2604 Kind = CharacterLiteral::UTF16;
2605 else if (Literal.isUTF32())
2606 Kind = CharacterLiteral::UTF32;
2607
Richard Smithdd66be72012-03-08 01:34:56 +00002608 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2609 Tok.getLocation());
2610
2611 if (Literal.getUDSuffix().empty())
2612 return Owned(Lit);
2613
2614 // We're building a user-defined literal.
2615 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2616 SourceLocation UDSuffixLoc =
2617 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2618
Richard Smith36f5cfe2012-03-09 08:00:36 +00002619 // Make sure we're allowed user-defined literals here.
2620 if (!UDLScope)
2621 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2622
Richard Smithdd66be72012-03-08 01:34:56 +00002623 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2624 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002625 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2626 llvm::makeArrayRef(&Lit, 1),
2627 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002628}
2629
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002630ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2631 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2632 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2633 Context.IntTy, Loc));
2634}
2635
Richard Smithb453ad32012-03-08 08:45:32 +00002636static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2637 QualType Ty, SourceLocation Loc) {
2638 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2639
2640 using llvm::APFloat;
2641 APFloat Val(Format);
2642
2643 APFloat::opStatus result = Literal.GetFloatValue(Val);
2644
2645 // Overflow is always an error, but underflow is only an error if
2646 // we underflowed to zero (APFloat reports denormals as underflow).
2647 if ((result & APFloat::opOverflow) ||
2648 ((result & APFloat::opUnderflow) && Val.isZero())) {
2649 unsigned diagnostic;
2650 SmallString<20> buffer;
2651 if (result & APFloat::opOverflow) {
2652 diagnostic = diag::warn_float_overflow;
2653 APFloat::getLargest(Format).toString(buffer);
2654 } else {
2655 diagnostic = diag::warn_float_underflow;
2656 APFloat::getSmallest(Format).toString(buffer);
2657 }
2658
2659 S.Diag(Loc, diagnostic)
2660 << Ty
2661 << StringRef(buffer.data(), buffer.size());
2662 }
2663
2664 bool isExact = (result == APFloat::opOK);
2665 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2666}
2667
Richard Smith36f5cfe2012-03-09 08:00:36 +00002668ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002670 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002672 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002673 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 }
Ted Kremenek28396602009-01-13 23:19:12 +00002675
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002676 SmallString<128> SpellingBuffer;
2677 // NumericLiteralParser wants to overread by one character. Add padding to
2678 // the buffer in case the token is copied to the buffer. If getSpelling()
2679 // returns a StringRef to the memory buffer, it should have a null char at
2680 // the EOF, so it is also safe.
2681 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002682
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002684 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002685 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002686 if (Invalid)
2687 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002688
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002689 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002691 return ExprError();
2692
Richard Smithb453ad32012-03-08 08:45:32 +00002693 if (Literal.hasUDSuffix()) {
2694 // We're building a user-defined literal.
2695 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2696 SourceLocation UDSuffixLoc =
2697 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2698
Richard Smith36f5cfe2012-03-09 08:00:36 +00002699 // Make sure we're allowed user-defined literals here.
2700 if (!UDLScope)
2701 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002702
Richard Smith36f5cfe2012-03-09 08:00:36 +00002703 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002704 if (Literal.isFloatingLiteral()) {
2705 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2706 // long double, the literal is treated as a call of the form
2707 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002708 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002709 } else {
2710 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2711 // unsigned long long, the literal is treated as a call of the form
2712 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002713 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002714 }
2715
Richard Smith36f5cfe2012-03-09 08:00:36 +00002716 DeclarationName OpName =
2717 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2718 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2719 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2720
2721 // Perform literal operator lookup to determine if we're building a raw
2722 // literal or a cooked one.
2723 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2724 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2725 /*AllowRawAndTemplate*/true)) {
2726 case LOLR_Error:
2727 return ExprError();
2728
2729 case LOLR_Cooked: {
2730 Expr *Lit;
2731 if (Literal.isFloatingLiteral()) {
2732 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2733 } else {
2734 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2735 if (Literal.GetIntegerValue(ResultVal))
2736 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2737 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2738 Tok.getLocation());
2739 }
2740 return BuildLiteralOperatorCall(R, OpNameInfo,
2741 llvm::makeArrayRef(&Lit, 1),
2742 Tok.getLocation());
2743 }
2744
2745 case LOLR_Raw: {
2746 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2747 // literal is treated as a call of the form
2748 // operator "" X ("n")
2749 SourceLocation TokLoc = Tok.getLocation();
2750 unsigned Length = Literal.getUDSuffixOffset();
2751 QualType StrTy = Context.getConstantArrayType(
2752 Context.CharTy, llvm::APInt(32, Length + 1),
2753 ArrayType::Normal, 0);
2754 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002755 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002756 /*Pascal*/false, StrTy, &TokLoc, 1);
2757 return BuildLiteralOperatorCall(R, OpNameInfo,
2758 llvm::makeArrayRef(&Lit, 1), TokLoc);
2759 }
2760
2761 case LOLR_Template:
2762 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2763 // template), L is treated as a call fo the form
2764 // operator "" X <'c1', 'c2', ... 'ck'>()
2765 // where n is the source character sequence c1 c2 ... ck.
2766 TemplateArgumentListInfo ExplicitArgs;
2767 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2768 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2769 llvm::APSInt Value(CharBits, CharIsUnsigned);
2770 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002771 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002772 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002773 TemplateArgumentLocInfo ArgInfo;
2774 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2775 }
2776 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2777 Tok.getLocation(), &ExplicitArgs);
2778 }
2779
2780 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002781 }
2782
Chris Lattner5d661452007-08-26 03:42:43 +00002783 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002784
Chris Lattner5d661452007-08-26 03:42:43 +00002785 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002786 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002787 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002788 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002789 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002790 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002791 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002792 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002793
Richard Smithb453ad32012-03-08 08:45:32 +00002794 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002795
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002796 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002797 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002798 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002799 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002800 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002801 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002802 }
2803 }
Chris Lattner5d661452007-08-26 03:42:43 +00002804 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002805 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002806 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002807 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002808
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002809 // 'long long' is a C99 or C++11 feature.
2810 if (!getLangOpts().C99 && Literal.isLongLong) {
2811 if (getLangOpts().CPlusPlus)
2812 Diag(Tok.getLocation(),
2813 getLangOpts().CPlusPlus0x ?
2814 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2815 else
2816 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2817 }
Neil Boothb9449512007-08-29 22:00:19 +00002818
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002820 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2821 // The microsoft literal suffix extensions support 128-bit literals, which
2822 // may be wider than [u]intmax_t.
2823 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2824 MaxWidth = 128;
2825 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002826
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 if (Literal.GetIntegerValue(ResultVal)) {
2828 // If this value didn't fit into uintmax_t, warn and force to ull.
2829 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002830 Ty = Context.UnsignedLongLongTy;
2831 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002832 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 } else {
2834 // If this value fits into a ULL, try to figure out what else it fits into
2835 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002836
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2838 // be an unsigned int.
2839 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2840
2841 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002842 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002843 if (!Literal.isLong && !Literal.isLongLong) {
2844 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002845 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002846
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 // Does it fit in a unsigned int?
2848 if (ResultVal.isIntN(IntSize)) {
2849 // Does it fit in a signed int?
2850 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002851 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002853 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002854 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002857
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002859 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002860 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002861
Reid Spencer5f016e22007-07-11 17:01:13 +00002862 // Does it fit in a unsigned long?
2863 if (ResultVal.isIntN(LongSize)) {
2864 // Does it fit in a signed long?
2865 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002866 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002868 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002869 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002871 }
2872
Stephen Canonb9e05f12012-05-03 22:49:43 +00002873 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002874 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002875 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002876
Reid Spencer5f016e22007-07-11 17:01:13 +00002877 // Does it fit in a unsigned long long?
2878 if (ResultVal.isIntN(LongLongSize)) {
2879 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002880 // To be compatible with MSVC, hex integer literals ending with the
2881 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002882 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002883 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002884 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002886 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002887 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 }
2889 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002890
2891 // If it doesn't fit in unsigned long long, and we're using Microsoft
2892 // extensions, then its a 128-bit integer literal.
2893 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2894 if (Literal.isUnsigned)
2895 Ty = Context.UnsignedInt128Ty;
2896 else
2897 Ty = Context.Int128Ty;
2898 Width = 128;
2899 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002900
Reid Spencer5f016e22007-07-11 17:01:13 +00002901 // If we still couldn't decide a type, we probably have something that
2902 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002903 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002905 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002906 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002907 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002908
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002909 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002910 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002911 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002912 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002914
Chris Lattner5d661452007-08-26 03:42:43 +00002915 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2916 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002917 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002918 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002919
2920 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002921}
2922
Richard Trieuccd891a2011-09-09 01:45:06 +00002923ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002924 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002925 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002926}
2927
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002928static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2929 SourceLocation Loc,
2930 SourceRange ArgRange) {
2931 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2932 // scalar or vector data type argument..."
2933 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2934 // type (C99 6.2.5p18) or void.
2935 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2936 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2937 << T << ArgRange;
2938 return true;
2939 }
2940
2941 assert((T->isVoidType() || !T->isIncompleteType()) &&
2942 "Scalar types should always be complete");
2943 return false;
2944}
2945
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002946static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2947 SourceLocation Loc,
2948 SourceRange ArgRange,
2949 UnaryExprOrTypeTrait TraitKind) {
2950 // C99 6.5.3.4p1:
2951 if (T->isFunctionType()) {
2952 // alignof(function) is allowed as an extension.
2953 if (TraitKind == UETT_SizeOf)
2954 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2955 return false;
2956 }
2957
2958 // Allow sizeof(void)/alignof(void) as an extension.
2959 if (T->isVoidType()) {
2960 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2961 return false;
2962 }
2963
2964 return true;
2965}
2966
2967static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2968 SourceLocation Loc,
2969 SourceRange ArgRange,
2970 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002971 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2972 // runtime doesn't allow it.
2973 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002974 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2975 << T << (TraitKind == UETT_SizeOf)
2976 << ArgRange;
2977 return true;
2978 }
2979
2980 return false;
2981}
2982
Chandler Carruth9d342d02011-05-26 08:53:10 +00002983/// \brief Check the constrains on expression operands to unary type expression
2984/// and type traits.
2985///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002986/// Completes any types necessary and validates the constraints on the operand
2987/// expression. The logic mostly mirrors the type-based overload, but may modify
2988/// the expression as it completes the type for that expression through template
2989/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002990bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002991 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002992 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002993
2994 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2995 // the result is the size of the referenced type."
2996 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2997 // result shall be the alignment of the referenced type."
2998 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2999 ExprTy = Ref->getPointeeType();
3000
3001 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003002 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3003 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003004
3005 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003006 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3007 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003008 return false;
3009
Richard Trieuccd891a2011-09-09 01:45:06 +00003010 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003011 diag::err_sizeof_alignof_incomplete_type,
3012 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003013 return true;
3014
3015 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003016 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003017 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3018 ExprTy = Ref->getPointeeType();
3019
Richard Trieuccd891a2011-09-09 01:45:06 +00003020 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3021 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003022 return true;
3023
Nico Webercf739922011-06-15 02:47:03 +00003024 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003025 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003026 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3027 QualType OType = PVD->getOriginalType();
3028 QualType Type = PVD->getType();
3029 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003030 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003031 << Type << OType;
3032 Diag(PVD->getLocation(), diag::note_declared_at);
3033 }
3034 }
3035 }
3036 }
3037
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003038 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003039}
3040
3041/// \brief Check the constraints on operands to unary expression and type
3042/// traits.
3043///
3044/// This will complete any types necessary, and validate the various constraints
3045/// on those operands.
3046///
Reid Spencer5f016e22007-07-11 17:01:13 +00003047/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003048/// C99 6.3.2.1p[2-4] all state:
3049/// Except when it is the operand of the sizeof operator ...
3050///
3051/// C++ [expr.sizeof]p4
3052/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3053/// standard conversions are not applied to the operand of sizeof.
3054///
3055/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003056bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003057 SourceLocation OpLoc,
3058 SourceRange ExprRange,
3059 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003060 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003061 return false;
3062
Sebastian Redl5d484e82009-11-23 17:18:46 +00003063 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3064 // the result is the size of the referenced type."
3065 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3066 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003067 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3068 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003069
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003070 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003071 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003072
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003073 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003074 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003075 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003076 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Richard Trieuccd891a2011-09-09 01:45:06 +00003078 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003079 diag::err_sizeof_alignof_incomplete_type,
3080 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003081 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Richard Trieuccd891a2011-09-09 01:45:06 +00003083 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003084 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003085 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Chris Lattner1efaa952009-04-24 00:30:45 +00003087 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003088}
3089
Chandler Carruth9d342d02011-05-26 08:53:10 +00003090static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003091 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003092
Mike Stump1eb44332009-09-09 15:08:12 +00003093 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003094 if (isa<DeclRefExpr>(E))
3095 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003096
3097 // Cannot know anything else if the expression is dependent.
3098 if (E->isTypeDependent())
3099 return false;
3100
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003101 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003102 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3103 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003104 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003105 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003106
3107 // Alignment of a field access is always okay, so long as it isn't a
3108 // bit-field.
3109 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003110 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003111 return false;
3112
Chandler Carruth9d342d02011-05-26 08:53:10 +00003113 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003114}
3115
Chandler Carruth9d342d02011-05-26 08:53:10 +00003116bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003117 E = E->IgnoreParens();
3118
3119 // Cannot know anything else if the expression is dependent.
3120 if (E->isTypeDependent())
3121 return false;
3122
Chandler Carruth9d342d02011-05-26 08:53:10 +00003123 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003124}
3125
Douglas Gregorba498172009-03-13 21:01:28 +00003126/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003127ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003128Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3129 SourceLocation OpLoc,
3130 UnaryExprOrTypeTrait ExprKind,
3131 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003132 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003133 return ExprError();
3134
John McCalla93c9342009-12-07 02:54:59 +00003135 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003136
Douglas Gregorba498172009-03-13 21:01:28 +00003137 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003139 return ExprError();
3140
3141 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003142 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3143 Context.getSizeType(),
3144 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003145}
3146
3147/// \brief Build a sizeof or alignof expression given an expression
3148/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003149ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003150Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3151 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003152 ExprResult PE = CheckPlaceholderExpr(E);
3153 if (PE.isInvalid())
3154 return ExprError();
3155
3156 E = PE.get();
3157
Douglas Gregorba498172009-03-13 21:01:28 +00003158 // Verify that the operand is valid.
3159 bool isInvalid = false;
3160 if (E->isTypeDependent()) {
3161 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003162 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003163 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003164 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003165 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003166 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003167 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003168 isInvalid = true;
3169 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003170 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003171 }
3172
3173 if (isInvalid)
3174 return ExprError();
3175
Eli Friedman71b8fb52012-01-21 01:01:51 +00003176 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3177 PE = TranformToPotentiallyEvaluated(E);
3178 if (PE.isInvalid()) return ExprError();
3179 E = PE.take();
3180 }
3181
Douglas Gregorba498172009-03-13 21:01:28 +00003182 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003183 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003184 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003185 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003186}
3187
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003188/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3189/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003190/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003191ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003192Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003193 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003194 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003195 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003196 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003197
Richard Trieuccd891a2011-09-09 01:45:06 +00003198 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003199 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003200 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003201 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003202 }
Sebastian Redl05189992008-11-11 17:56:53 +00003203
Douglas Gregorba498172009-03-13 21:01:28 +00003204 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003205 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003206 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003207}
3208
John Wiegley429bb272011-04-08 18:41:53 +00003209static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003210 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003211 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003212 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003213
John McCallf6a16482010-12-04 03:47:34 +00003214 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003215 if (V.get()->getObjectKind() != OK_Ordinary) {
3216 V = S.DefaultLvalueConversion(V.take());
3217 if (V.isInvalid())
3218 return QualType();
3219 }
John McCallf6a16482010-12-04 03:47:34 +00003220
Chris Lattnercc26ed72007-08-26 05:39:26 +00003221 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003222 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003223 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Chris Lattnercc26ed72007-08-26 05:39:26 +00003225 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003226 if (V.get()->getType()->isArithmeticType())
3227 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003228
John McCall2cd11fe2010-10-12 02:09:17 +00003229 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003230 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003231 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003232 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003233 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003234 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003235 }
3236
Chris Lattnercc26ed72007-08-26 05:39:26 +00003237 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003238 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003239 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003240 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003241}
3242
3243
Reid Spencer5f016e22007-07-11 17:01:13 +00003244
John McCall60d7b3a2010-08-24 06:29:42 +00003245ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003246Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003247 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003248 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003249 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003250 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003251 case tok::plusplus: Opc = UO_PostInc; break;
3252 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003254
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003255 // Since this might is a postfix expression, get rid of ParenListExprs.
3256 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3257 if (Result.isInvalid()) return ExprError();
3258 Input = Result.take();
3259
John McCall9ae2f072010-08-23 23:25:46 +00003260 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003261}
3262
John McCall1503f0d2012-07-31 05:14:30 +00003263/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3264///
3265/// \return true on error
3266static bool checkArithmeticOnObjCPointer(Sema &S,
3267 SourceLocation opLoc,
3268 Expr *op) {
3269 assert(op->getType()->isObjCObjectPointerType());
3270 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3271 return false;
3272
3273 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3274 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3275 << op->getSourceRange();
3276 return true;
3277}
3278
John McCall60d7b3a2010-08-24 06:29:42 +00003279ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003280Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3281 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003282 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003283 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003284 if (Result.isInvalid()) return ExprError();
3285 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003286
John McCall9ae2f072010-08-23 23:25:46 +00003287 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003288
David Blaikie4e4d0842012-03-11 07:00:24 +00003289 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003290 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003291 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003292 Context.DependentTy,
3293 VK_LValue, OK_Ordinary,
3294 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003295 }
3296
David Blaikie4e4d0842012-03-11 07:00:24 +00003297 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003298 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003299 LHSExp->getType()->isEnumeralType() ||
3300 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003301 RHSExp->getType()->isEnumeralType()) &&
3302 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003303 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003304 }
3305
John McCall9ae2f072010-08-23 23:25:46 +00003306 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003307}
3308
John McCall60d7b3a2010-08-24 06:29:42 +00003309ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003310Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003311 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003312 Expr *LHSExp = Base;
3313 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003314
Chris Lattner12d9ff62007-07-16 00:14:47 +00003315 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003316 if (!LHSExp->getType()->getAs<VectorType>()) {
3317 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3318 if (Result.isInvalid())
3319 return ExprError();
3320 LHSExp = Result.take();
3321 }
3322 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3323 if (Result.isInvalid())
3324 return ExprError();
3325 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003326
Chris Lattner12d9ff62007-07-16 00:14:47 +00003327 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003328 ExprValueKind VK = VK_LValue;
3329 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003330
Reid Spencer5f016e22007-07-11 17:01:13 +00003331 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003332 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003333 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003334 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003335 Expr *BaseExpr, *IndexExpr;
3336 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003337 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3338 BaseExpr = LHSExp;
3339 IndexExpr = RHSExp;
3340 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003341 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003342 BaseExpr = LHSExp;
3343 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003344 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003345 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003346 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003347 BaseExpr = LHSExp;
3348 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003349
3350 // Use custom logic if this should be the pseudo-object subscript
3351 // expression.
3352 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3353 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3354
Steve Naroff14108da2009-07-10 23:34:53 +00003355 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003356 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3357 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3358 << ResultType << BaseExpr->getSourceRange();
3359 return ExprError();
3360 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003361 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3362 // Handle the uncommon case of "123[Ptr]".
3363 BaseExpr = RHSExp;
3364 IndexExpr = LHSExp;
3365 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003366 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003367 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003368 // Handle the uncommon case of "123[Ptr]".
3369 BaseExpr = RHSExp;
3370 IndexExpr = LHSExp;
3371 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003372 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3373 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3374 << ResultType << BaseExpr->getSourceRange();
3375 return ExprError();
3376 }
John McCall183700f2009-09-21 23:43:11 +00003377 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003378 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003379 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003380 VK = LHSExp->getValueKind();
3381 if (VK != VK_RValue)
3382 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003383
Chris Lattner12d9ff62007-07-16 00:14:47 +00003384 // FIXME: need to deal with const...
3385 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003386 } else if (LHSTy->isArrayType()) {
3387 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003388 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003389 // wasn't promoted because of the C90 rule that doesn't
3390 // allow promoting non-lvalue arrays. Warn, then
3391 // force the promotion here.
3392 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3393 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003394 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3395 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003396 LHSTy = LHSExp->getType();
3397
3398 BaseExpr = LHSExp;
3399 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003400 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003401 } else if (RHSTy->isArrayType()) {
3402 // Same as previous, except for 123[f().a] case
3403 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3404 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003405 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3406 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003407 RHSTy = RHSExp->getType();
3408
3409 BaseExpr = RHSExp;
3410 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003411 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003412 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003413 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3414 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003415 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003416 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003417 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003418 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3419 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003420
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003421 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003422 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3423 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003424 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3425
Douglas Gregore7450f52009-03-24 19:52:54 +00003426 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003427 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3428 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003429 // incomplete types are not object types.
3430 if (ResultType->isFunctionType()) {
3431 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3432 << ResultType << BaseExpr->getSourceRange();
3433 return ExprError();
3434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
David Blaikie4e4d0842012-03-11 07:00:24 +00003436 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003437 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003438 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3439 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003440
3441 // C forbids expressions of unqualified void type from being l-values.
3442 // See IsCForbiddenLValueType.
3443 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003444 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003445 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003446 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003447 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003448
John McCall09431682010-11-18 19:01:18 +00003449 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003450 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003451
Mike Stumpeed9cac2009-02-19 03:04:26 +00003452 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003453 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003454}
3455
John McCall60d7b3a2010-08-24 06:29:42 +00003456ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003457 FunctionDecl *FD,
3458 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003459 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003460 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003461 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003462 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003463 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003464 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003465 return ExprError();
3466 }
3467
3468 if (Param->hasUninstantiatedDefaultArg()) {
3469 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003470
Richard Smithadb1d4c2012-07-22 23:45:10 +00003471 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3472 Param);
3473
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003474 // Instantiate the expression.
3475 MultiLevelTemplateArgumentList ArgList
3476 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003477
Nico Weber08e41a62010-11-29 18:19:25 +00003478 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003479 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003480 InstantiatingTemplate Inst(*this, CallLoc, Param,
3481 ArrayRef<TemplateArgument>(Innermost.first,
3482 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003483 if (Inst)
3484 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003485
Nico Weber08e41a62010-11-29 18:19:25 +00003486 ExprResult Result;
3487 {
3488 // C++ [dcl.fct.default]p5:
3489 // The names in the [default argument] expression are bound, and
3490 // the semantic constraints are checked, at the point where the
3491 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003492 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003493 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003494 Result = SubstExpr(UninstExpr, ArgList);
3495 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003496 if (Result.isInvalid())
3497 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003499 // Check the expression as an initializer for the parameter.
3500 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003501 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003502 InitializationKind Kind
3503 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003504 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003505 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003506
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003507 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003508 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003509 if (Result.isInvalid())
3510 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003511
David Blaikiec1c07252012-04-30 18:21:31 +00003512 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003513 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003514 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003515 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003516 }
3517
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003518 // If the default expression creates temporaries, we need to
3519 // push them to the current stack of expression temporaries so they'll
3520 // be properly destroyed.
3521 // FIXME: We should really be rebuilding the default argument with new
3522 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003523 // We don't need to do that with block decls, though, because
3524 // blocks in default argument expression can never capture anything.
3525 if (isa<ExprWithCleanups>(Param->getInit())) {
3526 // Set the "needs cleanups" bit regardless of whether there are
3527 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003528 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003529
3530 // Append all the objects to the cleanup list. Right now, this
3531 // should always be a no-op, because blocks in default argument
3532 // expressions should never be able to capture anything.
3533 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3534 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003535 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003536
3537 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003538 // Just mark all of the declarations in this potentially-evaluated expression
3539 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003540 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3541 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003542 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003543}
3544
Richard Smith831421f2012-06-25 20:30:08 +00003545
3546Sema::VariadicCallType
3547Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3548 Expr *Fn) {
3549 if (Proto && Proto->isVariadic()) {
3550 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3551 return VariadicConstructor;
3552 else if (Fn && Fn->getType()->isBlockPointerType())
3553 return VariadicBlock;
3554 else if (FDecl) {
3555 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3556 if (Method->isInstance())
3557 return VariadicMethod;
3558 }
3559 return VariadicFunction;
3560 }
3561 return VariadicDoesNotApply;
3562}
3563
Douglas Gregor88a35142008-12-22 05:46:06 +00003564/// ConvertArgumentsForCall - Converts the arguments specified in
3565/// Args/NumArgs to the parameter types of the function FDecl with
3566/// function prototype Proto. Call is the call expression itself, and
3567/// Fn is the function expression. For a C++ member function, this
3568/// routine does not attempt to convert the object argument. Returns
3569/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003570bool
3571Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003572 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003573 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003574 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003575 SourceLocation RParenLoc,
3576 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003577 // Bail out early if calling a builtin with custom typechecking.
3578 // We don't need to do this in the
3579 if (FDecl)
3580 if (unsigned ID = FDecl->getBuiltinID())
3581 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3582 return false;
3583
Mike Stumpeed9cac2009-02-19 03:04:26 +00003584 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003585 // assignment, to the types of the corresponding parameter, ...
3586 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003587 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003588 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003589 unsigned FnKind = Fn->getType()->isBlockPointerType()
3590 ? 1 /* block */
3591 : (IsExecConfig ? 3 /* kernel function (exec config) */
3592 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003593
Douglas Gregor88a35142008-12-22 05:46:06 +00003594 // If too few arguments are available (and we don't have default
3595 // arguments for the remaining parameters), don't make the call.
3596 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003597 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003598 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3599 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3600 ? diag::err_typecheck_call_too_few_args_one
3601 : diag::err_typecheck_call_too_few_args_at_least_one)
3602 << FnKind
3603 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3604 else
3605 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3606 ? diag::err_typecheck_call_too_few_args
3607 : diag::err_typecheck_call_too_few_args_at_least)
3608 << FnKind
3609 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003610
3611 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003612 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003613 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3614 << FDecl;
3615
3616 return true;
3617 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003618 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003619 }
3620
3621 // If too many are passed and not variadic, error on the extras and drop
3622 // them.
3623 if (NumArgs > NumArgsInProto) {
3624 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003625 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3626 Diag(Args[NumArgsInProto]->getLocStart(),
3627 MinArgs == NumArgsInProto
3628 ? diag::err_typecheck_call_too_many_args_one
3629 : diag::err_typecheck_call_too_many_args_at_most_one)
3630 << FnKind
3631 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3632 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3633 Args[NumArgs-1]->getLocEnd());
3634 else
3635 Diag(Args[NumArgsInProto]->getLocStart(),
3636 MinArgs == NumArgsInProto
3637 ? diag::err_typecheck_call_too_many_args
3638 : diag::err_typecheck_call_too_many_args_at_most)
3639 << FnKind
3640 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3641 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3642 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003643
3644 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003645 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003646 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3647 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003648
Douglas Gregor88a35142008-12-22 05:46:06 +00003649 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003650 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003651 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003652 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003653 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003654 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003655 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3656
Daniel Dunbar96a00142012-03-09 18:35:03 +00003657 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003658 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003659 if (Invalid)
3660 return true;
3661 unsigned TotalNumArgs = AllArgs.size();
3662 for (unsigned i = 0; i < TotalNumArgs; ++i)
3663 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003664
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003665 return false;
3666}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003667
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003668bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3669 FunctionDecl *FDecl,
3670 const FunctionProtoType *Proto,
3671 unsigned FirstProtoArg,
3672 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003673 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003674 VariadicCallType CallType,
3675 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003676 unsigned NumArgsInProto = Proto->getNumArgs();
3677 unsigned NumArgsToCheck = NumArgs;
3678 bool Invalid = false;
3679 if (NumArgs != NumArgsInProto)
3680 // Use default arguments for missing arguments
3681 NumArgsToCheck = NumArgsInProto;
3682 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003683 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003684 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003685 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003686
Douglas Gregor88a35142008-12-22 05:46:06 +00003687 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003688 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003689 if (ArgIx < NumArgs) {
3690 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003691
Daniel Dunbar96a00142012-03-09 18:35:03 +00003692 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003693 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003694 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003695 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003696
Douglas Gregora188ff22009-12-22 16:09:06 +00003697 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003698 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003699 if (FDecl && i < FDecl->getNumParams())
3700 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003701
John McCall5acb0c92011-10-17 18:40:02 +00003702 // Strip the unbridged-cast placeholder expression off, if applicable.
3703 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3704 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3705 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3706 Arg = stripARCUnbridgedCast(Arg);
3707
Douglas Gregora188ff22009-12-22 16:09:06 +00003708 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003709 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003710 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3711 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003712 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003713 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003714 Owned(Arg),
3715 /*TopLevelOfInitList=*/false,
3716 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003717 if (ArgE.isInvalid())
3718 return true;
3719
3720 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003721 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003722 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003723
John McCall60d7b3a2010-08-24 06:29:42 +00003724 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003725 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003726 if (ArgExpr.isInvalid())
3727 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003728
Anders Carlsson56c5e332009-08-25 03:49:14 +00003729 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003730 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003731
3732 // Check for array bounds violations for each argument to the call. This
3733 // check only triggers warnings when the argument isn't a more complex Expr
3734 // with its own checking, such as a BinaryOperator.
3735 CheckArrayAccess(Arg);
3736
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003737 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3738 CheckStaticArrayArgument(CallLoc, Param, Arg);
3739
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003740 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003741 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003742
Douglas Gregor88a35142008-12-22 05:46:06 +00003743 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003744 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003745 // Assume that extern "C" functions with variadic arguments that
3746 // return __unknown_anytype aren't *really* variadic.
3747 if (Proto->getResultType() == Context.UnknownAnyTy &&
3748 FDecl && FDecl->isExternC()) {
3749 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3750 ExprResult arg;
3751 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3752 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3753 else
3754 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3755 Invalid |= arg.isInvalid();
3756 AllArgs.push_back(arg.take());
3757 }
3758
3759 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3760 } else {
3761 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003762 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3763 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003764 Invalid |= Arg.isInvalid();
3765 AllArgs.push_back(Arg.take());
3766 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003767 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003768
3769 // Check for array bounds violations.
3770 for (unsigned i = ArgIx; i != NumArgs; ++i)
3771 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003772 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003773 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003774}
3775
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003776static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3777 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3778 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3779 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3780 << ATL->getLocalSourceRange();
3781}
3782
3783/// CheckStaticArrayArgument - If the given argument corresponds to a static
3784/// array parameter, check that it is non-null, and that if it is formed by
3785/// array-to-pointer decay, the underlying array is sufficiently large.
3786///
3787/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3788/// array type derivation, then for each call to the function, the value of the
3789/// corresponding actual argument shall provide access to the first element of
3790/// an array with at least as many elements as specified by the size expression.
3791void
3792Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3793 ParmVarDecl *Param,
3794 const Expr *ArgExpr) {
3795 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003796 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003797 return;
3798
3799 QualType OrigTy = Param->getOriginalType();
3800
3801 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3802 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3803 return;
3804
3805 if (ArgExpr->isNullPointerConstant(Context,
3806 Expr::NPC_NeverValueDependent)) {
3807 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3808 DiagnoseCalleeStaticArrayParam(*this, Param);
3809 return;
3810 }
3811
3812 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3813 if (!CAT)
3814 return;
3815
3816 const ConstantArrayType *ArgCAT =
3817 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3818 if (!ArgCAT)
3819 return;
3820
3821 if (ArgCAT->getSize().ult(CAT->getSize())) {
3822 Diag(CallLoc, diag::warn_static_array_too_small)
3823 << ArgExpr->getSourceRange()
3824 << (unsigned) ArgCAT->getSize().getZExtValue()
3825 << (unsigned) CAT->getSize().getZExtValue();
3826 DiagnoseCalleeStaticArrayParam(*this, Param);
3827 }
3828}
3829
John McCall755d8492011-04-12 00:42:48 +00003830/// Given a function expression of unknown-any type, try to rebuild it
3831/// to have a function type.
3832static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3833
Steve Narofff69936d2007-09-16 03:34:24 +00003834/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003835/// This provides the location of the left/right parens and a list of comma
3836/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003837ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003838Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003839 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003840 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003841 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003842 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003843 if (Result.isInvalid()) return ExprError();
3844 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003845
David Blaikie4e4d0842012-03-11 07:00:24 +00003846 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003847 // If this is a pseudo-destructor expression, build the call immediately.
3848 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003849 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003850 // Pseudo-destructor calls should not have any arguments.
3851 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003852 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003853 SourceRange(ArgExprs[0]->getLocStart(),
3854 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003855 }
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003857 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3858 Context.VoidTy, VK_RValue,
3859 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003860 }
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Douglas Gregor17330012009-02-04 15:01:18 +00003862 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003863 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003864 // FIXME: Will need to cache the results of name lookup (including ADL) in
3865 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003866 bool Dependent = false;
3867 if (Fn->isTypeDependent())
3868 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003869 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003870 Dependent = true;
3871
Peter Collingbournee08ce652011-02-09 21:07:24 +00003872 if (Dependent) {
3873 if (ExecConfig) {
3874 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003875 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003876 Context.DependentTy, VK_RValue, RParenLoc));
3877 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003878 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003879 Context.DependentTy, VK_RValue,
3880 RParenLoc));
3881 }
3882 }
Douglas Gregor17330012009-02-04 15:01:18 +00003883
3884 // Determine whether this is a call to an object (C++ [over.call.object]).
3885 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003886 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3887 ArgExprs.data(),
3888 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003889
John McCall755d8492011-04-12 00:42:48 +00003890 if (Fn->getType() == Context.UnknownAnyTy) {
3891 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3892 if (result.isInvalid()) return ExprError();
3893 Fn = result.take();
3894 }
3895
John McCall864c0412011-04-26 20:42:42 +00003896 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003897 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3898 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003899 }
John McCall864c0412011-04-26 20:42:42 +00003900 }
John McCall129e2df2009-11-30 22:42:35 +00003901
John McCall864c0412011-04-26 20:42:42 +00003902 // Check for overloaded calls. This can happen even in C due to extensions.
3903 if (Fn->getType() == Context.OverloadTy) {
3904 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3905
Douglas Gregoree697e62011-10-13 18:10:35 +00003906 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003907 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003908 OverloadExpr *ovl = find.Expression;
3909 if (isa<UnresolvedLookupExpr>(ovl)) {
3910 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003911 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3912 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003913 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003914 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3915 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003916 }
3917 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003918 }
3919
Douglas Gregorfa047642009-02-04 00:32:51 +00003920 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003921 if (Fn->getType() == Context.UnknownAnyTy) {
3922 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3923 if (result.isInvalid()) return ExprError();
3924 Fn = result.take();
3925 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003926
Eli Friedmanefa42f72009-12-26 03:35:45 +00003927 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003928
John McCall3b4294e2009-12-16 12:17:52 +00003929 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003930 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3931 if (UnOp->getOpcode() == UO_AddrOf)
3932 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3933
John McCall3b4294e2009-12-16 12:17:52 +00003934 if (isa<DeclRefExpr>(NakedFn))
3935 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003936 else if (isa<MemberExpr>(NakedFn))
3937 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003938
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003939 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3940 ArgExprs.size(), RParenLoc, ExecConfig,
3941 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003942}
3943
3944ExprResult
3945Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003946 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003947 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3948 if (!ConfigDecl)
3949 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3950 << "cudaConfigureCall");
3951 QualType ConfigQTy = ConfigDecl->getType();
3952
3953 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003954 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003955 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003956
Peter Collingbourne1f240762011-10-02 23:49:29 +00003957 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3958 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003959}
3960
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003961/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3962///
3963/// __builtin_astype( value, dst type )
3964///
Richard Trieuccd891a2011-09-09 01:45:06 +00003965ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003966 SourceLocation BuiltinLoc,
3967 SourceLocation RParenLoc) {
3968 ExprValueKind VK = VK_RValue;
3969 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003970 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3971 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003972 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3973 return ExprError(Diag(BuiltinLoc,
3974 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003975 << DstTy
3976 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003977 << E->getSourceRange());
3978 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003979 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003980}
3981
John McCall3b4294e2009-12-16 12:17:52 +00003982/// BuildResolvedCallExpr - Build a call to a resolved expression,
3983/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003984/// unary-convert to an expression of function-pointer or
3985/// block-pointer type.
3986///
3987/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003988ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003989Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3990 SourceLocation LParenLoc,
3991 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003992 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003993 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003994 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003995 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00003996
Chris Lattner04421082008-04-08 04:40:51 +00003997 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003998 // We special-case function promotion here because we only allow promoting
3999 // builtin functions to function pointers in the callee of a call.
4000 ExprResult Result;
4001 if (BuiltinID &&
4002 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4003 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4004 CK_BuiltinFnToFnPtr).take();
4005 } else {
4006 Result = UsualUnaryConversions(Fn);
4007 }
John Wiegley429bb272011-04-08 18:41:53 +00004008 if (Result.isInvalid())
4009 return ExprError();
4010 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004011
Chris Lattner925e60d2007-12-28 05:29:59 +00004012 // Make the call expr early, before semantic checks. This guarantees cleanup
4013 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004014 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004015 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004016 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4017 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004018 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004019 Context.BoolTy,
4020 VK_RValue,
4021 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004022 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004023 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004024 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004025 Context.BoolTy,
4026 VK_RValue,
4027 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004028
John McCall8e10f3b2011-02-26 05:39:39 +00004029 // Bail out early if calling a builtin with custom typechecking.
4030 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4031 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4032
John McCall1de4d4e2011-04-07 08:22:57 +00004033 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004034 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004035 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004036 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4037 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004038 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004039 if (FuncT == 0)
4040 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4041 << Fn->getType() << Fn->getSourceRange());
4042 } else if (const BlockPointerType *BPT =
4043 Fn->getType()->getAs<BlockPointerType>()) {
4044 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4045 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004046 // Handle calls to expressions of unknown-any type.
4047 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004048 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004049 if (rewrite.isInvalid()) return ExprError();
4050 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004051 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004052 goto retry;
4053 }
4054
Sebastian Redl0eb23302009-01-19 00:08:26 +00004055 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4056 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004057 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004058
David Blaikie4e4d0842012-03-11 07:00:24 +00004059 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004060 if (Config) {
4061 // CUDA: Kernel calls must be to global functions
4062 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4063 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4064 << FDecl->getName() << Fn->getSourceRange());
4065
4066 // CUDA: Kernel function must have 'void' return type
4067 if (!FuncT->getResultType()->isVoidType())
4068 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4069 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004070 } else {
4071 // CUDA: Calls to global functions must be configured
4072 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4073 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4074 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004075 }
4076 }
4077
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004078 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004079 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004080 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004081 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004082 return ExprError();
4083
Chris Lattner925e60d2007-12-28 05:29:59 +00004084 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004085 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004086 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004087
Richard Smith831421f2012-06-25 20:30:08 +00004088 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4089 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004090 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004091 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004092 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004093 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004094 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004095
Douglas Gregor74734d52009-04-02 15:37:10 +00004096 if (FDecl) {
4097 // Check if we have too few/too many template arguments, based
4098 // on our knowledge of the function definition.
4099 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004100 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004101 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004102 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004103 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4104 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004105 }
Douglas Gregor46542412010-10-25 20:39:23 +00004106
4107 // If the function we're calling isn't a function prototype, but we have
4108 // a function prototype from a prior declaratiom, use that prototype.
4109 if (!FDecl->hasPrototype())
4110 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004111 }
4112
Steve Naroffb291ab62007-08-28 23:30:39 +00004113 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004114 for (unsigned i = 0; i != NumArgs; i++) {
4115 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004116
4117 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004118 InitializedEntity Entity
4119 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004120 Proto->getArgType(i),
4121 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004122 ExprResult ArgE = PerformCopyInitialization(Entity,
4123 SourceLocation(),
4124 Owned(Arg));
4125 if (ArgE.isInvalid())
4126 return true;
4127
4128 Arg = ArgE.takeAs<Expr>();
4129
4130 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004131 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4132
4133 if (ArgE.isInvalid())
4134 return true;
4135
4136 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004137 }
4138
Daniel Dunbar96a00142012-03-09 18:35:03 +00004139 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004140 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004141 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004142 return ExprError();
4143
Chris Lattner925e60d2007-12-28 05:29:59 +00004144 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004145 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004146 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004147
Douglas Gregor88a35142008-12-22 05:46:06 +00004148 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4149 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004150 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4151 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004152
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004153 // Check for sentinels
4154 if (NDecl)
4155 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Chris Lattner59907c42007-08-10 20:18:51 +00004157 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004158 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004159 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004160 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004161
John McCall8e10f3b2011-02-26 05:39:39 +00004162 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004163 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004164 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004165 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004166 return ExprError();
4167 }
Chris Lattner59907c42007-08-10 20:18:51 +00004168
John McCall9ae2f072010-08-23 23:25:46 +00004169 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004170}
4171
John McCall60d7b3a2010-08-24 06:29:42 +00004172ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004173Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004174 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004175 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004176 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004177 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004178
4179 TypeSourceInfo *TInfo;
4180 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4181 if (!TInfo)
4182 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4183
John McCall9ae2f072010-08-23 23:25:46 +00004184 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004185}
4186
John McCall60d7b3a2010-08-24 06:29:42 +00004187ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004188Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004189 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004190 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004191
Eli Friedman6223c222008-05-20 05:22:08 +00004192 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004193 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004194 diag::err_illegal_decl_array_incomplete_type,
4195 SourceRange(LParenLoc,
4196 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004197 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004198 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004199 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004200 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004201 } else if (!literalType->isDependentType() &&
4202 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004203 diag::err_typecheck_decl_incomplete_type,
4204 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004205 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004206
Douglas Gregor99a2e602009-12-16 01:38:02 +00004207 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004208 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004209 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004210 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004211 SourceRange(LParenLoc, RParenLoc),
4212 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004213 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004214 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4215 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004216 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004217 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004218 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004219
Chris Lattner371f2582008-12-04 23:50:19 +00004220 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004221 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004222 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004223 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004224 }
Eli Friedman08544622009-12-22 02:35:53 +00004225
John McCallf89e55a2010-11-18 06:31:45 +00004226 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004227 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004228
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004229 return MaybeBindToTemporary(
4230 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004231 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004232}
4233
John McCall60d7b3a2010-08-24 06:29:42 +00004234ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004235Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004236 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004237 // Immediately handle non-overload placeholders. Overloads can be
4238 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004239 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4240 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4241 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004242
4243 // Ignore failures; dropping the entire initializer list because
4244 // of one failure would be terrible for indexing/etc.
4245 if (result.isInvalid()) continue;
4246
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004247 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004248 }
4249 }
4250
Steve Naroff08d92e42007-09-15 18:49:24 +00004251 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004252 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004253
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004254 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4255 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004256 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004257 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004258}
4259
John McCalldc05b112011-09-10 01:16:55 +00004260/// Do an explicit extend of the given block pointer if we're in ARC.
4261static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4262 assert(E.get()->getType()->isBlockPointerType());
4263 assert(E.get()->isRValue());
4264
4265 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004266 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004267
4268 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004269 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004270 /*base path*/ 0, VK_RValue);
4271 S.ExprNeedsCleanups = true;
4272}
4273
4274/// Prepare a conversion of the given expression to an ObjC object
4275/// pointer type.
4276CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4277 QualType type = E.get()->getType();
4278 if (type->isObjCObjectPointerType()) {
4279 return CK_BitCast;
4280 } else if (type->isBlockPointerType()) {
4281 maybeExtendBlockObject(*this, E);
4282 return CK_BlockPointerToObjCPointerCast;
4283 } else {
4284 assert(type->isPointerType());
4285 return CK_CPointerToObjCPointerCast;
4286 }
4287}
4288
John McCallf3ea8cf2010-11-14 08:17:51 +00004289/// Prepares for a scalar cast, performing all the necessary stages
4290/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004291CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004292 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4293 // Also, callers should have filtered out the invalid cases with
4294 // pointers. Everything else should be possible.
4295
John Wiegley429bb272011-04-08 18:41:53 +00004296 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004297 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004298 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004299
John McCall1d9b3b22011-09-09 05:25:32 +00004300 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004301 case Type::STK_MemberPointer:
4302 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004303
John McCall1d9b3b22011-09-09 05:25:32 +00004304 case Type::STK_CPointer:
4305 case Type::STK_BlockPointer:
4306 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004307 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004308 case Type::STK_CPointer:
4309 return CK_BitCast;
4310 case Type::STK_BlockPointer:
4311 return (SrcKind == Type::STK_BlockPointer
4312 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4313 case Type::STK_ObjCObjectPointer:
4314 if (SrcKind == Type::STK_ObjCObjectPointer)
4315 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004316 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004317 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004318 maybeExtendBlockObject(*this, Src);
4319 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004320 case Type::STK_Bool:
4321 return CK_PointerToBoolean;
4322 case Type::STK_Integral:
4323 return CK_PointerToIntegral;
4324 case Type::STK_Floating:
4325 case Type::STK_FloatingComplex:
4326 case Type::STK_IntegralComplex:
4327 case Type::STK_MemberPointer:
4328 llvm_unreachable("illegal cast from pointer");
4329 }
David Blaikie7530c032012-01-17 06:56:22 +00004330 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004331
John McCalldaa8e4e2010-11-15 09:13:47 +00004332 case Type::STK_Bool: // casting from bool is like casting from an integer
4333 case Type::STK_Integral:
4334 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004335 case Type::STK_CPointer:
4336 case Type::STK_ObjCObjectPointer:
4337 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004338 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004339 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004340 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004341 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004342 case Type::STK_Bool:
4343 return CK_IntegralToBoolean;
4344 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004345 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004346 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004347 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004348 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004349 Src = ImpCastExprToType(Src.take(),
4350 DestTy->castAs<ComplexType>()->getElementType(),
4351 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004352 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004353 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004354 Src = ImpCastExprToType(Src.take(),
4355 DestTy->castAs<ComplexType>()->getElementType(),
4356 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004357 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004358 case Type::STK_MemberPointer:
4359 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004360 }
David Blaikie7530c032012-01-17 06:56:22 +00004361 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004362
John McCalldaa8e4e2010-11-15 09:13:47 +00004363 case Type::STK_Floating:
4364 switch (DestTy->getScalarTypeKind()) {
4365 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004366 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004367 case Type::STK_Bool:
4368 return CK_FloatingToBoolean;
4369 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004370 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004371 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004372 Src = ImpCastExprToType(Src.take(),
4373 DestTy->castAs<ComplexType>()->getElementType(),
4374 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004375 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004376 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004377 Src = ImpCastExprToType(Src.take(),
4378 DestTy->castAs<ComplexType>()->getElementType(),
4379 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004380 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004381 case Type::STK_CPointer:
4382 case Type::STK_ObjCObjectPointer:
4383 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004384 llvm_unreachable("valid float->pointer cast?");
4385 case Type::STK_MemberPointer:
4386 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004387 }
David Blaikie7530c032012-01-17 06:56:22 +00004388 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004389
John McCalldaa8e4e2010-11-15 09:13:47 +00004390 case Type::STK_FloatingComplex:
4391 switch (DestTy->getScalarTypeKind()) {
4392 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004393 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004394 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004395 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004396 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004397 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4398 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004399 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004400 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004401 return CK_FloatingCast;
4402 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004403 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004404 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004405 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004406 Src = ImpCastExprToType(Src.take(),
4407 SrcTy->castAs<ComplexType>()->getElementType(),
4408 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004409 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004410 case Type::STK_CPointer:
4411 case Type::STK_ObjCObjectPointer:
4412 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004413 llvm_unreachable("valid complex float->pointer cast?");
4414 case Type::STK_MemberPointer:
4415 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004416 }
David Blaikie7530c032012-01-17 06:56:22 +00004417 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004418
John McCalldaa8e4e2010-11-15 09:13:47 +00004419 case Type::STK_IntegralComplex:
4420 switch (DestTy->getScalarTypeKind()) {
4421 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004422 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004423 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004424 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004425 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004426 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4427 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004428 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004429 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004430 return CK_IntegralCast;
4431 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004432 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004433 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004434 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004435 Src = ImpCastExprToType(Src.take(),
4436 SrcTy->castAs<ComplexType>()->getElementType(),
4437 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004438 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004439 case Type::STK_CPointer:
4440 case Type::STK_ObjCObjectPointer:
4441 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004442 llvm_unreachable("valid complex int->pointer cast?");
4443 case Type::STK_MemberPointer:
4444 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004445 }
David Blaikie7530c032012-01-17 06:56:22 +00004446 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004447 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004448
John McCallf3ea8cf2010-11-14 08:17:51 +00004449 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004450}
4451
Anders Carlssonc3516322009-10-16 02:48:28 +00004452bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004453 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004454 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004455
Anders Carlssona64db8f2007-11-27 05:51:55 +00004456 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004457 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004458 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004459 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004460 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004461 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004462 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004463 } else
4464 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004465 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004466 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004467
John McCall2de56d12010-08-25 11:45:40 +00004468 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004469 return false;
4470}
4471
John Wiegley429bb272011-04-08 18:41:53 +00004472ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4473 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004474 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004475
Anders Carlsson16a89042009-10-16 05:23:41 +00004476 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004477
Nate Begeman9b10da62009-06-27 22:05:55 +00004478 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4479 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004480 // In OpenCL, casts between vectors of different types are not allowed.
4481 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004482 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004483 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004484 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004485 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004486 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004487 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004488 return ExprError();
4489 }
John McCall2de56d12010-08-25 11:45:40 +00004490 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004491 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004492 }
4493
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004494 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004495 // conversion will take place first from scalar to elt type, and then
4496 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004497 if (SrcTy->isPointerType())
4498 return Diag(R.getBegin(),
4499 diag::err_invalid_conversion_between_vector_and_scalar)
4500 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004501
4502 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004503 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004504 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004505 if (CastExprRes.isInvalid())
4506 return ExprError();
4507 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004508
John McCall2de56d12010-08-25 11:45:40 +00004509 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004510 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004511}
4512
John McCall60d7b3a2010-08-24 06:29:42 +00004513ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004514Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4515 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004516 SourceLocation RParenLoc, Expr *CastExpr) {
4517 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004518 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004519
Richard Trieuccd891a2011-09-09 01:45:06 +00004520 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004521 if (D.isInvalidType())
4522 return ExprError();
4523
David Blaikie4e4d0842012-03-11 07:00:24 +00004524 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004525 // Check that there are no default arguments (C++ only).
4526 CheckExtraCXXDefaultArguments(D);
4527 }
4528
John McCalle82247a2011-10-01 05:17:03 +00004529 checkUnusedDeclAttributes(D);
4530
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004531 QualType castType = castTInfo->getType();
4532 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004534 bool isVectorLiteral = false;
4535
4536 // Check for an altivec or OpenCL literal,
4537 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004538 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4539 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004540 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004541 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004542 if (PLE && PLE->getNumExprs() == 0) {
4543 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4544 return ExprError();
4545 }
4546 if (PE || PLE->getNumExprs() == 1) {
4547 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4548 if (!E->getType()->isVectorType())
4549 isVectorLiteral = true;
4550 }
4551 else
4552 isVectorLiteral = true;
4553 }
4554
4555 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4556 // then handle it as such.
4557 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004558 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004559
Nate Begeman2ef13e52009-08-10 23:49:36 +00004560 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004561 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4562 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004563 if (isa<ParenListExpr>(CastExpr)) {
4564 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004565 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004566 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004567 }
John McCallb042fdf2010-01-15 18:56:44 +00004568
Richard Trieuccd891a2011-09-09 01:45:06 +00004569 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004570}
4571
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004572ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4573 SourceLocation RParenLoc, Expr *E,
4574 TypeSourceInfo *TInfo) {
4575 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4576 "Expected paren or paren list expression");
4577
4578 Expr **exprs;
4579 unsigned numExprs;
4580 Expr *subExpr;
4581 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4582 exprs = PE->getExprs();
4583 numExprs = PE->getNumExprs();
4584 } else {
4585 subExpr = cast<ParenExpr>(E)->getSubExpr();
4586 exprs = &subExpr;
4587 numExprs = 1;
4588 }
4589
4590 QualType Ty = TInfo->getType();
4591 assert(Ty->isVectorType() && "Expected vector type");
4592
Chris Lattner5f9e2722011-07-23 10:55:15 +00004593 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004594 const VectorType *VTy = Ty->getAs<VectorType>();
4595 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4596
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004597 // '(...)' form of vector initialization in AltiVec: the number of
4598 // initializers must be one or must match the size of the vector.
4599 // If a single value is specified in the initializer then it will be
4600 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004601 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004602 // The number of initializers must be one or must match the size of the
4603 // vector. If a single value is specified in the initializer then it will
4604 // be replicated to all the components of the vector
4605 if (numExprs == 1) {
4606 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004607 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4608 if (Literal.isInvalid())
4609 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004610 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004611 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004612 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4613 }
4614 else if (numExprs < numElems) {
4615 Diag(E->getExprLoc(),
4616 diag::err_incorrect_number_of_vector_initializers);
4617 return ExprError();
4618 }
4619 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004620 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004621 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004622 else {
4623 // For OpenCL, when the number of initializers is a single value,
4624 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004625 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004626 VTy->getVectorKind() == VectorType::GenericVector &&
4627 numExprs == 1) {
4628 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004629 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4630 if (Literal.isInvalid())
4631 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004632 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004633 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004634 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4635 }
4636
Benjamin Kramer14c59822012-02-14 12:06:21 +00004637 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004638 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004639 // FIXME: This means that pretty-printing the final AST will produce curly
4640 // braces instead of the original commas.
4641 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004642 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004643 initE->setType(Ty);
4644 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4645}
4646
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004647/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4648/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004649ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004650Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4651 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004652 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004653 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004654
John McCall60d7b3a2010-08-24 06:29:42 +00004655 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004656
Nate Begeman2ef13e52009-08-10 23:49:36 +00004657 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004658 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4659 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004660
John McCall9ae2f072010-08-23 23:25:46 +00004661 if (Result.isInvalid()) return ExprError();
4662
4663 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004664}
4665
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004666ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4667 SourceLocation R,
4668 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004669 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4670 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004671 return Owned(expr);
4672}
4673
Chandler Carruth82214a82011-02-18 23:54:50 +00004674/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004675/// constant and the other is not a pointer. Returns true if a diagnostic is
4676/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004677bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004678 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004679 Expr *NullExpr = LHSExpr;
4680 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004681 Expr::NullPointerConstantKind NullKind =
4682 NullExpr->isNullPointerConstant(Context,
4683 Expr::NPC_ValueDependentIsNotNull);
4684
4685 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004686 NullExpr = RHSExpr;
4687 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004688 NullKind =
4689 NullExpr->isNullPointerConstant(Context,
4690 Expr::NPC_ValueDependentIsNotNull);
4691 }
4692
4693 if (NullKind == Expr::NPCK_NotNull)
4694 return false;
4695
David Blaikie50800fc2012-08-08 17:33:31 +00004696 if (NullKind == Expr::NPCK_ZeroExpression)
4697 return false;
4698
4699 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004700 // In this case, check to make sure that we got here from a "NULL"
4701 // string in the source code.
4702 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004703 SourceLocation loc = NullExpr->getExprLoc();
4704 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004705 return false;
4706 }
4707
4708 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4709 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4710 << NonPointerExpr->getType() << DiagType
4711 << NonPointerExpr->getSourceRange();
4712 return true;
4713}
4714
Richard Trieu26f96072011-09-02 01:51:02 +00004715/// \brief Return false if the condition expression is valid, true otherwise.
4716static bool checkCondition(Sema &S, Expr *Cond) {
4717 QualType CondTy = Cond->getType();
4718
4719 // C99 6.5.15p2
4720 if (CondTy->isScalarType()) return false;
4721
4722 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004723 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004724 return false;
4725
4726 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004727 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004728 diag::err_typecheck_cond_expect_scalar :
4729 diag::err_typecheck_cond_expect_scalar_or_vector)
4730 << CondTy;
4731 return true;
4732}
4733
4734/// \brief Return false if the two expressions can be converted to a vector,
4735/// true otherwise
4736static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4737 ExprResult &RHS,
4738 QualType CondTy) {
4739 // Both operands should be of scalar type.
4740 if (!LHS.get()->getType()->isScalarType()) {
4741 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4742 << CondTy;
4743 return true;
4744 }
4745 if (!RHS.get()->getType()->isScalarType()) {
4746 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4747 << CondTy;
4748 return true;
4749 }
4750
4751 // Implicity convert these scalars to the type of the condition.
4752 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4753 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4754 return false;
4755}
4756
4757/// \brief Handle when one or both operands are void type.
4758static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4759 ExprResult &RHS) {
4760 Expr *LHSExpr = LHS.get();
4761 Expr *RHSExpr = RHS.get();
4762
4763 if (!LHSExpr->getType()->isVoidType())
4764 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4765 << RHSExpr->getSourceRange();
4766 if (!RHSExpr->getType()->isVoidType())
4767 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4768 << LHSExpr->getSourceRange();
4769 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4770 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4771 return S.Context.VoidTy;
4772}
4773
4774/// \brief Return false if the NullExpr can be promoted to PointerTy,
4775/// true otherwise.
4776static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4777 QualType PointerTy) {
4778 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4779 !NullExpr.get()->isNullPointerConstant(S.Context,
4780 Expr::NPC_ValueDependentIsNull))
4781 return true;
4782
4783 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4784 return false;
4785}
4786
4787/// \brief Checks compatibility between two pointers and return the resulting
4788/// type.
4789static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4790 ExprResult &RHS,
4791 SourceLocation Loc) {
4792 QualType LHSTy = LHS.get()->getType();
4793 QualType RHSTy = RHS.get()->getType();
4794
4795 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4796 // Two identical pointers types are always compatible.
4797 return LHSTy;
4798 }
4799
4800 QualType lhptee, rhptee;
4801
4802 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004803 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4804 lhptee = LHSBTy->getPointeeType();
4805 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004806 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004807 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4808 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004809 }
4810
Eli Friedmanae916a12012-04-05 22:30:04 +00004811 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4812 // differently qualified versions of compatible types, the result type is
4813 // a pointer to an appropriately qualified version of the composite
4814 // type.
4815
4816 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4817 // clause doesn't make sense for our extensions. E.g. address space 2 should
4818 // be incompatible with address space 3: they may live on different devices or
4819 // anything.
4820 Qualifiers lhQual = lhptee.getQualifiers();
4821 Qualifiers rhQual = rhptee.getQualifiers();
4822
4823 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4824 lhQual.removeCVRQualifiers();
4825 rhQual.removeCVRQualifiers();
4826
4827 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4828 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4829
4830 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4831
4832 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004833 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4834 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4835 << RHS.get()->getSourceRange();
4836 // In this situation, we assume void* type. No especially good
4837 // reason, but this is what gcc does, and we do have to pick
4838 // to get a consistent AST.
4839 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4840 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4841 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4842 return incompatTy;
4843 }
4844
4845 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004846 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4847 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004848
Eli Friedmanae916a12012-04-05 22:30:04 +00004849 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4850 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4851 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004852}
4853
4854/// \brief Return the resulting type when the operands are both block pointers.
4855static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4856 ExprResult &LHS,
4857 ExprResult &RHS,
4858 SourceLocation Loc) {
4859 QualType LHSTy = LHS.get()->getType();
4860 QualType RHSTy = RHS.get()->getType();
4861
4862 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4863 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4864 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4865 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4866 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4867 return destType;
4868 }
4869 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4870 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4871 << RHS.get()->getSourceRange();
4872 return QualType();
4873 }
4874
4875 // We have 2 block pointer types.
4876 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4877}
4878
4879/// \brief Return the resulting type when the operands are both pointers.
4880static QualType
4881checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4882 ExprResult &RHS,
4883 SourceLocation Loc) {
4884 // get the pointer types
4885 QualType LHSTy = LHS.get()->getType();
4886 QualType RHSTy = RHS.get()->getType();
4887
4888 // get the "pointed to" types
4889 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4890 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4891
4892 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4893 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4894 // Figure out necessary qualifiers (C99 6.5.15p6)
4895 QualType destPointee
4896 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4897 QualType destType = S.Context.getPointerType(destPointee);
4898 // Add qualifiers if necessary.
4899 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4900 // Promote to void*.
4901 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4902 return destType;
4903 }
4904 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4905 QualType destPointee
4906 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4907 QualType destType = S.Context.getPointerType(destPointee);
4908 // Add qualifiers if necessary.
4909 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4910 // Promote to void*.
4911 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4912 return destType;
4913 }
4914
4915 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4916}
4917
4918/// \brief Return false if the first expression is not an integer and the second
4919/// expression is not a pointer, true otherwise.
4920static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4921 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004922 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004923 if (!PointerExpr->getType()->isPointerType() ||
4924 !Int.get()->getType()->isIntegerType())
4925 return false;
4926
Richard Trieuccd891a2011-09-09 01:45:06 +00004927 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4928 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004929
4930 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4931 << Expr1->getType() << Expr2->getType()
4932 << Expr1->getSourceRange() << Expr2->getSourceRange();
4933 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4934 CK_IntegralToPointer);
4935 return true;
4936}
4937
Richard Trieu33fc7572011-09-06 20:06:39 +00004938/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4939/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004940/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004941QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4942 ExprResult &RHS, ExprValueKind &VK,
4943 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004944 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004945
Richard Trieu33fc7572011-09-06 20:06:39 +00004946 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4947 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004948 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004949
Richard Trieu33fc7572011-09-06 20:06:39 +00004950 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4951 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004952 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004953
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004954 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004955 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004956 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004957
4958 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004959 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004960
John Wiegley429bb272011-04-08 18:41:53 +00004961 Cond = UsualUnaryConversions(Cond.take());
4962 if (Cond.isInvalid())
4963 return QualType();
4964 LHS = UsualUnaryConversions(LHS.take());
4965 if (LHS.isInvalid())
4966 return QualType();
4967 RHS = UsualUnaryConversions(RHS.take());
4968 if (RHS.isInvalid())
4969 return QualType();
4970
4971 QualType CondTy = Cond.get()->getType();
4972 QualType LHSTy = LHS.get()->getType();
4973 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004974
Reid Spencer5f016e22007-07-11 17:01:13 +00004975 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004976 if (checkCondition(*this, Cond.get()))
4977 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004978
Chris Lattner70d67a92008-01-06 22:42:25 +00004979 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004980 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004981 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004982
Nate Begeman6155d732010-09-20 22:41:17 +00004983 // OpenCL: If the condition is a vector, and both operands are scalar,
4984 // attempt to implicity convert them to the vector type to act like the
4985 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004986 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004987 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004988 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004989
Chris Lattner70d67a92008-01-06 22:42:25 +00004990 // If both operands have arithmetic type, do the usual arithmetic conversions
4991 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004992 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4993 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004994 if (LHS.isInvalid() || RHS.isInvalid())
4995 return QualType();
4996 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004997 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004998
Chris Lattner70d67a92008-01-06 22:42:25 +00004999 // If both operands are the same structure or union type, the result is that
5000 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005001 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5002 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005003 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005004 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005005 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005006 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005007 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005008 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005009
Chris Lattner70d67a92008-01-06 22:42:25 +00005010 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005011 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005012 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005013 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005014 }
Richard Trieu26f96072011-09-02 01:51:02 +00005015
Steve Naroffb6d54e52008-01-08 01:11:38 +00005016 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5017 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005018 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5019 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005020
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005021 // All objective-c pointer type analysis is done here.
5022 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5023 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005024 if (LHS.isInvalid() || RHS.isInvalid())
5025 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005026 if (!compositeType.isNull())
5027 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005028
5029
Steve Naroff7154a772009-07-01 14:36:47 +00005030 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005031 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5032 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5033 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005034
Steve Naroff7154a772009-07-01 14:36:47 +00005035 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005036 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5037 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5038 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005039
John McCall404cd162010-11-13 01:35:44 +00005040 // GCC compatibility: soften pointer/integer mismatch. Note that
5041 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005042 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5043 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005044 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005045 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5046 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005047 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005048
Chandler Carruth82214a82011-02-18 23:54:50 +00005049 // Emit a better diagnostic if one of the expressions is a null pointer
5050 // constant and the other is not a pointer type. In this case, the user most
5051 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005052 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005053 return QualType();
5054
Chris Lattner70d67a92008-01-06 22:42:25 +00005055 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005056 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005057 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5058 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005059 return QualType();
5060}
5061
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005062/// FindCompositeObjCPointerType - Helper method to find composite type of
5063/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005064QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005065 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005066 QualType LHSTy = LHS.get()->getType();
5067 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005068
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005069 // Handle things like Class and struct objc_class*. Here we case the result
5070 // to the pseudo-builtin, because that will be implicitly cast back to the
5071 // redefinition type if an attempt is made to access its fields.
5072 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005073 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005074 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005075 return LHSTy;
5076 }
5077 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005078 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005079 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005080 return RHSTy;
5081 }
5082 // And the same for struct objc_object* / id
5083 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005084 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005085 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005086 return LHSTy;
5087 }
5088 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005089 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005090 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005091 return RHSTy;
5092 }
5093 // And the same for struct objc_selector* / SEL
5094 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005095 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005096 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005097 return LHSTy;
5098 }
5099 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005100 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005101 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005102 return RHSTy;
5103 }
5104 // Check constraints for Objective-C object pointers types.
5105 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005106
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005107 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5108 // Two identical object pointer types are always compatible.
5109 return LHSTy;
5110 }
John McCall1d9b3b22011-09-09 05:25:32 +00005111 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5112 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005113 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005114
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005115 // If both operands are interfaces and either operand can be
5116 // assigned to the other, use that type as the composite
5117 // type. This allows
5118 // xxx ? (A*) a : (B*) b
5119 // where B is a subclass of A.
5120 //
5121 // Additionally, as for assignment, if either type is 'id'
5122 // allow silent coercion. Finally, if the types are
5123 // incompatible then make sure to use 'id' as the composite
5124 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005125
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005126 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5127 // It could return the composite type.
5128 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5129 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5130 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5131 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5132 } else if ((LHSTy->isObjCQualifiedIdType() ||
5133 RHSTy->isObjCQualifiedIdType()) &&
5134 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5135 // Need to handle "id<xx>" explicitly.
5136 // GCC allows qualified id and any Objective-C type to devolve to
5137 // id. Currently localizing to here until clear this should be
5138 // part of ObjCQualifiedIdTypesAreCompatible.
5139 compositeType = Context.getObjCIdType();
5140 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5141 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005142 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005143 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5144 ;
5145 else {
5146 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5147 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005148 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005149 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005150 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5151 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005152 return incompatTy;
5153 }
5154 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005155 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5156 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005157 return compositeType;
5158 }
5159 // Check Objective-C object pointer types and 'void *'
5160 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005161 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005162 // ARC forbids the implicit conversion of object pointers to 'void *',
5163 // so these types are not compatible.
5164 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5166 LHS = RHS = true;
5167 return QualType();
5168 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005169 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5170 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5171 QualType destPointee
5172 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5173 QualType destType = Context.getPointerType(destPointee);
5174 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005175 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005176 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005177 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005178 return destType;
5179 }
5180 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005181 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005182 // ARC forbids the implicit conversion of object pointers to 'void *',
5183 // so these types are not compatible.
5184 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5185 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5186 LHS = RHS = true;
5187 return QualType();
5188 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005189 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5190 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5191 QualType destPointee
5192 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5193 QualType destType = Context.getPointerType(destPointee);
5194 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005195 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005196 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005197 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005198 return destType;
5199 }
5200 return QualType();
5201}
5202
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005203/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005204/// ParenRange in parentheses.
5205static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005206 const PartialDiagnostic &Note,
5207 SourceRange ParenRange) {
5208 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5209 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5210 EndLoc.isValid()) {
5211 Self.Diag(Loc, Note)
5212 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5213 << FixItHint::CreateInsertion(EndLoc, ")");
5214 } else {
5215 // We can't display the parentheses, so just show the bare note.
5216 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005217 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005218}
5219
5220static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5221 return Opc >= BO_Mul && Opc <= BO_Shr;
5222}
5223
Hans Wennborg2f072b42011-06-09 17:06:51 +00005224/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5225/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005226/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5227/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005228static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005229 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005230 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5231 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005232 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005233 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005234
5235 // Built-in binary operator.
5236 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5237 if (IsArithmeticOp(OP->getOpcode())) {
5238 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005239 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005240 return true;
5241 }
5242 }
5243
5244 // Overloaded operator.
5245 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5246 if (Call->getNumArgs() != 2)
5247 return false;
5248
5249 // Make sure this is really a binary operator that is safe to pass into
5250 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5251 OverloadedOperatorKind OO = Call->getOperator();
5252 if (OO < OO_Plus || OO > OO_Arrow)
5253 return false;
5254
5255 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5256 if (IsArithmeticOp(OpKind)) {
5257 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005258 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005259 return true;
5260 }
5261 }
5262
5263 return false;
5264}
5265
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005266static bool IsLogicOp(BinaryOperatorKind Opc) {
5267 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5268}
5269
Hans Wennborg2f072b42011-06-09 17:06:51 +00005270/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5271/// or is a logical expression such as (x==y) which has int type, but is
5272/// commonly interpreted as boolean.
5273static bool ExprLooksBoolean(Expr *E) {
5274 E = E->IgnoreParenImpCasts();
5275
5276 if (E->getType()->isBooleanType())
5277 return true;
5278 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5279 return IsLogicOp(OP->getOpcode());
5280 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5281 return OP->getOpcode() == UO_LNot;
5282
5283 return false;
5284}
5285
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005286/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5287/// and binary operator are mixed in a way that suggests the programmer assumed
5288/// the conditional operator has higher precedence, for example:
5289/// "int x = a + someBinaryCondition ? 1 : 2".
5290static void DiagnoseConditionalPrecedence(Sema &Self,
5291 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005292 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005293 Expr *LHSExpr,
5294 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005295 BinaryOperatorKind CondOpcode;
5296 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005297
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005298 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005299 return;
5300 if (!ExprLooksBoolean(CondRHS))
5301 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005302
Hans Wennborg2f072b42011-06-09 17:06:51 +00005303 // The condition is an arithmetic binary expression, with a right-
5304 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005305
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005306 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005307 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005308 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005309
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005310 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005311 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005312 << BinaryOperator::getOpcodeStr(CondOpcode),
5313 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005314
5315 SuggestParentheses(Self, OpLoc,
5316 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005317 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005318}
5319
Steve Narofff69936d2007-09-16 03:34:24 +00005320/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005321/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005322ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005323 SourceLocation ColonLoc,
5324 Expr *CondExpr, Expr *LHSExpr,
5325 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005326 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5327 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005328 OpaqueValueExpr *opaqueValue = 0;
5329 Expr *commonExpr = 0;
5330 if (LHSExpr == 0) {
5331 commonExpr = CondExpr;
5332
5333 // We usually want to apply unary conversions *before* saving, except
5334 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005335 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005336 && !commonExpr->isTypeDependent()
5337 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5338 && commonExpr->isGLValue()
5339 && commonExpr->isOrdinaryOrBitFieldObject()
5340 && RHSExpr->isOrdinaryOrBitFieldObject()
5341 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005342 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5343 if (commonRes.isInvalid())
5344 return ExprError();
5345 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005346 }
5347
5348 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5349 commonExpr->getType(),
5350 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005351 commonExpr->getObjectKind(),
5352 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005353 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005354 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005355
John McCallf89e55a2010-11-18 06:31:45 +00005356 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005357 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005358 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5359 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005360 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005361 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5362 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005363 return ExprError();
5364
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005365 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5366 RHS.get());
5367
John McCall56ca35d2011-02-17 10:25:35 +00005368 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005369 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5370 LHS.take(), ColonLoc,
5371 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005372
5373 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005374 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005375 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5376 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005377}
5378
John McCalle4be87e2011-01-31 23:13:11 +00005379// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005380// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005381// routine is it effectively iqnores the qualifiers on the top level pointee.
5382// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5383// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005384static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005385checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5386 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5387 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005388
Reid Spencer5f016e22007-07-11 17:01:13 +00005389 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005390 const Type *lhptee, *rhptee;
5391 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005392 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5393 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005394
John McCalle4be87e2011-01-31 23:13:11 +00005395 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005396
5397 // C99 6.5.16.1p1: This following citation is common to constraints
5398 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5399 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005400 Qualifiers lq;
5401
John McCallf85e1932011-06-15 23:02:42 +00005402 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5403 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5404 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5405 // Ignore lifetime for further calculation.
5406 lhq.removeObjCLifetime();
5407 rhq.removeObjCLifetime();
5408 }
5409
John McCall86c05f32011-02-01 00:10:29 +00005410 if (!lhq.compatiblyIncludes(rhq)) {
5411 // Treat address-space mismatches as fatal. TODO: address subspaces
5412 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5413 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5414
John McCallf85e1932011-06-15 23:02:42 +00005415 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005416 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005417 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005418 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005419 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005420 && (lhptee->isVoidType() || rhptee->isVoidType()))
5421 ; // keep old
5422
John McCallf85e1932011-06-15 23:02:42 +00005423 // Treat lifetime mismatches as fatal.
5424 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5425 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5426
John McCall86c05f32011-02-01 00:10:29 +00005427 // For GCC compatibility, other qualifier mismatches are treated
5428 // as still compatible in C.
5429 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005431
Mike Stumpeed9cac2009-02-19 03:04:26 +00005432 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5433 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005434 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005435 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005436 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005437 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005438
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005439 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005440 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005441 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005442 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005443
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005444 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005445 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005446 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005447
5448 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005449 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005450 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005451 }
John McCall86c05f32011-02-01 00:10:29 +00005452
Mike Stumpeed9cac2009-02-19 03:04:26 +00005453 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005454 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005455 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5456 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005457 // Check if the pointee types are compatible ignoring the sign.
5458 // We explicitly check for char so that we catch "char" vs
5459 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005460 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005461 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005462 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005463 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005464
Chris Lattner6a2b9262009-10-17 20:33:28 +00005465 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005466 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005467 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005468 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005469
John McCall86c05f32011-02-01 00:10:29 +00005470 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005471 // Types are compatible ignoring the sign. Qualifier incompatibility
5472 // takes priority over sign incompatibility because the sign
5473 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005474 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005475 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005476
John McCalle4be87e2011-01-31 23:13:11 +00005477 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005478 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005479
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005480 // If we are a multi-level pointer, it's possible that our issue is simply
5481 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5482 // the eventual target type is the same and the pointers have the same
5483 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005484 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005485 do {
John McCall86c05f32011-02-01 00:10:29 +00005486 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5487 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005488 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005489
John McCall86c05f32011-02-01 00:10:29 +00005490 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005491 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005492 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005493
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005494 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005495 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005496 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005497 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005498 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5499 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005500 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005501}
5502
John McCalle4be87e2011-01-31 23:13:11 +00005503/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005504/// block pointer types are compatible or whether a block and normal pointer
5505/// are compatible. It is more restrict than comparing two function pointer
5506// types.
John McCalle4be87e2011-01-31 23:13:11 +00005507static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005508checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5509 QualType RHSType) {
5510 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5511 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005512
Steve Naroff1c7d0672008-09-04 15:10:53 +00005513 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005514
Steve Naroff1c7d0672008-09-04 15:10:53 +00005515 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005516 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5517 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005518
John McCalle4be87e2011-01-31 23:13:11 +00005519 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005520 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005521 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005522
John McCalle4be87e2011-01-31 23:13:11 +00005523 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524
Steve Naroff1c7d0672008-09-04 15:10:53 +00005525 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005526 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5527 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005528
Richard Trieu1da27a12011-09-06 20:21:22 +00005529 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005530 return Sema::IncompatibleBlockPointer;
5531
Steve Naroff1c7d0672008-09-04 15:10:53 +00005532 return ConvTy;
5533}
5534
John McCalle4be87e2011-01-31 23:13:11 +00005535/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005536/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005537static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005538checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5539 QualType RHSType) {
5540 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5541 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005542
Richard Trieu1da27a12011-09-06 20:21:22 +00005543 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005544 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005545 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5546 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005547 return Sema::IncompatiblePointer;
5548 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005549 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005550 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005551 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5552 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005553 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005554 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005555 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005556 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5557 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005558
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005559 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5560 // make an exception for id<P>
5561 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005562 return Sema::CompatiblePointerDiscardsQualifiers;
5563
Richard Trieu1da27a12011-09-06 20:21:22 +00005564 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005565 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005566 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005567 return Sema::IncompatibleObjCQualifiedId;
5568 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005569}
5570
John McCall1c23e912010-11-16 02:32:08 +00005571Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005572Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005573 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005574 // Fake up an opaque expression. We don't actually care about what
5575 // cast operations are required, so if CheckAssignmentConstraints
5576 // adds casts to this they'll be wasted, but fortunately that doesn't
5577 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005578 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5579 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005580 CastKind K = CK_Invalid;
5581
Richard Trieu1da27a12011-09-06 20:21:22 +00005582 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005583}
5584
Mike Stumpeed9cac2009-02-19 03:04:26 +00005585/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5586/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005587/// pointers. Here are some objectionable examples that GCC considers warnings:
5588///
5589/// int a, *pint;
5590/// short *pshort;
5591/// struct foo *pfoo;
5592///
5593/// pint = pshort; // warning: assignment from incompatible pointer type
5594/// a = pint; // warning: assignment makes integer from pointer without a cast
5595/// pint = a; // warning: assignment makes pointer from integer without a cast
5596/// pint = pfoo; // warning: assignment from incompatible pointer type
5597///
5598/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005599/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005600///
John McCalldaa8e4e2010-11-15 09:13:47 +00005601/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005602Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005603Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005604 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005605 QualType RHSType = RHS.get()->getType();
5606 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005607
Chris Lattnerfc144e22008-01-04 23:18:45 +00005608 // Get canonical types. We're not formatting these types, just comparing
5609 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005610 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5611 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005612
Eli Friedmanb001de72011-10-06 23:00:33 +00005613
John McCallb6cfa242011-01-31 22:28:28 +00005614 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005615 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005616 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005617 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005618 }
5619
Eli Friedman860a3192012-06-16 02:19:17 +00005620 // If we have an atomic type, try a non-atomic assignment, then just add an
5621 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005622 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005623 Sema::AssignConvertType result =
5624 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5625 if (result != Compatible)
5626 return result;
5627 if (Kind != CK_NoOp)
5628 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5629 Kind = CK_NonAtomicToAtomic;
5630 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005631 }
5632
Douglas Gregor9d293df2008-10-28 00:22:11 +00005633 // If the left-hand side is a reference type, then we are in a
5634 // (rare!) case where we've allowed the use of references in C,
5635 // e.g., as a parameter type in a built-in function. In this case,
5636 // just make sure that the type referenced is compatible with the
5637 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005638 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005639 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005640 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5641 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005642 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005643 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005644 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005645 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005646 }
John McCallb6cfa242011-01-31 22:28:28 +00005647
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005648 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5649 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005650 if (LHSType->isExtVectorType()) {
5651 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005652 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005653 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005654 // CK_VectorSplat does T -> vector T, so first cast to the
5655 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005656 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5657 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005658 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005659 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005660 }
5661 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005662 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005663 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005664 }
Mike Stump1eb44332009-09-09 15:08:12 +00005665
John McCallb6cfa242011-01-31 22:28:28 +00005666 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005667 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5668 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005669 // Allow assignments of an AltiVec vector type to an equivalent GCC
5670 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005671 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005672 Kind = CK_BitCast;
5673 return Compatible;
5674 }
5675
Douglas Gregor255210e2010-08-06 10:14:59 +00005676 // If we are allowing lax vector conversions, and LHS and RHS are both
5677 // vectors, the total size only needs to be the same. This is a bitcast;
5678 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005679 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005680 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005681 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005682 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005683 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005684 }
5685 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005687
John McCallb6cfa242011-01-31 22:28:28 +00005688 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005689 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005690 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005691 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005692 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005693 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005694
John McCallb6cfa242011-01-31 22:28:28 +00005695 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005696 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005697 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005698 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005699 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005700 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005701 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005702
John McCallb6cfa242011-01-31 22:28:28 +00005703 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005704 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005705 Kind = CK_IntegralToPointer; // FIXME: null?
5706 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005707 }
John McCallb6cfa242011-01-31 22:28:28 +00005708
5709 // C pointers are not compatible with ObjC object pointers,
5710 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005711 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005712 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005713 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005714 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005715 return Compatible;
5716 }
5717
5718 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005719 if (RHSType->isObjCClassType() &&
5720 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005721 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005722 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005723 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005724 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005725
John McCallb6cfa242011-01-31 22:28:28 +00005726 Kind = CK_BitCast;
5727 return IncompatiblePointer;
5728 }
5729
5730 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005731 if (RHSType->getAs<BlockPointerType>()) {
5732 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005733 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005734 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005735 }
Steve Naroffb4406862008-09-29 18:10:17 +00005736 }
John McCallb6cfa242011-01-31 22:28:28 +00005737
Steve Naroff1c7d0672008-09-04 15:10:53 +00005738 return Incompatible;
5739 }
5740
John McCallb6cfa242011-01-31 22:28:28 +00005741 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005743 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005744 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005745 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005746 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005747 }
5748
5749 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005750 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005751 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005752 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005753 }
5754
John McCallb6cfa242011-01-31 22:28:28 +00005755 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005756 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005757 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005758 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005759 }
Steve Naroffb4406862008-09-29 18:10:17 +00005760
John McCallb6cfa242011-01-31 22:28:28 +00005761 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005762 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005763 if (RHSPT->getPointeeType()->isVoidType()) {
5764 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005765 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005766 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005767
Chris Lattnerfc144e22008-01-04 23:18:45 +00005768 return Incompatible;
5769 }
5770
John McCallb6cfa242011-01-31 22:28:28 +00005771 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005772 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005773 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005774 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005775 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005776 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005777 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005778 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005779 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005780 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005781 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005782 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005783 }
5784
5785 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005786 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005787 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005788 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005789 }
5790
John McCallb6cfa242011-01-31 22:28:28 +00005791 // In general, C pointers are not compatible with ObjC object pointers,
5792 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005793 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005794 Kind = CK_CPointerToObjCPointerCast;
5795
John McCallb6cfa242011-01-31 22:28:28 +00005796 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005797 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005798 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005799 }
5800
5801 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005802 if (LHSType->isObjCClassType() &&
5803 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005804 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005805 return Compatible;
5806 }
5807
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005808 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005809 }
John McCallb6cfa242011-01-31 22:28:28 +00005810
5811 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005812 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005813 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005814 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005815 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005816 }
5817
Steve Naroff14108da2009-07-10 23:34:53 +00005818 return Incompatible;
5819 }
John McCallb6cfa242011-01-31 22:28:28 +00005820
5821 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005822 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005823 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005824 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005825 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005826 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005827 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005828
John McCallb6cfa242011-01-31 22:28:28 +00005829 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005830 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005831 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005832 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005833 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005834
Chris Lattnerfc144e22008-01-04 23:18:45 +00005835 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005836 }
John McCallb6cfa242011-01-31 22:28:28 +00005837
5838 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005839 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005840 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005841 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005842 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005843 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005844 }
Steve Naroff14108da2009-07-10 23:34:53 +00005845
John McCallb6cfa242011-01-31 22:28:28 +00005846 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005847 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005848 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005849 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005850 }
5851
Steve Naroff14108da2009-07-10 23:34:53 +00005852 return Incompatible;
5853 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005854
John McCallb6cfa242011-01-31 22:28:28 +00005855 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005856 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5857 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005858 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005859 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005860 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005861 }
John McCallb6cfa242011-01-31 22:28:28 +00005862
Reid Spencer5f016e22007-07-11 17:01:13 +00005863 return Incompatible;
5864}
5865
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005866/// \brief Constructs a transparent union from an expression that is
5867/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005868static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5869 ExprResult &EResult, QualType UnionType,
5870 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005871 // Build an initializer list that designates the appropriate member
5872 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005873 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005874 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005875 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005876 Initializer->setType(UnionType);
5877 Initializer->setInitializedFieldInUnion(Field);
5878
5879 // Build a compound literal constructing a value of the transparent
5880 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005881 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005882 EResult = S.Owned(
5883 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5884 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005885}
5886
5887Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005888Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005889 ExprResult &RHS) {
5890 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005891
Mike Stump1eb44332009-09-09 15:08:12 +00005892 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005893 // transparent_union GCC extension.
5894 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005895 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005896 return Incompatible;
5897
5898 // The field to initialize within the transparent union.
5899 RecordDecl *UD = UT->getDecl();
5900 FieldDecl *InitField = 0;
5901 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005902 for (RecordDecl::field_iterator it = UD->field_begin(),
5903 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005904 it != itend; ++it) {
5905 if (it->getType()->isPointerType()) {
5906 // If the transparent union contains a pointer type, we allow:
5907 // 1) void pointer
5908 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005909 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005910 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005911 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005912 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005913 break;
5914 }
Mike Stump1eb44332009-09-09 15:08:12 +00005915
Richard Trieuf7720da2011-09-06 20:40:12 +00005916 if (RHS.get()->isNullPointerConstant(Context,
5917 Expr::NPC_ValueDependentIsNull)) {
5918 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5919 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005920 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005921 break;
5922 }
5923 }
5924
John McCalldaa8e4e2010-11-15 09:13:47 +00005925 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005926 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005927 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005928 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005929 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005930 break;
5931 }
5932 }
5933
5934 if (!InitField)
5935 return Incompatible;
5936
Richard Trieuf7720da2011-09-06 20:40:12 +00005937 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005938 return Compatible;
5939}
5940
Chris Lattner5cf216b2008-01-04 18:04:52 +00005941Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005942Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5943 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005944 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005945 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005946 // C++ 5.17p3: If the left operand is not of class type, the
5947 // expression is implicitly converted (C++ 4) to the
5948 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005949 ExprResult Res;
5950 if (Diagnose) {
5951 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5952 AA_Assigning);
5953 } else {
5954 ImplicitConversionSequence ICS =
5955 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5956 /*SuppressUserConversions=*/false,
5957 /*AllowExplicit=*/false,
5958 /*InOverloadResolution=*/false,
5959 /*CStyle=*/false,
5960 /*AllowObjCWritebackConversion=*/false);
5961 if (ICS.isFailure())
5962 return Incompatible;
5963 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5964 ICS, AA_Assigning);
5965 }
John Wiegley429bb272011-04-08 18:41:53 +00005966 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005967 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005968 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005969 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005970 !CheckObjCARCUnavailableWeakConversion(LHSType,
5971 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005972 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005973 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005974 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005975 }
5976
5977 // FIXME: Currently, we fall through and treat C++ classes like C
5978 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005979 // FIXME: We also fall through for atomics; not sure what should
5980 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005981 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005982
Steve Naroff529a4ad2007-11-27 17:58:44 +00005983 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5984 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005985 if ((LHSType->isPointerType() ||
5986 LHSType->isObjCObjectPointerType() ||
5987 LHSType->isBlockPointerType())
5988 && RHS.get()->isNullPointerConstant(Context,
5989 Expr::NPC_ValueDependentIsNull)) {
5990 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005991 return Compatible;
5992 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005993
Chris Lattner943140e2007-10-16 02:55:40 +00005994 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005995 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005996 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005997 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005998 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005999 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006000 if (!LHSType->isReferenceType()) {
6001 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6002 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006003 return Incompatible;
6004 }
Steve Narofff1120de2007-08-24 22:33:52 +00006005
John McCalldaa8e4e2010-11-15 09:13:47 +00006006 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006007 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006008 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006009
Steve Narofff1120de2007-08-24 22:33:52 +00006010 // C99 6.5.16.1p2: The value of the right operand is converted to the
6011 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006012 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6013 // so that we can use references in built-in functions even in C.
6014 // The getNonReferenceType() call makes sure that the resulting expression
6015 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006016 if (result != Incompatible && RHS.get()->getType() != LHSType)
6017 RHS = ImpCastExprToType(RHS.take(),
6018 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006019 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006020}
6021
Richard Trieuf7720da2011-09-06 20:40:12 +00006022QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6023 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006024 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006025 << LHS.get()->getType() << RHS.get()->getType()
6026 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006027 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006028}
6029
Richard Trieu08062aa2011-09-06 21:01:04 +00006030QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006031 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006032 if (!IsCompAssign) {
6033 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6034 if (LHS.isInvalid())
6035 return QualType();
6036 }
6037 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6038 if (RHS.isInvalid())
6039 return QualType();
6040
Mike Stumpeed9cac2009-02-19 03:04:26 +00006041 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006042 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006043 QualType LHSType =
6044 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6045 QualType RHSType =
6046 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006047
Nate Begemanbe2341d2008-07-14 18:02:46 +00006048 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006049 if (LHSType == RHSType)
6050 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006051
Douglas Gregor255210e2010-08-06 10:14:59 +00006052 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006053 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6054 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6055 if (LHSType->isExtVectorType()) {
6056 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6057 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006058 }
6059
Richard Trieuccd891a2011-09-09 01:45:06 +00006060 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006061 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6062 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006063 }
6064
David Blaikie4e4d0842012-03-11 07:00:24 +00006065 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006066 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006067 // If we are allowing lax vector conversions, and LHS and RHS are both
6068 // vectors, the total size only needs to be the same. This is a
6069 // bitcast; no bits are changed but the result type is different.
6070 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006071 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6072 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006073 }
6074
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006075 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6076 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6077 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006078 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006079 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006080 std::swap(RHS, LHS);
6081 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006082 }
Mike Stump1eb44332009-09-09 15:08:12 +00006083
Nate Begemandde25982009-06-28 19:12:57 +00006084 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006085 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006086 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006087 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6088 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006089 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006090 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006091 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006092 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6093 if (swapped) std::swap(RHS, LHS);
6094 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006095 }
6096 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006097 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6098 RHSType->isRealFloatingType()) {
6099 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006100 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006101 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006102 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006103 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6104 if (swapped) std::swap(RHS, LHS);
6105 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006106 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006107 }
6108 }
Mike Stump1eb44332009-09-09 15:08:12 +00006109
Nate Begemandde25982009-06-28 19:12:57 +00006110 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006111 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006112 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006113 << LHS.get()->getType() << RHS.get()->getType()
6114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006115 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006116}
6117
Richard Trieu481037f2011-09-16 00:53:10 +00006118// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6119// expression. These are mainly cases where the null pointer is used as an
6120// integer instead of a pointer.
6121static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6122 SourceLocation Loc, bool IsCompare) {
6123 // The canonical way to check for a GNU null is with isNullPointerConstant,
6124 // but we use a bit of a hack here for speed; this is a relatively
6125 // hot path, and isNullPointerConstant is slow.
6126 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6127 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6128
6129 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6130
6131 // Avoid analyzing cases where the result will either be invalid (and
6132 // diagnosed as such) or entirely valid and not something to warn about.
6133 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6134 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6135 return;
6136
6137 // Comparison operations would not make sense with a null pointer no matter
6138 // what the other expression is.
6139 if (!IsCompare) {
6140 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6141 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6142 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6143 return;
6144 }
6145
6146 // The rest of the operations only make sense with a null pointer
6147 // if the other expression is a pointer.
6148 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6149 NonNullType->canDecayToPointerType())
6150 return;
6151
6152 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6153 << LHSNull /* LHS is NULL */ << NonNullType
6154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6155}
6156
Richard Trieu08062aa2011-09-06 21:01:04 +00006157QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006158 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006159 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006160 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6161
Richard Trieu08062aa2011-09-06 21:01:04 +00006162 if (LHS.get()->getType()->isVectorType() ||
6163 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006164 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006165
Richard Trieuccd891a2011-09-09 01:45:06 +00006166 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006167 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006168 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006169
David Chisnall7a7ee302012-01-16 17:27:18 +00006170
Eli Friedman860a3192012-06-16 02:19:17 +00006171 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006172 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006173
Chris Lattner7ef655a2010-01-12 21:23:57 +00006174 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006175 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006176 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006177 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006178 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6179 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006180
Chris Lattner7ef655a2010-01-12 21:23:57 +00006181 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006182}
6183
Chris Lattner7ef655a2010-01-12 21:23:57 +00006184QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006185 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006186 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6187
Richard Trieu08062aa2011-09-06 21:01:04 +00006188 if (LHS.get()->getType()->isVectorType() ||
6189 RHS.get()->getType()->isVectorType()) {
6190 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6191 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006192 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006193 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006194 }
Steve Naroff90045e82007-07-13 23:32:42 +00006195
Richard Trieuccd891a2011-09-09 01:45:06 +00006196 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006197 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006198 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006199
Eli Friedman860a3192012-06-16 02:19:17 +00006200 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006201 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006202
Chris Lattner7ef655a2010-01-12 21:23:57 +00006203 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006204 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006205 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006206 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6207 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006208
Chris Lattner7ef655a2010-01-12 21:23:57 +00006209 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006210}
6211
Chandler Carruth13b21be2011-06-27 08:02:19 +00006212/// \brief Diagnose invalid arithmetic on two void pointers.
6213static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006214 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006215 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006216 ? diag::err_typecheck_pointer_arith_void_type
6217 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006218 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6219 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006220}
6221
6222/// \brief Diagnose invalid arithmetic on a void pointer.
6223static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6224 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006225 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006226 ? diag::err_typecheck_pointer_arith_void_type
6227 : diag::ext_gnu_void_ptr)
6228 << 0 /* one pointer */ << Pointer->getSourceRange();
6229}
6230
6231/// \brief Diagnose invalid arithmetic on two function pointers.
6232static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6233 Expr *LHS, Expr *RHS) {
6234 assert(LHS->getType()->isAnyPointerType());
6235 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006236 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006237 ? diag::err_typecheck_pointer_arith_function_type
6238 : diag::ext_gnu_ptr_func_arith)
6239 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6240 // We only show the second type if it differs from the first.
6241 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6242 RHS->getType())
6243 << RHS->getType()->getPointeeType()
6244 << LHS->getSourceRange() << RHS->getSourceRange();
6245}
6246
6247/// \brief Diagnose invalid arithmetic on a function pointer.
6248static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6249 Expr *Pointer) {
6250 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006251 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006252 ? diag::err_typecheck_pointer_arith_function_type
6253 : diag::ext_gnu_ptr_func_arith)
6254 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6255 << 0 /* one pointer, so only one type */
6256 << Pointer->getSourceRange();
6257}
6258
Richard Trieud9f19342011-09-12 18:08:02 +00006259/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006260///
6261/// \returns True if pointer has incomplete type
6262static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6263 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006264 assert(Operand->getType()->isAnyPointerType() &&
6265 !Operand->getType()->isDependentType());
6266 QualType PointeeTy = Operand->getType()->getPointeeType();
6267 return S.RequireCompleteType(Loc, PointeeTy,
6268 diag::err_typecheck_arithmetic_incomplete_type,
6269 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006270}
6271
Chandler Carruth13b21be2011-06-27 08:02:19 +00006272/// \brief Check the validity of an arithmetic pointer operand.
6273///
6274/// If the operand has pointer type, this code will check for pointer types
6275/// which are invalid in arithmetic operations. These will be diagnosed
6276/// appropriately, including whether or not the use is supported as an
6277/// extension.
6278///
6279/// \returns True when the operand is valid to use (even if as an extension).
6280static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6281 Expr *Operand) {
6282 if (!Operand->getType()->isAnyPointerType()) return true;
6283
6284 QualType PointeeTy = Operand->getType()->getPointeeType();
6285 if (PointeeTy->isVoidType()) {
6286 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006287 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006288 }
6289 if (PointeeTy->isFunctionType()) {
6290 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006291 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006292 }
6293
Richard Trieu097ecd22011-09-02 02:15:37 +00006294 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006295
6296 return true;
6297}
6298
6299/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6300/// operands.
6301///
6302/// This routine will diagnose any invalid arithmetic on pointer operands much
6303/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6304/// for emitting a single diagnostic even for operations where both LHS and RHS
6305/// are (potentially problematic) pointers.
6306///
6307/// \returns True when the operand is valid to use (even if as an extension).
6308static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006309 Expr *LHSExpr, Expr *RHSExpr) {
6310 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6311 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006312 if (!isLHSPointer && !isRHSPointer) return true;
6313
6314 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006315 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6316 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006317
6318 // Check for arithmetic on pointers to incomplete types.
6319 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6320 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6321 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006322 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6323 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6324 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006325
David Blaikie4e4d0842012-03-11 07:00:24 +00006326 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006327 }
6328
6329 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6330 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6331 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006332 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6333 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6334 RHSExpr);
6335 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006336
David Blaikie4e4d0842012-03-11 07:00:24 +00006337 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006338 }
6339
John McCall1503f0d2012-07-31 05:14:30 +00006340 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6341 return false;
6342 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6343 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006344
Chandler Carruth13b21be2011-06-27 08:02:19 +00006345 return true;
6346}
6347
Nico Weber1cb2d742012-03-02 22:01:22 +00006348/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6349/// literal.
6350static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6351 Expr *LHSExpr, Expr *RHSExpr) {
6352 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6353 Expr* IndexExpr = RHSExpr;
6354 if (!StrExpr) {
6355 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6356 IndexExpr = LHSExpr;
6357 }
6358
6359 bool IsStringPlusInt = StrExpr &&
6360 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6361 if (!IsStringPlusInt)
6362 return;
6363
6364 llvm::APSInt index;
6365 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6366 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6367 if (index.isNonNegative() &&
6368 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6369 index.isUnsigned()))
6370 return;
6371 }
6372
6373 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6374 Self.Diag(OpLoc, diag::warn_string_plus_int)
6375 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6376
6377 // Only print a fixit for "str" + int, not for int + "str".
6378 if (IndexExpr == RHSExpr) {
6379 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6380 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6381 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6382 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6383 << FixItHint::CreateInsertion(EndLoc, "]");
6384 } else
6385 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6386}
6387
Richard Trieud9f19342011-09-12 18:08:02 +00006388/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006389static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006390 Expr *LHSExpr, Expr *RHSExpr) {
6391 assert(LHSExpr->getType()->isAnyPointerType());
6392 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006393 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006394 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6395 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006396}
6397
Chris Lattner7ef655a2010-01-12 21:23:57 +00006398QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006399 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6400 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006401 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6402
Richard Trieudef75842011-09-06 21:13:51 +00006403 if (LHS.get()->getType()->isVectorType() ||
6404 RHS.get()->getType()->isVectorType()) {
6405 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006406 if (CompLHSTy) *CompLHSTy = compType;
6407 return compType;
6408 }
Steve Naroff49b45262007-07-13 16:58:59 +00006409
Richard Trieudef75842011-09-06 21:13:51 +00006410 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6411 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006412 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006413
Nico Weber1cb2d742012-03-02 22:01:22 +00006414 // Diagnose "string literal" '+' int.
6415 if (Opc == BO_Add)
6416 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6417
Reid Spencer5f016e22007-07-11 17:01:13 +00006418 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006419 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006420 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006421 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006423
John McCall1503f0d2012-07-31 05:14:30 +00006424 // Type-checking. Ultimately the pointer's going to be in PExp;
6425 // note that we bias towards the LHS being the pointer.
6426 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006427
John McCall1503f0d2012-07-31 05:14:30 +00006428 bool isObjCPointer;
6429 if (PExp->getType()->isPointerType()) {
6430 isObjCPointer = false;
6431 } else if (PExp->getType()->isObjCObjectPointerType()) {
6432 isObjCPointer = true;
6433 } else {
6434 std::swap(PExp, IExp);
6435 if (PExp->getType()->isPointerType()) {
6436 isObjCPointer = false;
6437 } else if (PExp->getType()->isObjCObjectPointerType()) {
6438 isObjCPointer = true;
6439 } else {
6440 return InvalidOperands(Loc, LHS, RHS);
6441 }
6442 }
6443 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006444
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006445 if (!IExp->getType()->isIntegerType())
6446 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006447
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006448 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6449 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006450
John McCall1503f0d2012-07-31 05:14:30 +00006451 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006452 return QualType();
6453
6454 // Check array bounds for pointer arithemtic
6455 CheckArrayAccess(PExp, IExp);
6456
6457 if (CompLHSTy) {
6458 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6459 if (LHSTy.isNull()) {
6460 LHSTy = LHS.get()->getType();
6461 if (LHSTy->isPromotableIntegerType())
6462 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006463 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006464 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006465 }
6466
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006467 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006468}
6469
Chris Lattnereca7be62008-04-07 05:30:13 +00006470// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006471QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006472 SourceLocation Loc,
6473 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006474 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6475
Richard Trieudef75842011-09-06 21:13:51 +00006476 if (LHS.get()->getType()->isVectorType() ||
6477 RHS.get()->getType()->isVectorType()) {
6478 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006479 if (CompLHSTy) *CompLHSTy = compType;
6480 return compType;
6481 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006482
Richard Trieudef75842011-09-06 21:13:51 +00006483 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6484 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006485 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006486
Chris Lattner6e4ab612007-12-09 21:53:25 +00006487 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006488
Chris Lattner6e4ab612007-12-09 21:53:25 +00006489 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006490 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006491 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006492 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006493 }
Mike Stump1eb44332009-09-09 15:08:12 +00006494
Chris Lattner6e4ab612007-12-09 21:53:25 +00006495 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006496 if (LHS.get()->getType()->isAnyPointerType()) {
6497 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006498
Chris Lattnerb5f15622009-04-24 23:50:08 +00006499 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006500 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6501 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006502 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006503
Chris Lattner6e4ab612007-12-09 21:53:25 +00006504 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006505 if (RHS.get()->getType()->isIntegerType()) {
6506 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006507 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006508
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006509 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006510 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6511 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006512
Richard Trieudef75842011-09-06 21:13:51 +00006513 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6514 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006515 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006516
Chris Lattner6e4ab612007-12-09 21:53:25 +00006517 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006518 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006519 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006520 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006521
David Blaikie4e4d0842012-03-11 07:00:24 +00006522 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006523 // Pointee types must be the same: C++ [expr.add]
6524 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006525 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006526 }
6527 } else {
6528 // Pointee types must be compatible C99 6.5.6p3
6529 if (!Context.typesAreCompatible(
6530 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6531 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006532 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006533 return QualType();
6534 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006535 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006536
Chandler Carruth13b21be2011-06-27 08:02:19 +00006537 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006538 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006539 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006540
Richard Trieudef75842011-09-06 21:13:51 +00006541 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006542 return Context.getPointerDiffType();
6543 }
6544 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006545
Richard Trieudef75842011-09-06 21:13:51 +00006546 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006547}
6548
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006549static bool isScopedEnumerationType(QualType T) {
6550 if (const EnumType *ET = dyn_cast<EnumType>(T))
6551 return ET->getDecl()->isScoped();
6552 return false;
6553}
6554
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006555static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006556 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006557 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006558 llvm::APSInt Right;
6559 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006560 if (RHS.get()->isValueDependent() ||
6561 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006562 return;
6563
6564 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006565 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006566 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006567 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006568 return;
6569 }
6570 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006571 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006572 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006573 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006574 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006575 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006576 return;
6577 }
6578 if (Opc != BO_Shl)
6579 return;
6580
6581 // When left shifting an ICE which is signed, we can check for overflow which
6582 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6583 // integers have defined behavior modulo one more than the maximum value
6584 // representable in the result type, so never warn for those.
6585 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006586 if (LHS.get()->isValueDependent() ||
6587 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6588 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006589 return;
6590 llvm::APInt ResultBits =
6591 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6592 if (LeftBits.uge(ResultBits))
6593 return;
6594 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6595 Result = Result.shl(Right);
6596
Ted Kremenekfa821382011-06-15 00:54:52 +00006597 // Print the bit representation of the signed integer as an unsigned
6598 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006599 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006600 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6601
Chandler Carruth21206d52011-02-23 23:34:11 +00006602 // If we are only missing a sign bit, this is less likely to result in actual
6603 // bugs -- if the result is cast back to an unsigned type, it will have the
6604 // expected value. Thus we place this behind a different warning that can be
6605 // turned off separately if needed.
6606 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006607 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006608 << HexResult.str() << LHSType
6609 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006610 return;
6611 }
6612
6613 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006614 << HexResult.str() << Result.getMinSignedBits() << LHSType
6615 << Left.getBitWidth() << LHS.get()->getSourceRange()
6616 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006617}
6618
Chris Lattnereca7be62008-04-07 05:30:13 +00006619// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006620QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006621 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006622 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006623 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6624
Chris Lattnerca5eede2007-12-12 05:47:28 +00006625 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006626 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6627 !RHS.get()->getType()->hasIntegerRepresentation())
6628 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006629
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006630 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6631 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006632 if (isScopedEnumerationType(LHS.get()->getType()) ||
6633 isScopedEnumerationType(RHS.get()->getType())) {
6634 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006635 }
6636
Nate Begeman2207d792009-10-25 02:26:48 +00006637 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006638 if (LHS.get()->getType()->isVectorType() ||
6639 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006640 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006641
Chris Lattnerca5eede2007-12-12 05:47:28 +00006642 // Shifts don't perform usual arithmetic conversions, they just do integer
6643 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006644
John McCall1bc80af2010-12-16 19:28:59 +00006645 // For the LHS, do usual unary conversions, but then reset them away
6646 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006647 ExprResult OldLHS = LHS;
6648 LHS = UsualUnaryConversions(LHS.take());
6649 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006650 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006651 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006652 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006653
6654 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006655 RHS = UsualUnaryConversions(RHS.take());
6656 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006657 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006658
Ryan Flynnd0439682009-08-07 16:20:20 +00006659 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006660 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006661
Chris Lattnerca5eede2007-12-12 05:47:28 +00006662 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006663 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006664}
6665
Chandler Carruth99919472010-07-10 12:30:03 +00006666static bool IsWithinTemplateSpecialization(Decl *D) {
6667 if (DeclContext *DC = D->getDeclContext()) {
6668 if (isa<ClassTemplateSpecializationDecl>(DC))
6669 return true;
6670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6671 return FD->isFunctionTemplateSpecialization();
6672 }
6673 return false;
6674}
6675
Richard Trieue648ac32011-09-02 03:48:46 +00006676/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006677static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6678 ExprResult &RHS) {
6679 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6680 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006681
6682 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6683 if (!LHSEnumType)
6684 return;
6685 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6686 if (!RHSEnumType)
6687 return;
6688
6689 // Ignore anonymous enums.
6690 if (!LHSEnumType->getDecl()->getIdentifier())
6691 return;
6692 if (!RHSEnumType->getDecl()->getIdentifier())
6693 return;
6694
6695 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6696 return;
6697
6698 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6699 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006700 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006701}
6702
Richard Trieu7be1be02011-09-02 02:55:45 +00006703/// \brief Diagnose bad pointer comparisons.
6704static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006705 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006706 bool IsError) {
6707 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006708 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006709 << LHS.get()->getType() << RHS.get()->getType()
6710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006711}
6712
6713/// \brief Returns false if the pointers are converted to a composite type,
6714/// true otherwise.
6715static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006716 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006717 // C++ [expr.rel]p2:
6718 // [...] Pointer conversions (4.10) and qualification
6719 // conversions (4.4) are performed on pointer operands (or on
6720 // a pointer operand and a null pointer constant) to bring
6721 // them to their composite pointer type. [...]
6722 //
6723 // C++ [expr.eq]p1 uses the same notion for (in)equality
6724 // comparisons of pointers.
6725
6726 // C++ [expr.eq]p2:
6727 // In addition, pointers to members can be compared, or a pointer to
6728 // member and a null pointer constant. Pointer to member conversions
6729 // (4.11) and qualification conversions (4.4) are performed to bring
6730 // them to a common type. If one operand is a null pointer constant,
6731 // the common type is the type of the other operand. Otherwise, the
6732 // common type is a pointer to member type similar (4.4) to the type
6733 // of one of the operands, with a cv-qualification signature (4.4)
6734 // that is the union of the cv-qualification signatures of the operand
6735 // types.
6736
Richard Trieuba261492011-09-06 21:27:33 +00006737 QualType LHSType = LHS.get()->getType();
6738 QualType RHSType = RHS.get()->getType();
6739 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6740 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006741
6742 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006743 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006744 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006745 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006746 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006747 return true;
6748 }
6749
6750 if (NonStandardCompositeType)
6751 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006752 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6753 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006754
Richard Trieuba261492011-09-06 21:27:33 +00006755 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6756 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006757 return false;
6758}
6759
6760static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006761 ExprResult &LHS,
6762 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006763 bool IsError) {
6764 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6765 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006766 << LHS.get()->getType() << RHS.get()->getType()
6767 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006768}
6769
Jordan Rose9f63a452012-06-08 21:14:25 +00006770static bool isObjCObjectLiteral(ExprResult &E) {
6771 switch (E.get()->getStmtClass()) {
6772 case Stmt::ObjCArrayLiteralClass:
6773 case Stmt::ObjCDictionaryLiteralClass:
6774 case Stmt::ObjCStringLiteralClass:
6775 case Stmt::ObjCBoxedExprClass:
6776 return true;
6777 default:
6778 // Note that ObjCBoolLiteral is NOT an object literal!
6779 return false;
6780 }
6781}
6782
Jordan Rose8d872ca2012-07-17 17:46:40 +00006783static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6784 // Get the LHS object's interface type.
6785 QualType Type = LHS->getType();
6786 QualType InterfaceType;
6787 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6788 InterfaceType = PTy->getPointeeType();
6789 if (const ObjCObjectType *iQFaceTy =
6790 InterfaceType->getAsObjCQualifiedInterfaceType())
6791 InterfaceType = iQFaceTy->getBaseType();
6792 } else {
6793 // If this is not actually an Objective-C object, bail out.
6794 return false;
6795 }
6796
6797 // If the RHS isn't an Objective-C object, bail out.
6798 if (!RHS->getType()->isObjCObjectPointerType())
6799 return false;
6800
6801 // Try to find the -isEqual: method.
6802 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6803 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6804 InterfaceType,
6805 /*instance=*/true);
6806 if (!Method) {
6807 if (Type->isObjCIdType()) {
6808 // For 'id', just check the global pool.
6809 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6810 /*receiverId=*/true,
6811 /*warn=*/false);
6812 } else {
6813 // Check protocols.
6814 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6815 cast<ObjCObjectPointerType>(Type),
6816 /*instance=*/true);
6817 }
6818 }
6819
6820 if (!Method)
6821 return false;
6822
6823 QualType T = Method->param_begin()[0]->getType();
6824 if (!T->isObjCObjectPointerType())
6825 return false;
6826
6827 QualType R = Method->getResultType();
6828 if (!R->isScalarType())
6829 return false;
6830
6831 return true;
6832}
6833
6834static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6835 ExprResult &LHS, ExprResult &RHS,
6836 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006837 Expr *Literal;
6838 Expr *Other;
6839 if (isObjCObjectLiteral(LHS)) {
6840 Literal = LHS.get();
6841 Other = RHS.get();
6842 } else {
6843 Literal = RHS.get();
6844 Other = LHS.get();
6845 }
6846
6847 // Don't warn on comparisons against nil.
6848 Other = Other->IgnoreParenCasts();
6849 if (Other->isNullPointerConstant(S.getASTContext(),
6850 Expr::NPC_ValueDependentIsNotNull))
6851 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006852
Jordan Roseeec207f2012-07-17 17:46:44 +00006853 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006854 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006855 enum {
6856 LK_Array,
6857 LK_Dictionary,
6858 LK_Numeric,
6859 LK_Boxed,
6860 LK_String
6861 } LiteralKind;
6862
Jordan Rose9f63a452012-06-08 21:14:25 +00006863 switch (Literal->getStmtClass()) {
6864 case Stmt::ObjCStringLiteralClass:
6865 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006866 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006867 break;
6868 case Stmt::ObjCArrayLiteralClass:
6869 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006870 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006871 break;
6872 case Stmt::ObjCDictionaryLiteralClass:
6873 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006874 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006875 break;
6876 case Stmt::ObjCBoxedExprClass: {
6877 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6878 switch (Inner->getStmtClass()) {
6879 case Stmt::IntegerLiteralClass:
6880 case Stmt::FloatingLiteralClass:
6881 case Stmt::CharacterLiteralClass:
6882 case Stmt::ObjCBoolLiteralExprClass:
6883 case Stmt::CXXBoolLiteralExprClass:
6884 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006885 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006886 break;
6887 case Stmt::ImplicitCastExprClass: {
6888 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6889 // Boolean literals can be represented by implicit casts.
6890 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006891 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006892 break;
6893 }
6894 // FALLTHROUGH
6895 }
6896 default:
6897 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006898 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006899 break;
6900 }
6901 break;
6902 }
6903 default:
6904 llvm_unreachable("Unknown Objective-C object literal kind");
6905 }
6906
Jordan Roseeec207f2012-07-17 17:46:44 +00006907 if (LiteralKind == LK_String)
6908 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6909 << Literal->getSourceRange();
6910 else
6911 S.Diag(Loc, diag::warn_objc_literal_comparison)
6912 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006913
Jordan Rose8d872ca2012-07-17 17:46:40 +00006914 if (BinaryOperator::isEqualityOp(Opc) &&
6915 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6916 SourceLocation Start = LHS.get()->getLocStart();
6917 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6918 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006919
Jordan Rose8d872ca2012-07-17 17:46:40 +00006920 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6921 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6922 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6923 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006924 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006925}
6926
Douglas Gregor0c6db942009-05-04 06:07:12 +00006927// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006928QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006929 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006930 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006931 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6932
John McCall2de56d12010-08-25 11:45:40 +00006933 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006934
Chris Lattner02dd4b12009-12-05 05:40:13 +00006935 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006936 if (LHS.get()->getType()->isVectorType() ||
6937 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006938 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006939
Richard Trieuf1775fb2011-09-06 21:43:51 +00006940 QualType LHSType = LHS.get()->getType();
6941 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006942
Richard Trieuf1775fb2011-09-06 21:43:51 +00006943 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6944 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006945
Richard Trieuf1775fb2011-09-06 21:43:51 +00006946 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006947
Richard Trieuf1775fb2011-09-06 21:43:51 +00006948 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006949 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006950 !LHS.get()->getLocStart().isMacroID() &&
6951 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006952 // For non-floating point types, check for self-comparisons of the form
6953 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6954 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006955 //
6956 // NOTE: Don't warn about comparison expressions resulting from macro
6957 // expansion. Also don't warn about comparisons which are only self
6958 // comparisons within a template specialization. The warnings should catch
6959 // obvious cases in the definition of the template anyways. The idea is to
6960 // warn when the typed comparison operator will always evaluate to the same
6961 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006962 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006963 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006964 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006965 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006966 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006967 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006968 << (Opc == BO_EQ
6969 || Opc == BO_LE
6970 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006971 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006972 !DRL->getDecl()->getType()->isReferenceType() &&
6973 !DRR->getDecl()->getType()->isReferenceType()) {
6974 // what is it always going to eval to?
6975 char always_evals_to;
6976 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006977 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006978 always_evals_to = 0; // false
6979 break;
John McCall2de56d12010-08-25 11:45:40 +00006980 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006981 always_evals_to = 1; // true
6982 break;
6983 default:
6984 // best we can say is 'a constant'
6985 always_evals_to = 2; // e.g. array1 <= array2
6986 break;
6987 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006988 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006989 << 1 // array
6990 << always_evals_to);
6991 }
6992 }
Chandler Carruth99919472010-07-10 12:30:03 +00006993 }
Mike Stump1eb44332009-09-09 15:08:12 +00006994
Chris Lattner55660a72009-03-08 19:39:53 +00006995 if (isa<CastExpr>(LHSStripped))
6996 LHSStripped = LHSStripped->IgnoreParenCasts();
6997 if (isa<CastExpr>(RHSStripped))
6998 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006999
Chris Lattner55660a72009-03-08 19:39:53 +00007000 // Warn about comparisons against a string constant (unless the other
7001 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007002 Expr *literalString = 0;
7003 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007004 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007005 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007006 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007007 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007008 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007009 } else if ((isa<StringLiteral>(RHSStripped) ||
7010 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007011 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007012 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007013 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007014 literalStringStripped = RHSStripped;
7015 }
7016
7017 if (literalString) {
7018 std::string resultComparison;
7019 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007020 case BO_LT: resultComparison = ") < 0"; break;
7021 case BO_GT: resultComparison = ") > 0"; break;
7022 case BO_LE: resultComparison = ") <= 0"; break;
7023 case BO_GE: resultComparison = ") >= 0"; break;
7024 case BO_EQ: resultComparison = ") == 0"; break;
7025 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007026 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007027 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007028
Ted Kremenek351ba912011-02-23 01:52:04 +00007029 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007030 PDiag(diag::warn_stringcompare)
7031 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007032 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007033 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007034 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007035
Douglas Gregord64fdd02010-06-08 19:50:34 +00007036 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007037 if (LHS.get()->getType()->isArithmeticType() &&
7038 RHS.get()->getType()->isArithmeticType()) {
7039 UsualArithmeticConversions(LHS, RHS);
7040 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007041 return QualType();
7042 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007043 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007044 LHS = UsualUnaryConversions(LHS.take());
7045 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007046 return QualType();
7047
Richard Trieuf1775fb2011-09-06 21:43:51 +00007048 RHS = UsualUnaryConversions(RHS.take());
7049 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007050 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007051 }
7052
Richard Trieuf1775fb2011-09-06 21:43:51 +00007053 LHSType = LHS.get()->getType();
7054 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007055
Douglas Gregor447b69e2008-11-19 03:25:36 +00007056 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007057 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007058
Richard Trieuccd891a2011-09-09 01:45:06 +00007059 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007060 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007061 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007062 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007063 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007064 if (LHSType->hasFloatingRepresentation())
7065 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007066
Richard Trieuf1775fb2011-09-06 21:43:51 +00007067 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007068 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007069 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007070
Richard Trieuf1775fb2011-09-06 21:43:51 +00007071 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007072 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007073 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007074 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007075
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007076 // All of the following pointer-related warnings are GCC extensions, except
7077 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007078 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007079 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007080 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007081 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007082 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007083
David Blaikie4e4d0842012-03-11 07:00:24 +00007084 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007085 if (LCanPointeeTy == RCanPointeeTy)
7086 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007087 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007088 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7089 // Valid unless comparison between non-null pointer and function pointer
7090 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007091 // In a SFINAE context, we treat this as a hard error to maintain
7092 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007093 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7094 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007095 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007096 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007097
7098 if (isSFINAEContext())
7099 return QualType();
7100
Richard Trieuf1775fb2011-09-06 21:43:51 +00007101 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007102 return ResultTy;
7103 }
7104 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007105
Richard Trieuf1775fb2011-09-06 21:43:51 +00007106 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007107 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007108 else
7109 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007110 }
Eli Friedman3075e762009-08-23 00:27:47 +00007111 // C99 6.5.9p2 and C99 6.5.8p2
7112 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7113 RCanPointeeTy.getUnqualifiedType())) {
7114 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007115 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007116 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007117 << LHSType << RHSType << LHS.get()->getSourceRange()
7118 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007119 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007120 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007121 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7122 // Valid unless comparison between non-null pointer and function pointer
7123 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007124 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007125 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007126 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007127 } else {
7128 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007129 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007130 }
John McCall34d6f932011-03-11 04:25:25 +00007131 if (LCanPointeeTy != RCanPointeeTy) {
7132 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007133 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007134 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007135 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007136 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007137 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007138 }
Mike Stump1eb44332009-09-09 15:08:12 +00007139
David Blaikie4e4d0842012-03-11 07:00:24 +00007140 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007141 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007143 return ResultTy;
7144
Mike Stump1eb44332009-09-09 15:08:12 +00007145 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007146 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007147 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007148 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007149 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007150 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7151 RHS = ImpCastExprToType(RHS.take(), LHSType,
7152 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007153 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007154 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007155 return ResultTy;
7156 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007157 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007158 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007159 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007160 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7161 LHS = ImpCastExprToType(LHS.take(), RHSType,
7162 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007163 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007164 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007165 return ResultTy;
7166 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007167
7168 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007169 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007170 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7171 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007172 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007173 else
7174 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007175 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007176
7177 // Handle scoped enumeration types specifically, since they don't promote
7178 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007179 if (LHS.get()->getType()->isEnumeralType() &&
7180 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7181 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007182 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007183 }
Mike Stump1eb44332009-09-09 15:08:12 +00007184
Steve Naroff1c7d0672008-09-04 15:10:53 +00007185 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007186 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007187 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007188 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7189 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007190
Steve Naroff1c7d0672008-09-04 15:10:53 +00007191 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007192 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007193 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007194 << LHSType << RHSType << LHS.get()->getSourceRange()
7195 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007196 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007197 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007198 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007199 }
John Wiegley429bb272011-04-08 18:41:53 +00007200
Steve Naroff59f53942008-09-28 01:11:11 +00007201 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007202 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007203 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7204 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007205 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007206 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007207 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007208 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007209 ->getPointeeType()->isVoidType())))
7210 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007211 << LHSType << RHSType << LHS.get()->getSourceRange()
7212 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007213 }
John McCall34d6f932011-03-11 04:25:25 +00007214 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007215 LHS = ImpCastExprToType(LHS.take(), RHSType,
7216 RHSType->isPointerType() ? CK_BitCast
7217 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007218 else
John McCall1d9b3b22011-09-09 05:25:32 +00007219 RHS = ImpCastExprToType(RHS.take(), LHSType,
7220 LHSType->isPointerType() ? CK_BitCast
7221 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007222 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007223 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007224
Richard Trieuf1775fb2011-09-06 21:43:51 +00007225 if (LHSType->isObjCObjectPointerType() ||
7226 RHSType->isObjCObjectPointerType()) {
7227 const PointerType *LPT = LHSType->getAs<PointerType>();
7228 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007229 if (LPT || RPT) {
7230 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7231 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007232
Steve Naroffa8069f12008-11-17 19:49:16 +00007233 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007234 !Context.typesAreCompatible(LHSType, RHSType)) {
7235 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007236 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007237 }
John McCall34d6f932011-03-11 04:25:25 +00007238 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007239 LHS = ImpCastExprToType(LHS.take(), RHSType,
7240 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007241 else
John McCall1d9b3b22011-09-09 05:25:32 +00007242 RHS = ImpCastExprToType(RHS.take(), LHSType,
7243 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007244 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007245 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007246 if (LHSType->isObjCObjectPointerType() &&
7247 RHSType->isObjCObjectPointerType()) {
7248 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7249 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007250 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007251 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007252 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007253
John McCall34d6f932011-03-11 04:25:25 +00007254 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007255 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007256 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007257 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007258 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007259 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007260 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007261 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7262 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007263 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007264 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007265 if (LangOpts.DebuggerSupport) {
7266 // Under a debugger, allow the comparison of pointers to integers,
7267 // since users tend to want to compare addresses.
7268 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007269 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007270 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007271 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007272 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007273 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007274 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007275 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7276 isError = true;
7277 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007278 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007279
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007280 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007281 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007282 << LHSType << RHSType << LHS.get()->getSourceRange()
7283 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007284 if (isError)
7285 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007286 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007287
Richard Trieuf1775fb2011-09-06 21:43:51 +00007288 if (LHSType->isIntegerType())
7289 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007290 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007291 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007292 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007293 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007294 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007295 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007296
Steve Naroff39218df2008-09-04 16:56:14 +00007297 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007298 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007299 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7300 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007301 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007302 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007303 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007304 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7305 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007306 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007307 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007308
Richard Trieuf1775fb2011-09-06 21:43:51 +00007309 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007310}
7311
Tanya Lattner4f692c22012-01-16 21:02:28 +00007312
7313// Return a signed type that is of identical size and number of elements.
7314// For floating point vectors, return an integer type of identical size
7315// and number of elements.
7316QualType Sema::GetSignedVectorType(QualType V) {
7317 const VectorType *VTy = V->getAs<VectorType>();
7318 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7319 if (TypeSize == Context.getTypeSize(Context.CharTy))
7320 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7321 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7322 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7323 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7324 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7325 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7326 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7327 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7328 "Unhandled vector element size in vector compare");
7329 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7330}
7331
Nate Begemanbe2341d2008-07-14 18:02:46 +00007332/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007333/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007334/// like a scalar comparison, a vector comparison produces a vector of integer
7335/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007336QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007337 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007338 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007339 // Check to make sure we're operating on vectors of the same type and width,
7340 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007341 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007342 if (vType.isNull())
7343 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007344
Richard Trieu9f60dee2011-09-07 01:19:57 +00007345 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007346
Anton Yartsev7870b132011-03-27 15:36:07 +00007347 // If AltiVec, the comparison results in a numeric type, i.e.
7348 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007349 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007350 return Context.getLogicalOperationType();
7351
Nate Begemanbe2341d2008-07-14 18:02:46 +00007352 // For non-floating point types, check for self-comparisons of the form
7353 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7354 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007355 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007356 if (DeclRefExpr* DRL
7357 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7358 if (DeclRefExpr* DRR
7359 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007360 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007361 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007362 PDiag(diag::warn_comparison_always)
7363 << 0 // self-
7364 << 2 // "a constant"
7365 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007366 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007367
Nate Begemanbe2341d2008-07-14 18:02:46 +00007368 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007369 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007370 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007371 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007372 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007373
7374 // Return a signed type for the vector.
7375 return GetSignedVectorType(LHSType);
7376}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007377
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007378QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7379 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007380 // Ensure that either both operands are of the same vector type, or
7381 // one operand is of a vector type and the other is of its element type.
7382 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7383 if (vType.isNull() || vType->isFloatingType())
7384 return InvalidOperands(Loc, LHS, RHS);
7385
7386 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007387}
7388
Reid Spencer5f016e22007-07-11 17:01:13 +00007389inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007390 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007391 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7392
Richard Trieu9f60dee2011-09-07 01:19:57 +00007393 if (LHS.get()->getType()->isVectorType() ||
7394 RHS.get()->getType()->isVectorType()) {
7395 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7396 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007397 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007398
Richard Trieu9f60dee2011-09-07 01:19:57 +00007399 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007400 }
Steve Naroff90045e82007-07-13 23:32:42 +00007401
Richard Trieu9f60dee2011-09-07 01:19:57 +00007402 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7403 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007404 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007405 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007406 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007407 LHS = LHSResult.take();
7408 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007409
Eli Friedman860a3192012-06-16 02:19:17 +00007410 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007411 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007412 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007413}
7414
7415inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007416 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007417
Tanya Lattner4f692c22012-01-16 21:02:28 +00007418 // Check vector operands differently.
7419 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7420 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7421
Chris Lattner90a8f272010-07-13 19:41:32 +00007422 // Diagnose cases where the user write a logical and/or but probably meant a
7423 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7424 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007425 if (LHS.get()->getType()->isIntegerType() &&
7426 !LHS.get()->getType()->isBooleanType() &&
7427 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007428 // Don't warn in macros or template instantiations.
7429 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007430 // If the RHS can be constant folded, and if it constant folds to something
7431 // that isn't 0 or 1 (which indicate a potential logical operation that
7432 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007433 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007434 llvm::APSInt Result;
7435 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007436 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007437 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007438 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007439 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007440 << (Opc == BO_LAnd ? "&&" : "||");
7441 // Suggest replacing the logical operator with the bitwise version
7442 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7443 << (Opc == BO_LAnd ? "&" : "|")
7444 << FixItHint::CreateReplacement(SourceRange(
7445 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007446 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007447 Opc == BO_LAnd ? "&" : "|");
7448 if (Opc == BO_LAnd)
7449 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7450 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7451 << FixItHint::CreateRemoval(
7452 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007453 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007454 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007455 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007456 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007457 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007458 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007459
David Blaikie4e4d0842012-03-11 07:00:24 +00007460 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007461 LHS = UsualUnaryConversions(LHS.take());
7462 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007463 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007464
Richard Trieu9f60dee2011-09-07 01:19:57 +00007465 RHS = UsualUnaryConversions(RHS.take());
7466 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007467 return QualType();
7468
Richard Trieu9f60dee2011-09-07 01:19:57 +00007469 if (!LHS.get()->getType()->isScalarType() ||
7470 !RHS.get()->getType()->isScalarType())
7471 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007472
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007473 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007474 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007475
John McCall75f7c0f2010-06-04 00:29:51 +00007476 // The following is safe because we only use this method for
7477 // non-overloadable operands.
7478
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007479 // C++ [expr.log.and]p1
7480 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007481 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007482 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7483 if (LHSRes.isInvalid())
7484 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007485 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007486
Richard Trieu9f60dee2011-09-07 01:19:57 +00007487 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7488 if (RHSRes.isInvalid())
7489 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007490 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007491
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007492 // C++ [expr.log.and]p2
7493 // C++ [expr.log.or]p2
7494 // The result is a bool.
7495 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007496}
7497
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007498/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7499/// is a read-only property; return true if so. A readonly property expression
7500/// depends on various declarations and thus must be treated specially.
7501///
Mike Stump1eb44332009-09-09 15:08:12 +00007502static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007503 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7504 if (!PropExpr) return false;
7505 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007506
John McCall3c3b7f92011-10-25 17:37:35 +00007507 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7508 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007509 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007510 PropExpr->getBase()->getType();
7511
John McCall3c3b7f92011-10-25 17:37:35 +00007512 if (const ObjCObjectPointerType *OPT =
7513 BaseType->getAsObjCInterfacePointerType())
7514 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7515 if (S.isPropertyReadonly(PDecl, IFace))
7516 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007517 return false;
7518}
7519
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007520static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007521 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7522 if (!ME) return false;
7523 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7524 ObjCMessageExpr *Base =
7525 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7526 if (!Base) return false;
7527 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007528}
7529
John McCall78dae242012-03-13 00:37:01 +00007530/// Is the given expression (which must be 'const') a reference to a
7531/// variable which was originally non-const, but which has become
7532/// 'const' due to being captured within a block?
7533enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7534static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7535 assert(E->isLValue() && E->getType().isConstQualified());
7536 E = E->IgnoreParens();
7537
7538 // Must be a reference to a declaration from an enclosing scope.
7539 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7540 if (!DRE) return NCCK_None;
7541 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7542
7543 // The declaration must be a variable which is not declared 'const'.
7544 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7545 if (!var) return NCCK_None;
7546 if (var->getType().isConstQualified()) return NCCK_None;
7547 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7548
7549 // Decide whether the first capture was for a block or a lambda.
7550 DeclContext *DC = S.CurContext;
7551 while (DC->getParent() != var->getDeclContext())
7552 DC = DC->getParent();
7553 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7554}
7555
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007556/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7557/// emit an error and return true. If so, return false.
7558static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007559 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007560 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007561 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007562 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007563 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7564 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007565 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7566 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007567 if (IsLV == Expr::MLV_Valid)
7568 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007569
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007570 unsigned Diag = 0;
7571 bool NeedType = false;
7572 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007573 case Expr::MLV_ConstQualified:
7574 Diag = diag::err_typecheck_assign_const;
7575
John McCall78dae242012-03-13 00:37:01 +00007576 // Use a specialized diagnostic when we're assigning to an object
7577 // from an enclosing function or block.
7578 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7579 if (NCCK == NCCK_Block)
7580 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7581 else
7582 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7583 break;
7584 }
7585
John McCall7acddac2011-06-17 06:42:21 +00007586 // In ARC, use some specialized diagnostics for occasions where we
7587 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007588 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007589 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7590 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7591 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7592
John McCall7acddac2011-06-17 06:42:21 +00007593 // Use the normal diagnostic if it's pseudo-__strong but the
7594 // user actually wrote 'const'.
7595 if (var->isARCPseudoStrong() &&
7596 (!var->getTypeSourceInfo() ||
7597 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7598 // There are two pseudo-strong cases:
7599 // - self
John McCallf85e1932011-06-15 23:02:42 +00007600 ObjCMethodDecl *method = S.getCurMethodDecl();
7601 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007602 Diag = method->isClassMethod()
7603 ? diag::err_typecheck_arc_assign_self_class_method
7604 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007605
7606 // - fast enumeration variables
7607 else
John McCallf85e1932011-06-15 23:02:42 +00007608 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007609
John McCallf85e1932011-06-15 23:02:42 +00007610 SourceRange Assign;
7611 if (Loc != OrigLoc)
7612 Assign = SourceRange(OrigLoc, OrigLoc);
7613 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7614 // We need to preserve the AST regardless, so migration tool
7615 // can do its job.
7616 return false;
7617 }
7618 }
7619 }
7620
7621 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007622 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007623 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007624 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7625 NeedType = true;
7626 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007627 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007628 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7629 NeedType = true;
7630 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007631 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007632 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7633 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007634 case Expr::MLV_Valid:
7635 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007636 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007637 case Expr::MLV_MemberFunction:
7638 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007639 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7640 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007641 case Expr::MLV_IncompleteType:
7642 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007643 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007644 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007645 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007646 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7647 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007648 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007649 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007650 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007651 case Expr::MLV_InvalidMessageExpression:
7652 Diag = diag::error_readonly_message_assignment;
7653 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007654 case Expr::MLV_SubObjCPropertySetting:
7655 Diag = diag::error_no_subobject_property_setting;
7656 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007657 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007658
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007659 SourceRange Assign;
7660 if (Loc != OrigLoc)
7661 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007662 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007663 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007664 else
Mike Stump1eb44332009-09-09 15:08:12 +00007665 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007666 return true;
7667}
7668
Nico Weber7c81b432012-07-03 02:03:06 +00007669static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7670 SourceLocation Loc,
7671 Sema &Sema) {
7672 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007673 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7674 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7675 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7676 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007677 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007678 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007679
Nico Weber7c81b432012-07-03 02:03:06 +00007680 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007681 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7682 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7683 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7684 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7685 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7686 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007687 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007688 }
7689}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007690
7691// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007692QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007693 SourceLocation Loc,
7694 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007695 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7696
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007697 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007698 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007699 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007700
Richard Trieu268942b2011-09-07 01:33:52 +00007701 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007702 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7703 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007704 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007705 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007706 Expr *RHSCheck = RHS.get();
7707
Nico Weber7c81b432012-07-03 02:03:06 +00007708 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007709
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007710 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007711 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007712 if (RHS.isInvalid())
7713 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007714 // Special case of NSObject attributes on c-style pointer types.
7715 if (ConvTy == IncompatiblePointer &&
7716 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007717 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007718 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007719 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007720 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007721
John McCallf89e55a2010-11-18 06:31:45 +00007722 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007723 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007724 Diag(Loc, diag::err_objc_object_assignment)
7725 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007726
Chris Lattner2c156472008-08-21 18:04:13 +00007727 // If the RHS is a unary plus or minus, check to see if they = and + are
7728 // right next to each other. If so, the user may have typo'd "x =+ 4"
7729 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007730 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7731 RHSCheck = ICE->getSubExpr();
7732 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007733 if ((UO->getOpcode() == UO_Plus ||
7734 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007735 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007736 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007737 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007738 // And there is a space or other character before the subexpr of the
7739 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007740 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007741 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007742 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007743 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007744 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007745 }
Chris Lattner2c156472008-08-21 18:04:13 +00007746 }
John McCallf85e1932011-06-15 23:02:42 +00007747
7748 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007749 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7750 // Warn about retain cycles where a block captures the LHS, but
7751 // not if the LHS is a simple variable into which the block is
7752 // being stored...unless that variable can be captured by reference!
7753 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7754 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7755 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7756 checkRetainCycles(LHSExpr, RHS.get());
7757
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007758 // It is safe to assign a weak reference into a strong variable.
7759 // Although this code can still have problems:
7760 // id x = self.weakProp;
7761 // id y = self.weakProp;
7762 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7763 // paths through the function. This should be revisited if
7764 // -Wrepeated-use-of-weak is made flow-sensitive.
7765 DiagnosticsEngine::Level Level =
7766 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7767 RHS.get()->getLocStart());
7768 if (Level != DiagnosticsEngine::Ignored)
7769 getCurFunction()->markSafeWeakUse(RHS.get());
7770
Jordan Rosee10f4d32012-09-15 02:48:31 +00007771 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007772 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007773 }
John McCallf85e1932011-06-15 23:02:42 +00007774 }
Chris Lattner2c156472008-08-21 18:04:13 +00007775 } else {
7776 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007777 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007778 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007779
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007780 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007781 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007782 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007783
Richard Trieu268942b2011-09-07 01:33:52 +00007784 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007785
Reid Spencer5f016e22007-07-11 17:01:13 +00007786 // C99 6.5.16p3: The type of an assignment expression is the type of the
7787 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007788 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007789 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7790 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007791 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007792 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007793 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007794 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007795}
7796
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007797// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007798static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007799 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007800 LHS = S.CheckPlaceholderExpr(LHS.take());
7801 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007802 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007803 return QualType();
7804
John McCallcf2e5062010-10-12 07:14:40 +00007805 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7806 // operands, but not unary promotions.
7807 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007808
John McCallf6a16482010-12-04 03:47:34 +00007809 // So we treat the LHS as a ignored value, and in C++ we allow the
7810 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007811 LHS = S.IgnoredValueConversions(LHS.take());
7812 if (LHS.isInvalid())
7813 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007814
Eli Friedmana6115062012-05-24 00:47:05 +00007815 S.DiagnoseUnusedExprResult(LHS.get());
7816
David Blaikie4e4d0842012-03-11 07:00:24 +00007817 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007818 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7819 if (RHS.isInvalid())
7820 return QualType();
7821 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007822 S.RequireCompleteType(Loc, RHS.get()->getType(),
7823 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007824 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007825
John Wiegley429bb272011-04-08 18:41:53 +00007826 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007827}
7828
Steve Naroff49b45262007-07-13 16:58:59 +00007829/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7830/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007831static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7832 ExprValueKind &VK,
7833 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007834 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007835 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007836 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007837
Chris Lattner3528d352008-11-21 07:05:48 +00007838 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007839 // Atomic types can be used for increment / decrement where the non-atomic
7840 // versions can, so ignore the _Atomic() specifier for the purpose of
7841 // checking.
7842 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7843 ResType = ResAtomicType->getValueType();
7844
Chris Lattner3528d352008-11-21 07:05:48 +00007845 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007846
David Blaikie4e4d0842012-03-11 07:00:24 +00007847 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007848 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007849 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007850 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007851 return QualType();
7852 }
7853 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007854 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007855 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007856 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007857 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007858 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007859 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007860 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007861 } else if (ResType->isObjCObjectPointerType()) {
7862 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7863 // Otherwise, we just need a complete type.
7864 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7865 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7866 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007867 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007868 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007869 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007870 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007871 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007872 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007873 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007874 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007875 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007876 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007877 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007878 } else {
John McCall09431682010-11-18 19:01:18 +00007879 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007880 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007881 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007882 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007883 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007884 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007885 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007886 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007887 // In C++, a prefix increment is the same type as the operand. Otherwise
7888 // (in C or with postfix), the increment is the unqualified type of the
7889 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007890 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007891 VK = VK_LValue;
7892 return ResType;
7893 } else {
7894 VK = VK_RValue;
7895 return ResType.getUnqualifiedType();
7896 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007897}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007898
7899
Anders Carlsson369dee42008-02-01 07:15:58 +00007900/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007901/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007902/// where the declaration is needed for type checking. We only need to
7903/// handle cases when the expression references a function designator
7904/// or is an lvalue. Here are some examples:
7905/// - &(x) => x
7906/// - &*****f => f for f a function designator.
7907/// - &s.xx => s
7908/// - &s.zz[1].yy -> s, if zz is an array
7909/// - *(x + 1) -> x, if x is an array
7910/// - &"123"[2] -> 0
7911/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007912static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007913 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007914 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007915 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007916 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007917 // If this is an arrow operator, the address is an offset from
7918 // the base's value, so the object the base refers to is
7919 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007920 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007921 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007922 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007923 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007924 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007925 // FIXME: This code shouldn't be necessary! We should catch the implicit
7926 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007927 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7928 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7929 if (ICE->getSubExpr()->getType()->isArrayType())
7930 return getPrimaryDecl(ICE->getSubExpr());
7931 }
7932 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007933 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007934 case Stmt::UnaryOperatorClass: {
7935 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007936
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007937 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007938 case UO_Real:
7939 case UO_Imag:
7940 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007941 return getPrimaryDecl(UO->getSubExpr());
7942 default:
7943 return 0;
7944 }
7945 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007946 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007947 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007948 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007949 // If the result of an implicit cast is an l-value, we care about
7950 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007951 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007952 default:
7953 return 0;
7954 }
7955}
7956
Richard Trieu5520f232011-09-07 21:46:33 +00007957namespace {
7958 enum {
7959 AO_Bit_Field = 0,
7960 AO_Vector_Element = 1,
7961 AO_Property_Expansion = 2,
7962 AO_Register_Variable = 3,
7963 AO_No_Error = 4
7964 };
7965}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007966/// \brief Diagnose invalid operand for address of operations.
7967///
7968/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007969static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7970 Expr *E, unsigned Type) {
7971 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7972}
7973
Reid Spencer5f016e22007-07-11 17:01:13 +00007974/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007975/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007976/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007977/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007978/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007979/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007980/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007981static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007982 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007983 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7984 if (PTy->getKind() == BuiltinType::Overload) {
7985 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7986 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7987 << OrigOp.get()->getSourceRange();
7988 return QualType();
7989 }
7990
7991 return S.Context.OverloadTy;
7992 }
7993
7994 if (PTy->getKind() == BuiltinType::UnknownAny)
7995 return S.Context.UnknownAnyTy;
7996
7997 if (PTy->getKind() == BuiltinType::BoundMember) {
7998 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7999 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008000 return QualType();
8001 }
John McCall3c3b7f92011-10-25 17:37:35 +00008002
8003 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8004 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008005 }
John McCall9c72c602010-08-27 09:08:28 +00008006
John McCall3c3b7f92011-10-25 17:37:35 +00008007 if (OrigOp.get()->isTypeDependent())
8008 return S.Context.DependentTy;
8009
8010 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008011
John McCall9c72c602010-08-27 09:08:28 +00008012 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008013 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008014
David Blaikie4e4d0842012-03-11 07:00:24 +00008015 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008016 // Implement C99-only parts of addressof rules.
8017 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008018 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008019 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8020 // (assuming the deref expression is valid).
8021 return uOp->getSubExpr()->getType();
8022 }
8023 // Technically, there should be a check for array subscript
8024 // expressions here, but the result of one is always an lvalue anyway.
8025 }
John McCall5808ce42011-02-03 08:15:49 +00008026 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008027 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008028 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008029
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008030 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008031 bool sfinae = S.isSFINAEContext();
8032 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8033 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008034 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008035 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008036 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008037 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008038 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008039 } else if (lval == Expr::LV_MemberFunction) {
8040 // If it's an instance method, make a member pointer.
8041 // The expression must have exactly the form &A::foo.
8042
8043 // If the underlying expression isn't a decl ref, give up.
8044 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008045 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008046 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008047 return QualType();
8048 }
8049 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8050 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8051
8052 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008053 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008054 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008055 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008056
8057 // The method was named without a qualifier.
8058 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008059 if (MD->getParent()->getName().empty())
8060 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8061 << op->getSourceRange();
8062 else {
8063 SmallString<32> Str;
8064 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8065 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8066 << op->getSourceRange()
8067 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8068 }
John McCall9c72c602010-08-27 09:08:28 +00008069 }
8070
John McCall09431682010-11-18 19:01:18 +00008071 return S.Context.getMemberPointerType(op->getType(),
8072 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008073 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008074 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008075 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008076 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008077 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008078 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008079 AddressOfError = AO_Property_Expansion;
8080 } else {
8081 // FIXME: emit more specific diag...
8082 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8083 << op->getSourceRange();
8084 return QualType();
8085 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008086 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008087 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008088 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008089 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008090 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008091 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008092 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008093 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008094 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008095 // with the register storage-class specifier.
8096 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008097 // in C++ it is not error to take address of a register
8098 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008099 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008100 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008101 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008102 }
John McCallba135432009-11-21 08:51:07 +00008103 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008104 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008105 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008106 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008107 // Could be a pointer to member, though, if there is an explicit
8108 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008109 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008110 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008111 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008112 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008113 S.Diag(OpLoc,
8114 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008115 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008116 return QualType();
8117 }
Mike Stump1eb44332009-09-09 15:08:12 +00008118
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008119 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8120 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008121 return S.Context.getMemberPointerType(op->getType(),
8122 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008123 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008124 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008125 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008126 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008127 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008128
Richard Trieu5520f232011-09-07 21:46:33 +00008129 if (AddressOfError != AO_No_Error) {
8130 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8131 return QualType();
8132 }
8133
Eli Friedman441cf102009-05-16 23:27:50 +00008134 if (lval == Expr::LV_IncompleteVoidType) {
8135 // Taking the address of a void variable is technically illegal, but we
8136 // allow it in cases which are otherwise valid.
8137 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008138 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008139 }
8140
Reid Spencer5f016e22007-07-11 17:01:13 +00008141 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008142 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008143 return S.Context.getObjCObjectPointerType(op->getType());
8144 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008145}
8146
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008147/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008148static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8149 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008150 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008151 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008152
John Wiegley429bb272011-04-08 18:41:53 +00008153 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8154 if (ConvResult.isInvalid())
8155 return QualType();
8156 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008157 QualType OpTy = Op->getType();
8158 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008159
8160 if (isa<CXXReinterpretCastExpr>(Op)) {
8161 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8162 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8163 Op->getSourceRange());
8164 }
8165
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008166 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8167 // is an incomplete type or void. It would be possible to warn about
8168 // dereferencing a void pointer, but it's completely well-defined, and such a
8169 // warning is unlikely to catch any mistakes.
8170 if (const PointerType *PT = OpTy->getAs<PointerType>())
8171 Result = PT->getPointeeType();
8172 else if (const ObjCObjectPointerType *OPT =
8173 OpTy->getAs<ObjCObjectPointerType>())
8174 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008175 else {
John McCallfb8721c2011-04-10 19:13:55 +00008176 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008177 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008178 if (PR.take() != Op)
8179 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008180 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008181
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008182 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008183 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008184 << OpTy << Op->getSourceRange();
8185 return QualType();
8186 }
John McCall09431682010-11-18 19:01:18 +00008187
8188 // Dereferences are usually l-values...
8189 VK = VK_LValue;
8190
8191 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008192 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008193 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008194
8195 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008196}
8197
John McCall2de56d12010-08-25 11:45:40 +00008198static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008199 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008200 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008201 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008202 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008203 case tok::periodstar: Opc = BO_PtrMemD; break;
8204 case tok::arrowstar: Opc = BO_PtrMemI; break;
8205 case tok::star: Opc = BO_Mul; break;
8206 case tok::slash: Opc = BO_Div; break;
8207 case tok::percent: Opc = BO_Rem; break;
8208 case tok::plus: Opc = BO_Add; break;
8209 case tok::minus: Opc = BO_Sub; break;
8210 case tok::lessless: Opc = BO_Shl; break;
8211 case tok::greatergreater: Opc = BO_Shr; break;
8212 case tok::lessequal: Opc = BO_LE; break;
8213 case tok::less: Opc = BO_LT; break;
8214 case tok::greaterequal: Opc = BO_GE; break;
8215 case tok::greater: Opc = BO_GT; break;
8216 case tok::exclaimequal: Opc = BO_NE; break;
8217 case tok::equalequal: Opc = BO_EQ; break;
8218 case tok::amp: Opc = BO_And; break;
8219 case tok::caret: Opc = BO_Xor; break;
8220 case tok::pipe: Opc = BO_Or; break;
8221 case tok::ampamp: Opc = BO_LAnd; break;
8222 case tok::pipepipe: Opc = BO_LOr; break;
8223 case tok::equal: Opc = BO_Assign; break;
8224 case tok::starequal: Opc = BO_MulAssign; break;
8225 case tok::slashequal: Opc = BO_DivAssign; break;
8226 case tok::percentequal: Opc = BO_RemAssign; break;
8227 case tok::plusequal: Opc = BO_AddAssign; break;
8228 case tok::minusequal: Opc = BO_SubAssign; break;
8229 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8230 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8231 case tok::ampequal: Opc = BO_AndAssign; break;
8232 case tok::caretequal: Opc = BO_XorAssign; break;
8233 case tok::pipeequal: Opc = BO_OrAssign; break;
8234 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008235 }
8236 return Opc;
8237}
8238
John McCall2de56d12010-08-25 11:45:40 +00008239static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008240 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008241 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008242 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008243 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008244 case tok::plusplus: Opc = UO_PreInc; break;
8245 case tok::minusminus: Opc = UO_PreDec; break;
8246 case tok::amp: Opc = UO_AddrOf; break;
8247 case tok::star: Opc = UO_Deref; break;
8248 case tok::plus: Opc = UO_Plus; break;
8249 case tok::minus: Opc = UO_Minus; break;
8250 case tok::tilde: Opc = UO_Not; break;
8251 case tok::exclaim: Opc = UO_LNot; break;
8252 case tok::kw___real: Opc = UO_Real; break;
8253 case tok::kw___imag: Opc = UO_Imag; break;
8254 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008255 }
8256 return Opc;
8257}
8258
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008259/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8260/// This warning is only emitted for builtin assignment operations. It is also
8261/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008262static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008263 SourceLocation OpLoc) {
8264 if (!S.ActiveTemplateInstantiations.empty())
8265 return;
8266 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8267 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008268 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8269 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8270 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8271 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8272 if (!LHSDeclRef || !RHSDeclRef ||
8273 LHSDeclRef->getLocation().isMacroID() ||
8274 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008275 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008276 const ValueDecl *LHSDecl =
8277 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8278 const ValueDecl *RHSDecl =
8279 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8280 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008281 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008282 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008283 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008284 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008285 if (RefTy->getPointeeType().isVolatileQualified())
8286 return;
8287
8288 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008289 << LHSDeclRef->getType()
8290 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008291}
8292
Douglas Gregoreaebc752008-11-06 23:29:22 +00008293/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8294/// operator @p Opc at location @c TokLoc. This routine only supports
8295/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008296ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008297 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008298 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008299 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008300 // The syntax only allows initializer lists on the RHS of assignment,
8301 // so we don't need to worry about accepting invalid code for
8302 // non-assignment operators.
8303 // C++11 5.17p9:
8304 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8305 // of x = {} is x = T().
8306 InitializationKind Kind =
8307 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8308 InitializedEntity Entity =
8309 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8310 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008311 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008312 if (Init.isInvalid())
8313 return Init;
8314 RHSExpr = Init.take();
8315 }
8316
Richard Trieu78ea78b2011-09-07 01:49:20 +00008317 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008318 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008319 // The following two variables are used for compound assignment operators
8320 QualType CompLHSTy; // Type of LHS after promotions for computation
8321 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008322 ExprValueKind VK = VK_RValue;
8323 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008324
8325 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008326 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008327 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008328 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008329 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8330 VK = LHS.get()->getValueKind();
8331 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008332 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008333 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008334 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008335 break;
John McCall2de56d12010-08-25 11:45:40 +00008336 case BO_PtrMemD:
8337 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008338 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008339 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008340 break;
John McCall2de56d12010-08-25 11:45:40 +00008341 case BO_Mul:
8342 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008343 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008344 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008345 break;
John McCall2de56d12010-08-25 11:45:40 +00008346 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008347 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008348 break;
John McCall2de56d12010-08-25 11:45:40 +00008349 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008350 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008351 break;
John McCall2de56d12010-08-25 11:45:40 +00008352 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008353 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008354 break;
John McCall2de56d12010-08-25 11:45:40 +00008355 case BO_Shl:
8356 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008357 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008358 break;
John McCall2de56d12010-08-25 11:45:40 +00008359 case BO_LE:
8360 case BO_LT:
8361 case BO_GE:
8362 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008363 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008364 break;
John McCall2de56d12010-08-25 11:45:40 +00008365 case BO_EQ:
8366 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008367 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008368 break;
John McCall2de56d12010-08-25 11:45:40 +00008369 case BO_And:
8370 case BO_Xor:
8371 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008372 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008373 break;
John McCall2de56d12010-08-25 11:45:40 +00008374 case BO_LAnd:
8375 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008376 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008377 break;
John McCall2de56d12010-08-25 11:45:40 +00008378 case BO_MulAssign:
8379 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008380 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008381 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008382 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008383 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8384 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008385 break;
John McCall2de56d12010-08-25 11:45:40 +00008386 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008387 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008388 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008389 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8390 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008391 break;
John McCall2de56d12010-08-25 11:45:40 +00008392 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008393 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008394 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8395 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008396 break;
John McCall2de56d12010-08-25 11:45:40 +00008397 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008398 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008401 break;
John McCall2de56d12010-08-25 11:45:40 +00008402 case BO_ShlAssign:
8403 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008404 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008405 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008406 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8407 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008408 break;
John McCall2de56d12010-08-25 11:45:40 +00008409 case BO_AndAssign:
8410 case BO_XorAssign:
8411 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008412 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008413 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8415 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008416 break;
John McCall2de56d12010-08-25 11:45:40 +00008417 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008418 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008419 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008420 VK = RHS.get()->getValueKind();
8421 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008422 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008423 break;
8424 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008425 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008426 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008427
8428 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008429 CheckArrayAccess(LHS.get());
8430 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008431
Eli Friedmanab3a8522009-03-28 01:22:36 +00008432 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008433 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008434 ResultTy, VK, OK, OpLoc,
8435 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008436 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008437 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008438 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008439 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008440 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008441 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008442 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008443 CompResultTy, OpLoc,
8444 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008445}
8446
Sebastian Redlaee3c932009-10-27 12:10:02 +00008447/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8448/// operators are mixed in a way that suggests that the programmer forgot that
8449/// comparison operators have higher precedence. The most typical example of
8450/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008451static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008452 SourceLocation OpLoc, Expr *LHSExpr,
8453 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008454 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008455 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8456 RHSopc = static_cast<BinOp::Opcode>(-1);
8457 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8458 LHSopc = BO->getOpcode();
8459 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8460 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008461
8462 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008463 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008464 return;
8465
8466 // Bitwise operations are sometimes used as eager logical ops.
8467 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008468 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8469 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008470 return;
8471
Richard Trieu78ea78b2011-09-07 01:49:20 +00008472 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8473 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008474 if (!isLeftComp && !isRightComp) return;
8475
Richard Trieu78ea78b2011-09-07 01:49:20 +00008476 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8477 OpLoc)
8478 : SourceRange(OpLoc, RHSExpr->getLocEnd());
David Blaikie0bea8632012-10-08 01:11:04 +00008479 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8480 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008481 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008482 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8483 RHSExpr->getLocEnd())
8484 : SourceRange(LHSExpr->getLocStart(),
8485 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008486
8487 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8488 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8489 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008490 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008491 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008492 SuggestParentheses(Self, OpLoc,
8493 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8494 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008495}
8496
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008497/// \brief It accepts a '&' expr that is inside a '|' one.
8498/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8499/// in parentheses.
8500static void
8501EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8502 BinaryOperator *Bop) {
8503 assert(Bop->getOpcode() == BO_And);
8504 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8505 << Bop->getSourceRange() << OpLoc;
8506 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008507 Self.PDiag(diag::note_precedence_silence)
8508 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008509 Bop->getSourceRange());
8510}
8511
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008512/// \brief It accepts a '&&' expr that is inside a '||' one.
8513/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8514/// in parentheses.
8515static void
8516EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008517 BinaryOperator *Bop) {
8518 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008519 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8520 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008521 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008522 Self.PDiag(diag::note_precedence_silence)
8523 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008524 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008525}
8526
8527/// \brief Returns true if the given expression can be evaluated as a constant
8528/// 'true'.
8529static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8530 bool Res;
8531 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8532}
8533
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008534/// \brief Returns true if the given expression can be evaluated as a constant
8535/// 'false'.
8536static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8537 bool Res;
8538 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8539}
8540
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008541/// \brief Look for '&&' in the left hand of a '||' expr.
8542static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008543 Expr *LHSExpr, Expr *RHSExpr) {
8544 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008545 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008546 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008547 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008548 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008549 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8550 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8551 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8552 } else if (Bop->getOpcode() == BO_LOr) {
8553 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8554 // If it's "a || b && 1 || c" we didn't warn earlier for
8555 // "a || b && 1", but warn now.
8556 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8557 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8558 }
8559 }
8560 }
8561}
8562
8563/// \brief Look for '&&' in the right hand of a '||' expr.
8564static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008565 Expr *LHSExpr, Expr *RHSExpr) {
8566 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008567 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008568 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008569 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008570 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008571 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8572 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8573 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008574 }
8575 }
8576}
8577
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008578/// \brief Look for '&' in the left or right hand of a '|' expr.
8579static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8580 Expr *OrArg) {
8581 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8582 if (Bop->getOpcode() == BO_And)
8583 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8584 }
8585}
8586
David Blaikieb3f55c52012-10-05 00:41:03 +00008587static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8588 Expr *SubExpr, StringRef shift) {
8589 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8590 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008591 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008592 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie6b34c172012-10-08 01:19:49 +00008593 << Bop->getSourceRange() << OpLoc << Op << shift;
David Blaikieb3f55c52012-10-05 00:41:03 +00008594 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008595 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008596 Bop->getSourceRange());
8597 }
8598 }
8599}
8600
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008601/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008602/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008603static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008604 SourceLocation OpLoc, Expr *LHSExpr,
8605 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008606 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008607 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008608 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008609
8610 // Diagnose "arg1 & arg2 | arg3"
8611 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008612 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8613 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008614 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008615
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008616 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8617 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008618 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008619 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8620 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008621 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008622
8623 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8624 || Opc == BO_Shr) {
David Blaikie6b34c172012-10-08 01:19:49 +00008625 StringRef shift = BinaryOperator::getOpcodeStr(Opc);
David Blaikieb3f55c52012-10-05 00:41:03 +00008626 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, shift);
8627 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, shift);
8628 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008629}
8630
Reid Spencer5f016e22007-07-11 17:01:13 +00008631// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008632ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008633 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008634 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008635 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008636 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8637 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008638
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008639 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008640 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008641
Richard Trieubefece12011-09-07 02:02:10 +00008642 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008643}
8644
John McCall3c3b7f92011-10-25 17:37:35 +00008645/// Build an overloaded binary operator expression in the given scope.
8646static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8647 BinaryOperatorKind Opc,
8648 Expr *LHS, Expr *RHS) {
8649 // Find all of the overloaded operators visible from this
8650 // point. We perform both an operator-name lookup from the local
8651 // scope and an argument-dependent lookup based on the types of
8652 // the arguments.
8653 UnresolvedSet<16> Functions;
8654 OverloadedOperatorKind OverOp
8655 = BinaryOperator::getOverloadedOperator(Opc);
8656 if (Sc && OverOp != OO_None)
8657 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8658 RHS->getType(), Functions);
8659
8660 // Build the (potentially-overloaded, potentially-dependent)
8661 // binary operation.
8662 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8663}
8664
John McCall60d7b3a2010-08-24 06:29:42 +00008665ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008666 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008667 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008668 // We want to end up calling one of checkPseudoObjectAssignment
8669 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8670 // both expressions are overloadable or either is type-dependent),
8671 // or CreateBuiltinBinOp (in any other case). We also want to get
8672 // any placeholder types out of the way.
8673
John McCall3c3b7f92011-10-25 17:37:35 +00008674 // Handle pseudo-objects in the LHS.
8675 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8676 // Assignments with a pseudo-object l-value need special analysis.
8677 if (pty->getKind() == BuiltinType::PseudoObject &&
8678 BinaryOperator::isAssignmentOp(Opc))
8679 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8680
8681 // Don't resolve overloads if the other type is overloadable.
8682 if (pty->getKind() == BuiltinType::Overload) {
8683 // We can't actually test that if we still have a placeholder,
8684 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008685 // code below are valid when the LHS is an overload set. Note
8686 // that an overload set can be dependently-typed, but it never
8687 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008688 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8689 if (resolvedRHS.isInvalid()) return ExprError();
8690 RHSExpr = resolvedRHS.take();
8691
John McCallac516502011-10-28 01:04:34 +00008692 if (RHSExpr->isTypeDependent() ||
8693 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008694 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8695 }
8696
8697 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8698 if (LHS.isInvalid()) return ExprError();
8699 LHSExpr = LHS.take();
8700 }
8701
8702 // Handle pseudo-objects in the RHS.
8703 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8704 // An overload in the RHS can potentially be resolved by the type
8705 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008706 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8707 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8708 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8709
Eli Friedman87884912012-01-17 21:27:43 +00008710 if (LHSExpr->getType()->isOverloadableType())
8711 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8712
John McCall3c3b7f92011-10-25 17:37:35 +00008713 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008714 }
John McCall3c3b7f92011-10-25 17:37:35 +00008715
8716 // Don't resolve overloads if the other type is overloadable.
8717 if (pty->getKind() == BuiltinType::Overload &&
8718 LHSExpr->getType()->isOverloadableType())
8719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8720
8721 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8722 if (!resolvedRHS.isUsable()) return ExprError();
8723 RHSExpr = resolvedRHS.take();
8724 }
8725
David Blaikie4e4d0842012-03-11 07:00:24 +00008726 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008727 // If either expression is type-dependent, always build an
8728 // overloaded op.
8729 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8730 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008731
John McCallac516502011-10-28 01:04:34 +00008732 // Otherwise, build an overloaded op if either expression has an
8733 // overloadable type.
8734 if (LHSExpr->getType()->isOverloadableType() ||
8735 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008736 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008737 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008738
Douglas Gregoreaebc752008-11-06 23:29:22 +00008739 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008740 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008741}
8742
John McCall60d7b3a2010-08-24 06:29:42 +00008743ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008744 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008745 Expr *InputExpr) {
8746 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008747 ExprValueKind VK = VK_RValue;
8748 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008749 QualType resultType;
8750 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008751 case UO_PreInc:
8752 case UO_PreDec:
8753 case UO_PostInc:
8754 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008755 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008756 Opc == UO_PreInc ||
8757 Opc == UO_PostInc,
8758 Opc == UO_PreInc ||
8759 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008760 break;
John McCall2de56d12010-08-25 11:45:40 +00008761 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008762 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008763 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008764 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008765 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008766 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008767 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008768 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008769 }
John McCall2de56d12010-08-25 11:45:40 +00008770 case UO_Plus:
8771 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008772 Input = UsualUnaryConversions(Input.take());
8773 if (Input.isInvalid()) return ExprError();
8774 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008775 if (resultType->isDependentType())
8776 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008777 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8778 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008779 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008780 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008781 resultType->isEnumeralType())
8782 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008783 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008784 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008785 resultType->isPointerType())
8786 break;
8787
Sebastian Redl0eb23302009-01-19 00:08:26 +00008788 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008789 << resultType << Input.get()->getSourceRange());
8790
John McCall2de56d12010-08-25 11:45:40 +00008791 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008792 Input = UsualUnaryConversions(Input.take());
8793 if (Input.isInvalid()) return ExprError();
8794 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008795 if (resultType->isDependentType())
8796 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008797 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8798 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8799 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008800 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008801 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008802 else if (resultType->hasIntegerRepresentation())
8803 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008804 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008806 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008807 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008808 break;
John Wiegley429bb272011-04-08 18:41:53 +00008809
John McCall2de56d12010-08-25 11:45:40 +00008810 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008811 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008812 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8813 if (Input.isInvalid()) return ExprError();
8814 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008815
8816 // Though we still have to promote half FP to float...
8817 if (resultType->isHalfType()) {
8818 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8819 resultType = Context.FloatTy;
8820 }
8821
Sebastian Redl28507842009-02-26 14:39:58 +00008822 if (resultType->isDependentType())
8823 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008824 if (resultType->isScalarType()) {
8825 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008826 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008827 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8828 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008829 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8830 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008831 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008832 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008833 // Vector logical not returns the signed variant of the operand type.
8834 resultType = GetSignedVectorType(resultType);
8835 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008836 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008837 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008838 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008839 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008840
Reid Spencer5f016e22007-07-11 17:01:13 +00008841 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008842 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008843 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008844 break;
John McCall2de56d12010-08-25 11:45:40 +00008845 case UO_Real:
8846 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008847 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008848 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8849 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008850 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008851 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8852 if (Input.get()->getValueKind() != VK_RValue &&
8853 Input.get()->getObjectKind() == OK_Ordinary)
8854 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008855 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008856 // In C, a volatile scalar is read by __imag. In C++, it is not.
8857 Input = DefaultLvalueConversion(Input.take());
8858 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008859 break;
John McCall2de56d12010-08-25 11:45:40 +00008860 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008861 resultType = Input.get()->getType();
8862 VK = Input.get()->getValueKind();
8863 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008864 break;
8865 }
John Wiegley429bb272011-04-08 18:41:53 +00008866 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008867 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008868
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008869 // Check for array bounds violations in the operand of the UnaryOperator,
8870 // except for the '*' and '&' operators that have to be handled specially
8871 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8872 // that are explicitly defined as valid by the standard).
8873 if (Opc != UO_AddrOf && Opc != UO_Deref)
8874 CheckArrayAccess(Input.get());
8875
John Wiegley429bb272011-04-08 18:41:53 +00008876 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008877 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008878}
8879
Douglas Gregord3d08532011-12-14 21:23:13 +00008880/// \brief Determine whether the given expression is a qualified member
8881/// access expression, of a form that could be turned into a pointer to member
8882/// with the address-of operator.
8883static bool isQualifiedMemberAccess(Expr *E) {
8884 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8885 if (!DRE->getQualifier())
8886 return false;
8887
8888 ValueDecl *VD = DRE->getDecl();
8889 if (!VD->isCXXClassMember())
8890 return false;
8891
8892 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8893 return true;
8894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8895 return Method->isInstance();
8896
8897 return false;
8898 }
8899
8900 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8901 if (!ULE->getQualifier())
8902 return false;
8903
8904 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8905 DEnd = ULE->decls_end();
8906 D != DEnd; ++D) {
8907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8908 if (Method->isInstance())
8909 return true;
8910 } else {
8911 // Overload set does not contain methods.
8912 break;
8913 }
8914 }
8915
8916 return false;
8917 }
8918
8919 return false;
8920}
8921
John McCall60d7b3a2010-08-24 06:29:42 +00008922ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008923 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008924 // First things first: handle placeholders so that the
8925 // overloaded-operator check considers the right type.
8926 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8927 // Increment and decrement of pseudo-object references.
8928 if (pty->getKind() == BuiltinType::PseudoObject &&
8929 UnaryOperator::isIncrementDecrementOp(Opc))
8930 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8931
8932 // extension is always a builtin operator.
8933 if (Opc == UO_Extension)
8934 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8935
8936 // & gets special logic for several kinds of placeholder.
8937 // The builtin code knows what to do.
8938 if (Opc == UO_AddrOf &&
8939 (pty->getKind() == BuiltinType::Overload ||
8940 pty->getKind() == BuiltinType::UnknownAny ||
8941 pty->getKind() == BuiltinType::BoundMember))
8942 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8943
8944 // Anything else needs to be handled now.
8945 ExprResult Result = CheckPlaceholderExpr(Input);
8946 if (Result.isInvalid()) return ExprError();
8947 Input = Result.take();
8948 }
8949
David Blaikie4e4d0842012-03-11 07:00:24 +00008950 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008951 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8952 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008953 // Find all of the overloaded operators visible from this
8954 // point. We perform both an operator-name lookup from the local
8955 // scope and an argument-dependent lookup based on the types of
8956 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008957 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008958 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008959 if (S && OverOp != OO_None)
8960 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8961 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008962
John McCall9ae2f072010-08-23 23:25:46 +00008963 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008964 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008965
John McCall9ae2f072010-08-23 23:25:46 +00008966 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008967}
8968
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008969// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008970ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008971 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008972 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008973}
8974
Steve Naroff1b273c42007-09-16 14:56:35 +00008975/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008976ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008977 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008978 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008979 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008980 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008981 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008982}
8983
John McCallf85e1932011-06-15 23:02:42 +00008984/// Given the last statement in a statement-expression, check whether
8985/// the result is a producing expression (like a call to an
8986/// ns_returns_retained function) and, if so, rebuild it to hoist the
8987/// release out of the full-expression. Otherwise, return null.
8988/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008989static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008990 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008991 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008992 if (!cleanups) return 0;
8993
8994 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008995 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008996 return 0;
8997
8998 // Splice out the cast. This shouldn't modify any interesting
8999 // features of the statement.
9000 Expr *producer = cast->getSubExpr();
9001 assert(producer->getType() == cast->getType());
9002 assert(producer->getValueKind() == cast->getValueKind());
9003 cleanups->setSubExpr(producer);
9004 return cleanups;
9005}
9006
John McCall73f428c2012-04-04 01:27:53 +00009007void Sema::ActOnStartStmtExpr() {
9008 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9009}
9010
9011void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009012 // Note that function is also called by TreeTransform when leaving a
9013 // StmtExpr scope without rebuilding anything.
9014
John McCall73f428c2012-04-04 01:27:53 +00009015 DiscardCleanupsInEvaluationContext();
9016 PopExpressionEvaluationContext();
9017}
9018
John McCall60d7b3a2010-08-24 06:29:42 +00009019ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009020Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009021 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009022 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9023 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9024
John McCall73f428c2012-04-04 01:27:53 +00009025 if (hasAnyUnrecoverableErrorsInThisFunction())
9026 DiscardCleanupsInEvaluationContext();
9027 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9028 PopExpressionEvaluationContext();
9029
Douglas Gregordd8f5692010-03-10 04:54:39 +00009030 bool isFileScope
9031 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009032 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009033 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009034
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009035 // FIXME: there are a variety of strange constraints to enforce here, for
9036 // example, it is not possible to goto into a stmt expression apparently.
9037 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009038
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009039 // If there are sub stmts in the compound stmt, take the type of the last one
9040 // as the type of the stmtexpr.
9041 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009042 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009043 if (!Compound->body_empty()) {
9044 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009045 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009046 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009047 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9048 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009049 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009050 }
John McCallf85e1932011-06-15 23:02:42 +00009051
John Wiegley429bb272011-04-08 18:41:53 +00009052 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009053 // Do function/array conversion on the last expression, but not
9054 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009055 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9056 if (LastExpr.isInvalid())
9057 return ExprError();
9058 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009059
John Wiegley429bb272011-04-08 18:41:53 +00009060 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009061 // In ARC, if the final expression ends in a consume, splice
9062 // the consume out and bind it later. In the alternate case
9063 // (when dealing with a retainable type), the result
9064 // initialization will create a produce. In both cases the
9065 // result will be +1, and we'll need to balance that out with
9066 // a bind.
9067 if (Expr *rebuiltLastStmt
9068 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9069 LastExpr = rebuiltLastStmt;
9070 } else {
9071 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009072 InitializedEntity::InitializeResult(LPLoc,
9073 Ty,
9074 false),
9075 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009076 LastExpr);
9077 }
9078
John Wiegley429bb272011-04-08 18:41:53 +00009079 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009080 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009081 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009082 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009083 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009084 else
John Wiegley429bb272011-04-08 18:41:53 +00009085 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009086 StmtExprMayBindToTemp = true;
9087 }
9088 }
9089 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009091
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009092 // FIXME: Check that expression type is complete/non-abstract; statement
9093 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009094 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9095 if (StmtExprMayBindToTemp)
9096 return MaybeBindToTemporary(ResStmtExpr);
9097 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009098}
Steve Naroffd34e9152007-08-01 22:05:33 +00009099
John McCall60d7b3a2010-08-24 06:29:42 +00009100ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009101 TypeSourceInfo *TInfo,
9102 OffsetOfComponent *CompPtr,
9103 unsigned NumComponents,
9104 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009105 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009106 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009107 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009108
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009109 // We must have at least one component that refers to the type, and the first
9110 // one is known to be a field designator. Verify that the ArgTy represents
9111 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009112 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009113 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9114 << ArgTy << TypeRange);
9115
9116 // Type must be complete per C99 7.17p3 because a declaring a variable
9117 // with an incomplete type would be ill-formed.
9118 if (!Dependent
9119 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009120 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009121 return ExprError();
9122
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009123 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9124 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009125 // FIXME: This diagnostic isn't actually visible because the location is in
9126 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009127 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009128 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9129 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009130
9131 bool DidWarnAboutNonPOD = false;
9132 QualType CurrentType = ArgTy;
9133 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009134 SmallVector<OffsetOfNode, 4> Comps;
9135 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009136 for (unsigned i = 0; i != NumComponents; ++i) {
9137 const OffsetOfComponent &OC = CompPtr[i];
9138 if (OC.isBrackets) {
9139 // Offset of an array sub-field. TODO: Should we allow vector elements?
9140 if (!CurrentType->isDependentType()) {
9141 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9142 if(!AT)
9143 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9144 << CurrentType);
9145 CurrentType = AT->getElementType();
9146 } else
9147 CurrentType = Context.DependentTy;
9148
Richard Smithea011432011-10-17 23:29:39 +00009149 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9150 if (IdxRval.isInvalid())
9151 return ExprError();
9152 Expr *Idx = IdxRval.take();
9153
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009154 // The expression must be an integral expression.
9155 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009156 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9157 !Idx->getType()->isIntegerType())
9158 return ExprError(Diag(Idx->getLocStart(),
9159 diag::err_typecheck_subscript_not_integer)
9160 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009161
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009162 // Record this array index.
9163 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009164 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009165 continue;
9166 }
9167
9168 // Offset of a field.
9169 if (CurrentType->isDependentType()) {
9170 // We have the offset of a field, but we can't look into the dependent
9171 // type. Just record the identifier of the field.
9172 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9173 CurrentType = Context.DependentTy;
9174 continue;
9175 }
9176
9177 // We need to have a complete type to look into.
9178 if (RequireCompleteType(OC.LocStart, CurrentType,
9179 diag::err_offsetof_incomplete_type))
9180 return ExprError();
9181
9182 // Look for the designated field.
9183 const RecordType *RC = CurrentType->getAs<RecordType>();
9184 if (!RC)
9185 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9186 << CurrentType);
9187 RecordDecl *RD = RC->getDecl();
9188
9189 // C++ [lib.support.types]p5:
9190 // The macro offsetof accepts a restricted set of type arguments in this
9191 // International Standard. type shall be a POD structure or a POD union
9192 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009193 // C++11 [support.types]p4:
9194 // If type is not a standard-layout class (Clause 9), the results are
9195 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009196 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009197 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9198 unsigned DiagID =
9199 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9200 : diag::warn_offsetof_non_pod_type;
9201
9202 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009203 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009204 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009205 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9206 << CurrentType))
9207 DidWarnAboutNonPOD = true;
9208 }
9209
9210 // Look for the field.
9211 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9212 LookupQualifiedName(R, RD);
9213 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009214 IndirectFieldDecl *IndirectMemberDecl = 0;
9215 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009216 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009217 MemberDecl = IndirectMemberDecl->getAnonField();
9218 }
9219
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009220 if (!MemberDecl)
9221 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9222 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9223 OC.LocEnd));
9224
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009225 // C99 7.17p3:
9226 // (If the specified member is a bit-field, the behavior is undefined.)
9227 //
9228 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009229 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009230 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9231 << MemberDecl->getDeclName()
9232 << SourceRange(BuiltinLoc, RParenLoc);
9233 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9234 return ExprError();
9235 }
Eli Friedman19410a72010-08-05 10:11:36 +00009236
9237 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009238 if (IndirectMemberDecl)
9239 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009240
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009241 // If the member was found in a base class, introduce OffsetOfNodes for
9242 // the base class indirections.
9243 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9244 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009245 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009246 CXXBasePath &Path = Paths.front();
9247 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9248 B != BEnd; ++B)
9249 Comps.push_back(OffsetOfNode(B->Base));
9250 }
Eli Friedman19410a72010-08-05 10:11:36 +00009251
Francois Pichet87c2e122010-11-21 06:08:52 +00009252 if (IndirectMemberDecl) {
9253 for (IndirectFieldDecl::chain_iterator FI =
9254 IndirectMemberDecl->chain_begin(),
9255 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9256 assert(isa<FieldDecl>(*FI));
9257 Comps.push_back(OffsetOfNode(OC.LocStart,
9258 cast<FieldDecl>(*FI), OC.LocEnd));
9259 }
9260 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009261 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009262
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009263 CurrentType = MemberDecl->getType().getNonReferenceType();
9264 }
9265
9266 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009267 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009268}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009269
John McCall60d7b3a2010-08-24 06:29:42 +00009270ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009271 SourceLocation BuiltinLoc,
9272 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009273 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009274 OffsetOfComponent *CompPtr,
9275 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009276 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009277
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009278 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009279 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009280 if (ArgTy.isNull())
9281 return ExprError();
9282
Eli Friedman5a15dc12010-08-05 10:15:45 +00009283 if (!ArgTInfo)
9284 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9285
9286 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009287 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009288}
9289
9290
John McCall60d7b3a2010-08-24 06:29:42 +00009291ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009292 Expr *CondExpr,
9293 Expr *LHSExpr, Expr *RHSExpr,
9294 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009295 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9296
John McCallf89e55a2010-11-18 06:31:45 +00009297 ExprValueKind VK = VK_RValue;
9298 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009299 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009300 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009301 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009302 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009303 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009304 } else {
9305 // The conditional expression is required to be a constant expression.
9306 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009307 ExprResult CondICE
9308 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9309 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009310 if (CondICE.isInvalid())
9311 return ExprError();
9312 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009313
Sebastian Redl28507842009-02-26 14:39:58 +00009314 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009315 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9316
9317 resType = ActiveExpr->getType();
9318 ValueDependent = ActiveExpr->isValueDependent();
9319 VK = ActiveExpr->getValueKind();
9320 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009321 }
9322
Sebastian Redlf53597f2009-03-15 17:47:39 +00009323 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009324 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009325 resType->isDependentType(),
9326 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009327}
9328
Steve Naroff4eb206b2008-09-03 18:15:37 +00009329//===----------------------------------------------------------------------===//
9330// Clang Extensions.
9331//===----------------------------------------------------------------------===//
9332
9333/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009334void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009335 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009336 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009337 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009338 if (CurScope)
9339 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009340 else
9341 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009342
Eli Friedman84b007f2012-01-26 03:00:14 +00009343 getCurBlock()->HasImplicitReturnType = true;
9344
John McCall538773c2011-11-11 03:19:12 +00009345 // Enter a new evaluation context to insulate the block from any
9346 // cleanups from the enclosing full-expression.
9347 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009348}
9349
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009350void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9351 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009352 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009353 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009354 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009355
John McCallbf1a0282010-06-04 23:28:52 +00009356 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009357 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009358
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009359 // FIXME: We should allow unexpanded parameter packs here, but that would,
9360 // in turn, make the block expression contain unexpanded parameter packs.
9361 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9362 // Drop the parameters.
9363 FunctionProtoType::ExtProtoInfo EPI;
9364 EPI.HasTrailingReturn = false;
9365 EPI.TypeQuals |= DeclSpec::TQ_const;
9366 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9367 EPI);
9368 Sig = Context.getTrivialTypeSourceInfo(T);
9369 }
9370
John McCall711c52b2011-01-05 12:14:39 +00009371 // GetTypeForDeclarator always produces a function type for a block
9372 // literal signature. Furthermore, it is always a FunctionProtoType
9373 // unless the function was written with a typedef.
9374 assert(T->isFunctionType() &&
9375 "GetTypeForDeclarator made a non-function block signature");
9376
9377 // Look for an explicit signature in that function type.
9378 FunctionProtoTypeLoc ExplicitSignature;
9379
9380 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9381 if (isa<FunctionProtoTypeLoc>(tmp)) {
9382 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9383
9384 // Check whether that explicit signature was synthesized by
9385 // GetTypeForDeclarator. If so, don't save that as part of the
9386 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009387 if (ExplicitSignature.getLocalRangeBegin() ==
9388 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009389 // This would be much cheaper if we stored TypeLocs instead of
9390 // TypeSourceInfos.
9391 TypeLoc Result = ExplicitSignature.getResultLoc();
9392 unsigned Size = Result.getFullDataSize();
9393 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9394 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9395
9396 ExplicitSignature = FunctionProtoTypeLoc();
9397 }
John McCall82dc0092010-06-04 11:21:44 +00009398 }
Mike Stump1eb44332009-09-09 15:08:12 +00009399
John McCall711c52b2011-01-05 12:14:39 +00009400 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9401 CurBlock->FunctionType = T;
9402
9403 const FunctionType *Fn = T->getAs<FunctionType>();
9404 QualType RetTy = Fn->getResultType();
9405 bool isVariadic =
9406 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9407
John McCallc71a4912010-06-04 19:02:56 +00009408 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009409
John McCall82dc0092010-06-04 11:21:44 +00009410 // Don't allow returning a objc interface by value.
9411 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009412 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009413 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9414 return;
9415 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009416
John McCall82dc0092010-06-04 11:21:44 +00009417 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009418 // return type. TODO: what should we do with declarators like:
9419 // ^ * { ... }
9420 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009421 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009422 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009423 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009424 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009425 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009426
John McCall82dc0092010-06-04 11:21:44 +00009427 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009428 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009429 if (ExplicitSignature) {
9430 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9431 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009432 if (Param->getIdentifier() == 0 &&
9433 !Param->isImplicit() &&
9434 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009435 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009436 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009437 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009438 }
John McCall82dc0092010-06-04 11:21:44 +00009439
9440 // Fake up parameter variables if we have a typedef, like
9441 // ^ fntype { ... }
9442 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9443 for (FunctionProtoType::arg_type_iterator
9444 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9445 ParmVarDecl *Param =
9446 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009447 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009448 *I);
John McCallc71a4912010-06-04 19:02:56 +00009449 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009450 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009451 }
John McCall82dc0092010-06-04 11:21:44 +00009452
John McCallc71a4912010-06-04 19:02:56 +00009453 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009454 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009455 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009456 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9457 CurBlock->TheDecl->param_end(),
9458 /*CheckParameterNames=*/false);
9459 }
9460
John McCall82dc0092010-06-04 11:21:44 +00009461 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009462 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009463
John McCall82dc0092010-06-04 11:21:44 +00009464 // Put the parameter variables in scope. We can bail out immediately
9465 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009466 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009467 return;
9468
Steve Naroff090276f2008-10-10 01:28:17 +00009469 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009470 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9471 (*AI)->setOwningFunction(CurBlock->TheDecl);
9472
Steve Naroff090276f2008-10-10 01:28:17 +00009473 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009474 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009475 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009476
Steve Naroff090276f2008-10-10 01:28:17 +00009477 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009478 }
John McCall7a9813c2010-01-22 00:28:27 +00009479 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009480}
9481
9482/// ActOnBlockError - If there is an error parsing a block, this callback
9483/// is invoked to pop the information about the block from the action impl.
9484void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009485 // Leave the expression-evaluation context.
9486 DiscardCleanupsInEvaluationContext();
9487 PopExpressionEvaluationContext();
9488
Steve Naroff4eb206b2008-09-03 18:15:37 +00009489 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009490 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009491 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009492}
9493
9494/// ActOnBlockStmtExpr - This is called when the body of a block statement
9495/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009496ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009497 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009498 // If blocks are disabled, emit an error.
9499 if (!LangOpts.Blocks)
9500 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009501
John McCall538773c2011-11-11 03:19:12 +00009502 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009503 if (hasAnyUnrecoverableErrorsInThisFunction())
9504 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009505 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9506 PopExpressionEvaluationContext();
9507
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009508 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009509
9510 if (BSI->HasImplicitReturnType)
9511 deduceClosureReturnType(*BSI);
9512
Steve Naroff090276f2008-10-10 01:28:17 +00009513 PopDeclContext();
9514
Steve Naroff4eb206b2008-09-03 18:15:37 +00009515 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009516 if (!BSI->ReturnType.isNull())
9517 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009518
Mike Stump56925862009-07-28 22:04:01 +00009519 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009520 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009521
John McCall469a1eb2011-02-02 13:00:07 +00009522 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009523 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9524 SmallVector<BlockDecl::Capture, 4> Captures;
9525 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9526 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9527 if (Cap.isThisCapture())
9528 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009529 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009530 Cap.isNested(), Cap.getCopyExpr());
9531 Captures.push_back(NewCap);
9532 }
9533 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9534 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009535
John McCallc71a4912010-06-04 19:02:56 +00009536 // If the user wrote a function type in some form, try to use that.
9537 if (!BSI->FunctionType.isNull()) {
9538 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9539
9540 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9541 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9542
9543 // Turn protoless block types into nullary block types.
9544 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009545 FunctionProtoType::ExtProtoInfo EPI;
9546 EPI.ExtInfo = Ext;
9547 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009548
9549 // Otherwise, if we don't need to change anything about the function type,
9550 // preserve its sugar structure.
9551 } else if (FTy->getResultType() == RetTy &&
9552 (!NoReturn || FTy->getNoReturnAttr())) {
9553 BlockTy = BSI->FunctionType;
9554
9555 // Otherwise, make the minimal modifications to the function type.
9556 } else {
9557 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009558 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9559 EPI.TypeQuals = 0; // FIXME: silently?
9560 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009561 BlockTy = Context.getFunctionType(RetTy,
9562 FPT->arg_type_begin(),
9563 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009564 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009565 }
9566
9567 // If we don't have a function type, just build one from nothing.
9568 } else {
John McCalle23cf432010-12-14 08:05:40 +00009569 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009570 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009571 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009572 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009573
John McCallc71a4912010-06-04 19:02:56 +00009574 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9575 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009576 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009577
Chris Lattner17a78302009-04-19 05:28:12 +00009578 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009579 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009580 !hasAnyUnrecoverableErrorsInThisFunction() &&
9581 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009582 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009583
Chris Lattnere476bdc2011-02-17 23:58:47 +00009584 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009585
Jordan Rose7dd900e2012-07-02 21:19:23 +00009586 // Try to apply the named return value optimization. We have to check again
9587 // if we can do this, though, because blocks keep return statements around
9588 // to deduce an implicit return type.
9589 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9590 !BSI->TheDecl->isDependentContext())
9591 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009592
Benjamin Kramerd2486192011-07-12 14:11:05 +00009593 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9594 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009595 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009596
John McCall80ee6e82011-11-10 05:35:25 +00009597 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009598 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009599 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009600 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009601 ExprCleanupObjects.push_back(Result->getBlockDecl());
9602 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009603
9604 // It also gets a branch-protected scope if any of the captured
9605 // variables needs destruction.
9606 for (BlockDecl::capture_const_iterator
9607 ci = Result->getBlockDecl()->capture_begin(),
9608 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9609 const VarDecl *var = ci->getVariable();
9610 if (var->getType().isDestructedType() != QualType::DK_none) {
9611 getCurFunction()->setHasBranchProtectedScope();
9612 break;
9613 }
9614 }
John McCall80ee6e82011-11-10 05:35:25 +00009615 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009616
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009617 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009618}
9619
John McCall60d7b3a2010-08-24 06:29:42 +00009620ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009621 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009622 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009623 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009624 GetTypeFromParser(Ty, &TInfo);
9625 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009626}
9627
John McCall60d7b3a2010-08-24 06:29:42 +00009628ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009629 Expr *E, TypeSourceInfo *TInfo,
9630 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009631 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009632
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009633 // Get the va_list type
9634 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009635 if (VaListType->isArrayType()) {
9636 // Deal with implicit array decay; for example, on x86-64,
9637 // va_list is an array, but it's supposed to decay to
9638 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009639 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009640 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009641 ExprResult Result = UsualUnaryConversions(E);
9642 if (Result.isInvalid())
9643 return ExprError();
9644 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009645 } else {
9646 // Otherwise, the va_list argument must be an l-value because
9647 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009648 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009649 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009650 return ExprError();
9651 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009652
Douglas Gregordd027302009-05-19 23:10:31 +00009653 if (!E->isTypeDependent() &&
9654 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009655 return ExprError(Diag(E->getLocStart(),
9656 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009657 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009658 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009659
David Majnemer0adde122011-06-14 05:17:32 +00009660 if (!TInfo->getType()->isDependentType()) {
9661 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009662 diag::err_second_parameter_to_va_arg_incomplete,
9663 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009664 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009665
David Majnemer0adde122011-06-14 05:17:32 +00009666 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009667 TInfo->getType(),
9668 diag::err_second_parameter_to_va_arg_abstract,
9669 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009670 return ExprError();
9671
Douglas Gregor4eb75222011-07-30 06:45:27 +00009672 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009673 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009674 TInfo->getType()->isObjCLifetimeType()
9675 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9676 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009677 << TInfo->getType()
9678 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009679 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009680
9681 // Check for va_arg where arguments of the given type will be promoted
9682 // (i.e. this va_arg is guaranteed to have undefined behavior).
9683 QualType PromoteType;
9684 if (TInfo->getType()->isPromotableIntegerType()) {
9685 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9686 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9687 PromoteType = QualType();
9688 }
9689 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9690 PromoteType = Context.DoubleTy;
9691 if (!PromoteType.isNull())
9692 Diag(TInfo->getTypeLoc().getBeginLoc(),
9693 diag::warn_second_parameter_to_va_arg_never_compatible)
9694 << TInfo->getType()
9695 << PromoteType
9696 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009697 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009698
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009699 QualType T = TInfo->getType().getNonLValueExprType(Context);
9700 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009701}
9702
John McCall60d7b3a2010-08-24 06:29:42 +00009703ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009704 // The type of __null will be int or long, depending on the size of
9705 // pointers on the target.
9706 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009707 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9708 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009709 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009710 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009711 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009712 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009713 Ty = Context.LongLongTy;
9714 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009715 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009716 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009717
Sebastian Redlf53597f2009-03-15 17:47:39 +00009718 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009719}
9720
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009721static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009722 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009723 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009724 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009725
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009726 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9727 if (!PT)
9728 return;
9729
9730 // Check if the destination is of type 'id'.
9731 if (!PT->isObjCIdType()) {
9732 // Check if the destination is the 'NSString' interface.
9733 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9734 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9735 return;
9736 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009737
John McCall4b9c2d22011-11-06 09:01:30 +00009738 // Ignore any parens, implicit casts (should only be
9739 // array-to-pointer decays), and not-so-opaque values. The last is
9740 // important for making this trigger for property assignments.
9741 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9742 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9743 if (OV->getSourceExpr())
9744 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9745
9746 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009747 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009748 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009749
Douglas Gregor849b2432010-03-31 17:46:05 +00009750 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009751}
9752
Chris Lattner5cf216b2008-01-04 18:04:52 +00009753bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9754 SourceLocation Loc,
9755 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009756 Expr *SrcExpr, AssignmentAction Action,
9757 bool *Complained) {
9758 if (Complained)
9759 *Complained = false;
9760
Chris Lattner5cf216b2008-01-04 18:04:52 +00009761 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009762 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009763 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009764 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009765 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009766 ConversionFixItGenerator ConvHints;
9767 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009768 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009769
Chris Lattner5cf216b2008-01-04 18:04:52 +00009770 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009771 case Compatible:
9772 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9773 return false;
9774
Chris Lattnerb7b61152008-01-04 18:22:42 +00009775 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009776 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009777 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9778 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009779 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009780 case IntToPointer:
9781 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9783 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009784 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009785 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009786 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009787 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009788 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9789 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009790 if (Hint.isNull() && !CheckInferredResultType) {
9791 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9792 }
9793 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009794 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009795 case IncompatiblePointerSign:
9796 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9797 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009798 case FunctionVoidPointer:
9799 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9800 break;
John McCall86c05f32011-02-01 00:10:29 +00009801 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009802 // Perform array-to-pointer decay if necessary.
9803 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9804
John McCall86c05f32011-02-01 00:10:29 +00009805 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9806 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9807 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9808 DiagKind = diag::err_typecheck_incompatible_address_space;
9809 break;
John McCallf85e1932011-06-15 23:02:42 +00009810
9811
9812 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009813 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009814 break;
John McCall86c05f32011-02-01 00:10:29 +00009815 }
9816
9817 llvm_unreachable("unknown error case for discarding qualifiers!");
9818 // fallthrough
9819 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009820 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009821 // If the qualifiers lost were because we were applying the
9822 // (deprecated) C++ conversion from a string literal to a char*
9823 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9824 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009825 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009826 // bit of refactoring (so that the second argument is an
9827 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009828 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009829 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009830 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009831 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9832 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009833 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9834 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009835 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009836 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009837 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009838 case IntToBlockPointer:
9839 DiagKind = diag::err_int_to_block_pointer;
9840 break;
9841 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009842 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009843 break;
Steve Naroff39579072008-10-14 22:18:38 +00009844 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009845 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009846 // it can give a more specific diagnostic.
9847 DiagKind = diag::warn_incompatible_qualified_id;
9848 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009849 case IncompatibleVectors:
9850 DiagKind = diag::warn_incompatible_vectors;
9851 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009852 case IncompatibleObjCWeakRef:
9853 DiagKind = diag::err_arc_weak_unavailable_assign;
9854 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009855 case Incompatible:
9856 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009857 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9858 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009859 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009860 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009861 break;
9862 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009863
Douglas Gregord4eea832010-04-09 00:35:39 +00009864 QualType FirstType, SecondType;
9865 switch (Action) {
9866 case AA_Assigning:
9867 case AA_Initializing:
9868 // The destination type comes first.
9869 FirstType = DstType;
9870 SecondType = SrcType;
9871 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009872
Douglas Gregord4eea832010-04-09 00:35:39 +00009873 case AA_Returning:
9874 case AA_Passing:
9875 case AA_Converting:
9876 case AA_Sending:
9877 case AA_Casting:
9878 // The source type comes first.
9879 FirstType = SrcType;
9880 SecondType = DstType;
9881 break;
9882 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009883
Anna Zaks67221552011-07-28 19:51:27 +00009884 PartialDiagnostic FDiag = PDiag(DiagKind);
9885 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9886
9887 // If we can fix the conversion, suggest the FixIts.
9888 assert(ConvHints.isNull() || Hint.isNull());
9889 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009890 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9891 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009892 FDiag << *HI;
9893 } else {
9894 FDiag << Hint;
9895 }
9896 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9897
Richard Trieu6efd4c52011-11-23 22:32:32 +00009898 if (MayHaveFunctionDiff)
9899 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9900
Anna Zaks67221552011-07-28 19:51:27 +00009901 Diag(Loc, FDiag);
9902
Richard Trieu6efd4c52011-11-23 22:32:32 +00009903 if (SecondType == Context.OverloadTy)
9904 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9905 FirstType);
9906
Douglas Gregor926df6c2011-06-11 01:09:30 +00009907 if (CheckInferredResultType)
9908 EmitRelatedResultTypeNote(SrcExpr);
9909
Douglas Gregora41a8c52010-04-22 00:20:18 +00009910 if (Complained)
9911 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009912 return isInvalid;
9913}
Anders Carlssone21555e2008-11-30 19:50:32 +00009914
Richard Smith282e7e62012-02-04 09:53:13 +00009915ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9916 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009917 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9918 public:
9919 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9920 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9921 }
9922 } Diagnoser;
9923
9924 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9925}
9926
9927ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9928 llvm::APSInt *Result,
9929 unsigned DiagID,
9930 bool AllowFold) {
9931 class IDDiagnoser : public VerifyICEDiagnoser {
9932 unsigned DiagID;
9933
9934 public:
9935 IDDiagnoser(unsigned DiagID)
9936 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9937
9938 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9939 S.Diag(Loc, DiagID) << SR;
9940 }
9941 } Diagnoser(DiagID);
9942
9943 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9944}
9945
9946void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9947 SourceRange SR) {
9948 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009949}
9950
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009951ExprResult
9952Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009953 VerifyICEDiagnoser &Diagnoser,
9954 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009955 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009956
David Blaikie4e4d0842012-03-11 07:00:24 +00009957 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009958 // C++11 [expr.const]p5:
9959 // If an expression of literal class type is used in a context where an
9960 // integral constant expression is required, then that class type shall
9961 // have a single non-explicit conversion function to an integral or
9962 // unscoped enumeration type
9963 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009964 if (!Diagnoser.Suppress) {
9965 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9966 public:
9967 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9968
9969 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9970 QualType T) {
9971 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9972 }
9973
9974 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9975 SourceLocation Loc,
9976 QualType T) {
9977 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9978 }
9979
9980 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9981 SourceLocation Loc,
9982 QualType T,
9983 QualType ConvTy) {
9984 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9985 }
9986
9987 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9988 CXXConversionDecl *Conv,
9989 QualType ConvTy) {
9990 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9991 << ConvTy->isEnumeralType() << ConvTy;
9992 }
9993
9994 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9995 QualType T) {
9996 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9997 }
9998
9999 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10000 CXXConversionDecl *Conv,
10001 QualType ConvTy) {
10002 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10003 << ConvTy->isEnumeralType() << ConvTy;
10004 }
10005
10006 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10007 SourceLocation Loc,
10008 QualType T,
10009 QualType ConvTy) {
10010 return DiagnosticBuilder::getEmpty();
10011 }
10012 } ConvertDiagnoser;
10013
10014 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10015 ConvertDiagnoser,
10016 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010017 } else {
10018 // The caller wants to silently enquire whether this is an ICE. Don't
10019 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010020 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10021 public:
10022 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10023
10024 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10025 QualType T) {
10026 return DiagnosticBuilder::getEmpty();
10027 }
10028
10029 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10030 SourceLocation Loc,
10031 QualType T) {
10032 return DiagnosticBuilder::getEmpty();
10033 }
10034
10035 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10036 SourceLocation Loc,
10037 QualType T,
10038 QualType ConvTy) {
10039 return DiagnosticBuilder::getEmpty();
10040 }
10041
10042 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10043 CXXConversionDecl *Conv,
10044 QualType ConvTy) {
10045 return DiagnosticBuilder::getEmpty();
10046 }
10047
10048 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10049 QualType T) {
10050 return DiagnosticBuilder::getEmpty();
10051 }
10052
10053 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10054 CXXConversionDecl *Conv,
10055 QualType ConvTy) {
10056 return DiagnosticBuilder::getEmpty();
10057 }
10058
10059 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10060 SourceLocation Loc,
10061 QualType T,
10062 QualType ConvTy) {
10063 return DiagnosticBuilder::getEmpty();
10064 }
10065 } ConvertDiagnoser;
10066
10067 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10068 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010069 }
10070 if (Converted.isInvalid())
10071 return Converted;
10072 E = Converted.take();
10073 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10074 return ExprError();
10075 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10076 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010077 if (!Diagnoser.Suppress)
10078 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010079 return ExprError();
10080 }
10081
Richard Smithdaaefc52011-12-14 23:32:26 +000010082 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10083 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +000010084 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010085 if (Result)
10086 *Result = E->EvaluateKnownConstInt(Context);
10087 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010088 }
10089
Anders Carlssone21555e2008-11-30 19:50:32 +000010090 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010091 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10092 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010093
Richard Smithdaaefc52011-12-14 23:32:26 +000010094 // Try to evaluate the expression, and produce diagnostics explaining why it's
10095 // not a constant expression as a side-effect.
10096 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10097 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10098
10099 // In C++11, we can rely on diagnostics being produced for any expression
10100 // which is not a constant expression. If no diagnostics were produced, then
10101 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010102 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010103 if (Result)
10104 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010105 return Owned(E);
10106 }
10107
10108 // If our only note is the usual "invalid subexpression" note, just point
10109 // the caret at its location rather than producing an essentially
10110 // redundant note.
10111 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10112 diag::note_invalid_subexpr_in_const_expr) {
10113 DiagLoc = Notes[0].first;
10114 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010115 }
10116
10117 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010118 if (!Diagnoser.Suppress) {
10119 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010120 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10121 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010122 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010123
Richard Smith282e7e62012-02-04 09:53:13 +000010124 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010125 }
10126
Douglas Gregorab41fe92012-05-04 22:38:52 +000010127 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010128 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10129 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010130
Anders Carlssone21555e2008-11-30 19:50:32 +000010131 if (Result)
10132 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010133 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010134}
Douglas Gregore0762c92009-06-19 23:52:42 +000010135
Eli Friedmanef331b72012-01-20 01:26:23 +000010136namespace {
10137 // Handle the case where we conclude a expression which we speculatively
10138 // considered to be unevaluated is actually evaluated.
10139 class TransformToPE : public TreeTransform<TransformToPE> {
10140 typedef TreeTransform<TransformToPE> BaseTransform;
10141
10142 public:
10143 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10144
10145 // Make sure we redo semantic analysis
10146 bool AlwaysRebuild() { return true; }
10147
Eli Friedman56ff2832012-02-06 23:29:57 +000010148 // Make sure we handle LabelStmts correctly.
10149 // FIXME: This does the right thing, but maybe we need a more general
10150 // fix to TreeTransform?
10151 StmtResult TransformLabelStmt(LabelStmt *S) {
10152 S->getDecl()->setStmt(0);
10153 return BaseTransform::TransformLabelStmt(S);
10154 }
10155
Eli Friedmanef331b72012-01-20 01:26:23 +000010156 // We need to special-case DeclRefExprs referring to FieldDecls which
10157 // are not part of a member pointer formation; normal TreeTransforming
10158 // doesn't catch this case because of the way we represent them in the AST.
10159 // FIXME: This is a bit ugly; is it really the best way to handle this
10160 // case?
10161 //
10162 // Error on DeclRefExprs referring to FieldDecls.
10163 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10164 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010165 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010166 return SemaRef.Diag(E->getLocation(),
10167 diag::err_invalid_non_static_member_use)
10168 << E->getDecl() << E->getSourceRange();
10169
10170 return BaseTransform::TransformDeclRefExpr(E);
10171 }
10172
10173 // Exception: filter out member pointer formation
10174 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10175 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10176 return E;
10177
10178 return BaseTransform::TransformUnaryOperator(E);
10179 }
10180
Douglas Gregore2c59132012-02-09 08:14:43 +000010181 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10182 // Lambdas never need to be transformed.
10183 return E;
10184 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010185 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010186}
10187
Eli Friedmanef331b72012-01-20 01:26:23 +000010188ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010189 assert(ExprEvalContexts.back().Context == Unevaluated &&
10190 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010191 ExprEvalContexts.back().Context =
10192 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10193 if (ExprEvalContexts.back().Context == Unevaluated)
10194 return E;
10195 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010196}
10197
Douglas Gregor2afce722009-11-26 00:44:06 +000010198void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010199Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010200 Decl *LambdaContextDecl,
10201 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010202 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010203 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010204 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010205 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010206 LambdaContextDecl,
10207 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010208 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010209 if (!MaybeODRUseExprs.empty())
10210 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010211}
10212
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010213void
10214Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10215 ReuseLambdaContextDecl_t,
10216 bool IsDecltype) {
10217 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10218 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10219}
10220
Richard Trieu67e29332011-08-02 04:35:43 +000010221void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010222 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010223
Douglas Gregore2c59132012-02-09 08:14:43 +000010224 if (!Rec.Lambdas.empty()) {
10225 if (Rec.Context == Unevaluated) {
10226 // C++11 [expr.prim.lambda]p2:
10227 // A lambda-expression shall not appear in an unevaluated operand
10228 // (Clause 5).
10229 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10230 Diag(Rec.Lambdas[I]->getLocStart(),
10231 diag::err_lambda_unevaluated_operand);
10232 } else {
10233 // Mark the capture expressions odr-used. This was deferred
10234 // during lambda expression creation.
10235 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10236 LambdaExpr *Lambda = Rec.Lambdas[I];
10237 for (LambdaExpr::capture_init_iterator
10238 C = Lambda->capture_init_begin(),
10239 CEnd = Lambda->capture_init_end();
10240 C != CEnd; ++C) {
10241 MarkDeclarationsReferencedInExpr(*C);
10242 }
10243 }
10244 }
10245 }
10246
Douglas Gregor2afce722009-11-26 00:44:06 +000010247 // When are coming out of an unevaluated context, clear out any
10248 // temporaries that we may have created as part of the evaluation of
10249 // the expression in that context: they aren't relevant because they
10250 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010251 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010252 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10253 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010254 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010255 CleanupVarDeclMarking();
10256 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010257 // Otherwise, merge the contexts together.
10258 } else {
10259 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010260 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10261 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010262 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010263
10264 // Pop the current expression evaluation context off the stack.
10265 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010266}
Douglas Gregore0762c92009-06-19 23:52:42 +000010267
John McCallf85e1932011-06-15 23:02:42 +000010268void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010269 ExprCleanupObjects.erase(
10270 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10271 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010272 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010273 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010274}
10275
Eli Friedman71b8fb52012-01-21 01:01:51 +000010276ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10277 if (!E->getType()->isVariablyModifiedType())
10278 return E;
10279 return TranformToPotentiallyEvaluated(E);
10280}
10281
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010282static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010283 // Do not mark anything as "used" within a dependent context; wait for
10284 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010285 if (SemaRef.CurContext->isDependentContext())
10286 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010287
Eli Friedman5f2987c2012-02-02 03:46:19 +000010288 switch (SemaRef.ExprEvalContexts.back().Context) {
10289 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010290 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010291 // (Depending on how you read the standard, we actually do need to do
10292 // something here for null pointer constants, but the standard's
10293 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010294 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010295
Eli Friedman5f2987c2012-02-02 03:46:19 +000010296 case Sema::ConstantEvaluated:
10297 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010298 // We are in a potentially evaluated expression (or a constant-expression
10299 // in C++03); we need to do implicit template instantiation, implicitly
10300 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010301 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010302
Eli Friedman5f2987c2012-02-02 03:46:19 +000010303 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010304 // Referenced declarations will only be used if the construct in the
10305 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010306 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010307 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010308 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010309}
10310
10311/// \brief Mark a function referenced, and check whether it is odr-used
10312/// (C++ [basic.def.odr]p2, C99 6.9p3)
10313void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10314 assert(Func && "No function?");
10315
10316 Func->setReferenced();
10317
Richard Smith57b9c4e2012-02-14 22:25:15 +000010318 // Don't mark this function as used multiple times, unless it's a constexpr
10319 // function which we need to instantiate.
10320 if (Func->isUsed(false) &&
10321 !(Func->isConstexpr() && !Func->getBody() &&
10322 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010323 return;
10324
10325 if (!IsPotentiallyEvaluatedContext(*this))
10326 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010327
Douglas Gregore0762c92009-06-19 23:52:42 +000010328 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010329 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010330 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010331 if (Constructor->isDefaultConstructor()) {
10332 if (Constructor->isTrivial())
10333 return;
10334 if (!Constructor->isUsed(false))
10335 DefineImplicitDefaultConstructor(Loc, Constructor);
10336 } else if (Constructor->isCopyConstructor()) {
10337 if (!Constructor->isUsed(false))
10338 DefineImplicitCopyConstructor(Loc, Constructor);
10339 } else if (Constructor->isMoveConstructor()) {
10340 if (!Constructor->isUsed(false))
10341 DefineImplicitMoveConstructor(Loc, Constructor);
10342 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010343 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010344
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010345 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010346 } else if (CXXDestructorDecl *Destructor =
10347 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010348 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10349 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010350 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010351 if (Destructor->isVirtual())
10352 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010353 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010354 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10355 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010356 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010357 if (!MethodDecl->isUsed(false)) {
10358 if (MethodDecl->isCopyAssignmentOperator())
10359 DefineImplicitCopyAssignment(Loc, MethodDecl);
10360 else
10361 DefineImplicitMoveAssignment(Loc, MethodDecl);
10362 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010363 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10364 MethodDecl->getParent()->isLambda()) {
10365 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10366 if (Conversion->isLambdaToBlockPointerConversion())
10367 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10368 else
10369 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010370 } else if (MethodDecl->isVirtual())
10371 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010372 }
John McCall15e310a2011-02-19 02:53:41 +000010373
Eli Friedman5f2987c2012-02-02 03:46:19 +000010374 // Recursive functions should be marked when used from another function.
10375 // FIXME: Is this really right?
10376 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010377
Richard Smithb9d0b762012-07-27 04:22:15 +000010378 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010379 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010380 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010381 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10382 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010383
Eli Friedman5f2987c2012-02-02 03:46:19 +000010384 // Implicit instantiation of function templates and member functions of
10385 // class templates.
10386 if (Func->isImplicitlyInstantiable()) {
10387 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010388 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010389 if (FunctionTemplateSpecializationInfo *SpecInfo
10390 = Func->getTemplateSpecializationInfo()) {
10391 if (SpecInfo->getPointOfInstantiation().isInvalid())
10392 SpecInfo->setPointOfInstantiation(Loc);
10393 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010394 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010395 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010396 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10397 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010398 } else if (MemberSpecializationInfo *MSInfo
10399 = Func->getMemberSpecializationInfo()) {
10400 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010401 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010402 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010403 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010404 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010405 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10406 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010407 }
Mike Stump1eb44332009-09-09 15:08:12 +000010408
Richard Smith57b9c4e2012-02-14 22:25:15 +000010409 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010410 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10411 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010412 PendingLocalImplicitInstantiations.push_back(
10413 std::make_pair(Func, PointOfInstantiation));
10414 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010415 // Do not defer instantiations of constexpr functions, to avoid the
10416 // expression evaluator needing to call back into Sema if it sees a
10417 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010418 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010419 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010420 PendingInstantiations.push_back(std::make_pair(Func,
10421 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010422 // Notify the consumer that a function was implicitly instantiated.
10423 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10424 }
John McCall15e310a2011-02-19 02:53:41 +000010425 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010426 } else {
10427 // Walk redefinitions, as some of them may be instantiable.
10428 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10429 e(Func->redecls_end()); i != e; ++i) {
10430 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10431 MarkFunctionReferenced(Loc, *i);
10432 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010433 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010434
10435 // Keep track of used but undefined functions.
10436 if (!Func->isPure() && !Func->hasBody() &&
10437 Func->getLinkage() != ExternalLinkage) {
10438 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10439 if (old.isInvalid()) old = Loc;
10440 }
10441
10442 Func->setUsed(true);
10443}
10444
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010445static void
10446diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10447 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010448 DeclContext *VarDC = var->getDeclContext();
10449
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010450 // If the parameter still belongs to the translation unit, then
10451 // we're actually just using one parameter in the declaration of
10452 // the next.
10453 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010454 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010455 return;
10456
Eli Friedman0a294222012-02-07 00:15:00 +000010457 // For C code, don't diagnose about capture if we're not actually in code
10458 // right now; it's impossible to write a non-constant expression outside of
10459 // function context, so we'll get other (more useful) diagnostics later.
10460 //
10461 // For C++, things get a bit more nasty... it would be nice to suppress this
10462 // diagnostic for certain cases like using a local variable in an array bound
10463 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010464 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010465 return;
10466
Eli Friedman0a294222012-02-07 00:15:00 +000010467 if (isa<CXXMethodDecl>(VarDC) &&
10468 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10469 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10470 << var->getIdentifier();
10471 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10472 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10473 << var->getIdentifier() << fn->getDeclName();
10474 } else if (isa<BlockDecl>(VarDC)) {
10475 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10476 << var->getIdentifier();
10477 } else {
10478 // FIXME: Is there any other context where a local variable can be
10479 // declared?
10480 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10481 << var->getIdentifier();
10482 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010483
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010484 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10485 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010486
10487 // FIXME: Add additional diagnostic info about class etc. which prevents
10488 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010489}
10490
Douglas Gregorf8af9822012-02-12 18:42:33 +000010491/// \brief Capture the given variable in the given lambda expression.
10492static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010493 VarDecl *Var, QualType FieldType,
10494 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010495 SourceLocation Loc,
10496 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010497 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010498
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010499 // Build the non-static data member.
10500 FieldDecl *Field
10501 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10502 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010503 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010504 Field->setImplicit(true);
10505 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010506 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010507
10508 // C++11 [expr.prim.lambda]p21:
10509 // When the lambda-expression is evaluated, the entities that
10510 // are captured by copy are used to direct-initialize each
10511 // corresponding non-static data member of the resulting closure
10512 // object. (For array members, the array elements are
10513 // direct-initialized in increasing subscript order.) These
10514 // initializations are performed in the (unspecified) order in
10515 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010516
Douglas Gregore2c59132012-02-09 08:14:43 +000010517 // Introduce a new evaluation context for the initialization, so
10518 // that temporaries introduced as part of the capture are retained
10519 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010520 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10521
Douglas Gregor73d90922012-02-10 09:26:04 +000010522 // C++ [expr.prim.labda]p12:
10523 // An entity captured by a lambda-expression is odr-used (3.2) in
10524 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010525 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10526 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010527 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010528 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010529
10530 // When the field has array type, create index variables for each
10531 // dimension of the array. We use these index variables to subscript
10532 // the source array, and other clients (e.g., CodeGen) will perform
10533 // the necessary iteration with these index variables.
10534 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010535 QualType BaseType = FieldType;
10536 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010537 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010538 while (const ConstantArrayType *Array
10539 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010540 // Create the iteration variable for this array index.
10541 IdentifierInfo *IterationVarName = 0;
10542 {
10543 SmallString<8> Str;
10544 llvm::raw_svector_ostream OS(Str);
10545 OS << "__i" << IndexVariables.size();
10546 IterationVarName = &S.Context.Idents.get(OS.str());
10547 }
10548 VarDecl *IterationVar
10549 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10550 IterationVarName, SizeType,
10551 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10552 SC_None, SC_None);
10553 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010554 LSI->ArrayIndexVars.push_back(IterationVar);
10555
Douglas Gregor18fe0842012-02-09 02:45:47 +000010556 // Create a reference to the iteration variable.
10557 ExprResult IterationVarRef
10558 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10559 assert(!IterationVarRef.isInvalid() &&
10560 "Reference to invented variable cannot fail!");
10561 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10562 assert(!IterationVarRef.isInvalid() &&
10563 "Conversion of invented variable cannot fail!");
10564
10565 // Subscript the array with this iteration variable.
10566 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10567 Ref, Loc, IterationVarRef.take(), Loc);
10568 if (Subscript.isInvalid()) {
10569 S.CleanupVarDeclMarking();
10570 S.DiscardCleanupsInEvaluationContext();
10571 S.PopExpressionEvaluationContext();
10572 return ExprError();
10573 }
10574
10575 Ref = Subscript.take();
10576 BaseType = Array->getElementType();
10577 }
10578
10579 // Construct the entity that we will be initializing. For an array, this
10580 // will be first element in the array, which may require several levels
10581 // of array-subscript entities.
10582 SmallVector<InitializedEntity, 4> Entities;
10583 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010584 Entities.push_back(
10585 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010586 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10587 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10588 0,
10589 Entities.back()));
10590
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010591 InitializationKind InitKind
10592 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010593 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010594 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010595 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010596 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010597
10598 // If this initialization requires any cleanups (e.g., due to a
10599 // default argument to a copy constructor), note that for the
10600 // lambda.
10601 if (S.ExprNeedsCleanups)
10602 LSI->ExprNeedsCleanups = true;
10603
10604 // Exit the expression evaluation context used for the capture.
10605 S.CleanupVarDeclMarking();
10606 S.DiscardCleanupsInEvaluationContext();
10607 S.PopExpressionEvaluationContext();
10608 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010609}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010610
Douglas Gregor999713e2012-02-18 09:37:24 +000010611bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10612 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10613 bool BuildAndDiagnose,
10614 QualType &CaptureType,
10615 QualType &DeclRefType) {
10616 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010617
Eli Friedmanb942cb22012-02-03 22:47:37 +000010618 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010619 if (Var->getDeclContext() == DC) return true;
10620 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010621
Douglas Gregorf8af9822012-02-12 18:42:33 +000010622 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010623
Douglas Gregor999713e2012-02-18 09:37:24 +000010624 // Walk up the stack to determine whether we can capture the variable,
10625 // performing the "simple" checks that don't depend on type. We stop when
10626 // we've either hit the declared scope of the variable or find an existing
10627 // capture of that variable.
10628 CaptureType = Var->getType();
10629 DeclRefType = CaptureType.getNonReferenceType();
10630 bool Explicit = (Kind != TryCapture_Implicit);
10631 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010632 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010633 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010634 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010635 DeclContext *ParentDC;
10636 if (isa<BlockDecl>(DC))
10637 ParentDC = DC->getParent();
10638 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010639 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010640 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10641 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010642 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010643 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010644 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010645 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010646 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010647
Eli Friedmanb942cb22012-02-03 22:47:37 +000010648 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010649 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010650
Eli Friedmanb942cb22012-02-03 22:47:37 +000010651 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010652 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010653 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010654 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010655
10656 // Retrieve the capture type for this variable.
10657 CaptureType = CSI->getCapture(Var).getCaptureType();
10658
10659 // Compute the type of an expression that refers to this variable.
10660 DeclRefType = CaptureType.getNonReferenceType();
10661
10662 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10663 if (Cap.isCopyCapture() &&
10664 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10665 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010666 break;
10667 }
10668
Douglas Gregorf8af9822012-02-12 18:42:33 +000010669 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010670 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010671
10672 // Lambdas are not allowed to capture unnamed variables
10673 // (e.g. anonymous unions).
10674 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10675 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010676 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010677 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010678 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10679 Diag(Var->getLocation(), diag::note_declared_at);
10680 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010681 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010682 }
10683
10684 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010685 if (Var->getType()->isVariablyModifiedType()) {
10686 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010687 if (IsBlock)
10688 Diag(Loc, diag::err_ref_vm_type);
10689 else
10690 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10691 Diag(Var->getLocation(), diag::note_previous_decl)
10692 << Var->getDeclName();
10693 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010694 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010695 }
10696
Eli Friedmanb942cb22012-02-03 22:47:37 +000010697 // Lambdas are not allowed to capture __block variables; they don't
10698 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010699 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010700 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010701 Diag(Loc, diag::err_lambda_capture_block)
10702 << Var->getDeclName();
10703 Diag(Var->getLocation(), diag::note_previous_decl)
10704 << Var->getDeclName();
10705 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010706 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010707 }
10708
Douglas Gregorf8af9822012-02-12 18:42:33 +000010709 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10710 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010711 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010712 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10713 Diag(Var->getLocation(), diag::note_previous_decl)
10714 << Var->getDeclName();
10715 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10716 diag::note_lambda_decl);
10717 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010718 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010719 }
10720
10721 FunctionScopesIndex--;
10722 DC = ParentDC;
10723 Explicit = false;
10724 } while (!Var->getDeclContext()->Equals(DC));
10725
Douglas Gregor999713e2012-02-18 09:37:24 +000010726 // Walk back down the scope stack, computing the type of the capture at
10727 // each step, checking type-specific requirements, and adding captures if
10728 // requested.
10729 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10730 ++I) {
10731 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010732
Douglas Gregor999713e2012-02-18 09:37:24 +000010733 // Compute the type of the capture and of a reference to the capture within
10734 // this scope.
10735 if (isa<BlockScopeInfo>(CSI)) {
10736 Expr *CopyExpr = 0;
10737 bool ByRef = false;
10738
10739 // Blocks are not allowed to capture arrays.
10740 if (CaptureType->isArrayType()) {
10741 if (BuildAndDiagnose) {
10742 Diag(Loc, diag::err_ref_array_type);
10743 Diag(Var->getLocation(), diag::note_previous_decl)
10744 << Var->getDeclName();
10745 }
10746 return true;
10747 }
10748
John McCall100c6492012-03-30 05:23:48 +000010749 // Forbid the block-capture of autoreleasing variables.
10750 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10751 if (BuildAndDiagnose) {
10752 Diag(Loc, diag::err_arc_autoreleasing_capture)
10753 << /*block*/ 0;
10754 Diag(Var->getLocation(), diag::note_previous_decl)
10755 << Var->getDeclName();
10756 }
10757 return true;
10758 }
10759
Douglas Gregor999713e2012-02-18 09:37:24 +000010760 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10761 // Block capture by reference does not change the capture or
10762 // declaration reference types.
10763 ByRef = true;
10764 } else {
10765 // Block capture by copy introduces 'const'.
10766 CaptureType = CaptureType.getNonReferenceType().withConst();
10767 DeclRefType = CaptureType;
10768
David Blaikie4e4d0842012-03-11 07:00:24 +000010769 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010770 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10771 // The capture logic needs the destructor, so make sure we mark it.
10772 // Usually this is unnecessary because most local variables have
10773 // their destructors marked at declaration time, but parameters are
10774 // an exception because it's technically only the call site that
10775 // actually requires the destructor.
10776 if (isa<ParmVarDecl>(Var))
10777 FinalizeVarWithDestructor(Var, Record);
10778
10779 // According to the blocks spec, the capture of a variable from
10780 // the stack requires a const copy constructor. This is not true
10781 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010782 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010783 DeclRefType.withConst(),
10784 VK_LValue, Loc);
10785 ExprResult Result
10786 = PerformCopyInitialization(
10787 InitializedEntity::InitializeBlock(Var->getLocation(),
10788 CaptureType, false),
10789 Loc, Owned(DeclRef));
10790
10791 // Build a full-expression copy expression if initialization
10792 // succeeded and used a non-trivial constructor. Recover from
10793 // errors by pretending that the copy isn't necessary.
10794 if (!Result.isInvalid() &&
10795 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10796 ->isTrivial()) {
10797 Result = MaybeCreateExprWithCleanups(Result);
10798 CopyExpr = Result.take();
10799 }
10800 }
10801 }
10802 }
10803
10804 // Actually capture the variable.
10805 if (BuildAndDiagnose)
10806 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10807 SourceLocation(), CaptureType, CopyExpr);
10808 Nested = true;
10809 continue;
10810 }
Douglas Gregor68932842012-02-18 05:51:20 +000010811
Douglas Gregor999713e2012-02-18 09:37:24 +000010812 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10813
10814 // Determine whether we are capturing by reference or by value.
10815 bool ByRef = false;
10816 if (I == N - 1 && Kind != TryCapture_Implicit) {
10817 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010818 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010819 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010820 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010821
10822 // Compute the type of the field that will capture this variable.
10823 if (ByRef) {
10824 // C++11 [expr.prim.lambda]p15:
10825 // An entity is captured by reference if it is implicitly or
10826 // explicitly captured but not captured by copy. It is
10827 // unspecified whether additional unnamed non-static data
10828 // members are declared in the closure type for entities
10829 // captured by reference.
10830 //
10831 // FIXME: It is not clear whether we want to build an lvalue reference
10832 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10833 // to do the former, while EDG does the latter. Core issue 1249 will
10834 // clarify, but for now we follow GCC because it's a more permissive and
10835 // easily defensible position.
10836 CaptureType = Context.getLValueReferenceType(DeclRefType);
10837 } else {
10838 // C++11 [expr.prim.lambda]p14:
10839 // For each entity captured by copy, an unnamed non-static
10840 // data member is declared in the closure type. The
10841 // declaration order of these members is unspecified. The type
10842 // of such a data member is the type of the corresponding
10843 // captured entity if the entity is not a reference to an
10844 // object, or the referenced type otherwise. [Note: If the
10845 // captured entity is a reference to a function, the
10846 // corresponding data member is also a reference to a
10847 // function. - end note ]
10848 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10849 if (!RefType->getPointeeType()->isFunctionType())
10850 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010851 }
John McCall100c6492012-03-30 05:23:48 +000010852
10853 // Forbid the lambda copy-capture of autoreleasing variables.
10854 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10855 if (BuildAndDiagnose) {
10856 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10857 Diag(Var->getLocation(), diag::note_previous_decl)
10858 << Var->getDeclName();
10859 }
10860 return true;
10861 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010862 }
10863
Douglas Gregor999713e2012-02-18 09:37:24 +000010864 // Capture this variable in the lambda.
10865 Expr *CopyExpr = 0;
10866 if (BuildAndDiagnose) {
10867 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010868 DeclRefType, Loc,
10869 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010870 if (!Result.isInvalid())
10871 CopyExpr = Result.take();
10872 }
10873
10874 // Compute the type of a reference to this captured variable.
10875 if (ByRef)
10876 DeclRefType = CaptureType.getNonReferenceType();
10877 else {
10878 // C++ [expr.prim.lambda]p5:
10879 // The closure type for a lambda-expression has a public inline
10880 // function call operator [...]. This function call operator is
10881 // declared const (9.3.1) if and only if the lambda-expression’s
10882 // parameter-declaration-clause is not followed by mutable.
10883 DeclRefType = CaptureType.getNonReferenceType();
10884 if (!LSI->Mutable && !CaptureType->isReferenceType())
10885 DeclRefType.addConst();
10886 }
10887
10888 // Add the capture.
10889 if (BuildAndDiagnose)
10890 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10891 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010892 Nested = true;
10893 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010894
10895 return false;
10896}
10897
10898bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10899 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10900 QualType CaptureType;
10901 QualType DeclRefType;
10902 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10903 /*BuildAndDiagnose=*/true, CaptureType,
10904 DeclRefType);
10905}
10906
10907QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10908 QualType CaptureType;
10909 QualType DeclRefType;
10910
10911 // Determine whether we can capture this variable.
10912 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10913 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10914 return QualType();
10915
10916 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010917}
10918
Eli Friedmand2cce132012-02-02 23:15:15 +000010919static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10920 SourceLocation Loc) {
10921 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010922 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010923 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010924 Var->getLinkage() != ExternalLinkage &&
10925 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010926 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10927 if (old.isInvalid()) old = Loc;
10928 }
10929
Douglas Gregor999713e2012-02-18 09:37:24 +000010930 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010931
Eli Friedmand2cce132012-02-02 23:15:15 +000010932 Var->setUsed(true);
10933}
10934
10935void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10936 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10937 // an object that satisfies the requirements for appearing in a
10938 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10939 // is immediately applied." This function handles the lvalue-to-rvalue
10940 // conversion part.
10941 MaybeODRUseExprs.erase(E->IgnoreParens());
10942}
10943
Eli Friedmanac626012012-02-29 03:16:56 +000010944ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10945 if (!Res.isUsable())
10946 return Res;
10947
10948 // If a constant-expression is a reference to a variable where we delay
10949 // deciding whether it is an odr-use, just assume we will apply the
10950 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10951 // (a non-type template argument), we have special handling anyway.
10952 UpdateMarkingForLValueToRValue(Res.get());
10953 return Res;
10954}
10955
Eli Friedmand2cce132012-02-02 23:15:15 +000010956void Sema::CleanupVarDeclMarking() {
10957 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10958 e = MaybeODRUseExprs.end();
10959 i != e; ++i) {
10960 VarDecl *Var;
10961 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010962 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010963 Var = cast<VarDecl>(DRE->getDecl());
10964 Loc = DRE->getLocation();
10965 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10966 Var = cast<VarDecl>(ME->getMemberDecl());
10967 Loc = ME->getMemberLoc();
10968 } else {
10969 llvm_unreachable("Unexpcted expression");
10970 }
10971
10972 MarkVarDeclODRUsed(*this, Var, Loc);
10973 }
10974
10975 MaybeODRUseExprs.clear();
10976}
10977
10978// Mark a VarDecl referenced, and perform the necessary handling to compute
10979// odr-uses.
10980static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10981 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010982 Var->setReferenced();
10983
Eli Friedmand2cce132012-02-02 23:15:15 +000010984 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010985 return;
10986
10987 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010988 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010989 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10990 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010991 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10992 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010993 (!AlreadyInstantiated ||
10994 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010995 if (!AlreadyInstantiated) {
10996 // This is a modification of an existing AST node. Notify listeners.
10997 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10998 L->StaticDataMemberInstantiated(Var);
10999 MSInfo->setPointOfInstantiation(Loc);
11000 }
11001 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011002 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011003 // Do not defer instantiations of variables which could be used in a
11004 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011005 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011006 else
Richard Smith37ce0102012-02-15 02:42:50 +000011007 SemaRef.PendingInstantiations.push_back(
11008 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011009 }
11010 }
11011
Eli Friedmand2cce132012-02-02 23:15:15 +000011012 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11013 // an object that satisfies the requirements for appearing in a
11014 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11015 // is immediately applied." We check the first part here, and
11016 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11017 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000011018 // C++03 depends on whether we get the C++03 version correct. This does not
11019 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011020 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000011021 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011022 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000011023 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
11024 SemaRef.MaybeODRUseExprs.insert(E);
11025 else
11026 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11027}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011028
Eli Friedmand2cce132012-02-02 23:15:15 +000011029/// \brief Mark a variable referenced, and check whether it is odr-used
11030/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11031/// used directly for normal expressions referring to VarDecl.
11032void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11033 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011034}
11035
11036static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11037 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011038 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11039 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11040 return;
11041 }
11042
Eli Friedman5f2987c2012-02-02 03:46:19 +000011043 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011044
11045 // If this is a call to a method via a cast, also mark the method in the
11046 // derived class used in case codegen can devirtualize the call.
11047 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11048 if (!ME)
11049 return;
11050 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11051 if (!MD)
11052 return;
11053 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011054 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011055 if (!MostDerivedClassDecl)
11056 return;
11057 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011058 if (!DM)
11059 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011060 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011061}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011062
Eli Friedman5f2987c2012-02-02 03:46:19 +000011063/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11064void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11065 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11066}
11067
11068/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11069void Sema::MarkMemberReferenced(MemberExpr *E) {
11070 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11071}
11072
Douglas Gregor73d90922012-02-10 09:26:04 +000011073/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011074/// marks the declaration referenced, and performs odr-use checking for functions
11075/// and variables. This method should not be used when building an normal
11076/// expression which refers to a variable.
11077void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11078 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11079 MarkVariableReferenced(Loc, VD);
11080 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11081 MarkFunctionReferenced(Loc, FD);
11082 else
11083 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011084}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011085
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011086namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011087 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011088 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011089 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011090 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11091 Sema &S;
11092 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011093
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011094 public:
11095 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011096
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011097 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011098
11099 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11100 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011101 };
11102}
11103
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011104bool MarkReferencedDecls::TraverseTemplateArgument(
11105 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011106 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011107 if (Decl *D = Arg.getAsDecl())
11108 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011109 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011110
11111 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011112}
11113
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011114bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011115 if (ClassTemplateSpecializationDecl *Spec
11116 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11117 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011118 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011119 }
11120
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011121 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011122}
11123
11124void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11125 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011126 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011127}
11128
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011129namespace {
11130 /// \brief Helper class that marks all of the declarations referenced by
11131 /// potentially-evaluated subexpressions as "referenced".
11132 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11133 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011134 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011135
11136 public:
11137 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11138
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011139 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11140 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011141
11142 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011143 // If we were asked not to visit local variables, don't.
11144 if (SkipLocalVariables) {
11145 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11146 if (VD->hasLocalStorage())
11147 return;
11148 }
11149
Eli Friedman5f2987c2012-02-02 03:46:19 +000011150 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011151 }
11152
11153 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011154 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011155 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011156 }
11157
John McCall80ee6e82011-11-10 05:35:25 +000011158 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011159 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011160 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11161 Visit(E->getSubExpr());
11162 }
11163
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011164 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011165 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011166 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011167 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011168 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011169 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011170 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011171
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011172 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11173 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011174 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011175 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11176 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11177 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011178 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011179 S.LookupDestructor(Record));
11180 }
11181
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011182 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011183 }
11184
11185 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011186 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011187 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011188 }
11189
Douglas Gregor102ff972010-10-19 17:17:35 +000011190 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11191 Visit(E->getExpr());
11192 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011193
11194 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11195 Inherited::VisitImplicitCastExpr(E);
11196
11197 if (E->getCastKind() == CK_LValueToRValue)
11198 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11199 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011200 };
11201}
11202
11203/// \brief Mark any declarations that appear within this expression or any
11204/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011205///
11206/// \param SkipLocalVariables If true, don't mark local variables as
11207/// 'referenced'.
11208void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11209 bool SkipLocalVariables) {
11210 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011211}
11212
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011213/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11214/// of the program being compiled.
11215///
11216/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011217/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011218/// possibility that the code will actually be executable. Code in sizeof()
11219/// expressions, code used only during overload resolution, etc., are not
11220/// potentially evaluated. This routine will suppress such diagnostics or,
11221/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011222/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011223/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011224///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011225/// This routine should be used for all diagnostics that describe the run-time
11226/// behavior of a program, such as passing a non-POD value through an ellipsis.
11227/// Failure to do so will likely result in spurious diagnostics or failures
11228/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011229bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011230 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011231 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011232 case Unevaluated:
11233 // The argument will never be evaluated, so don't complain.
11234 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011235
Richard Smithf6702a32011-12-20 02:08:33 +000011236 case ConstantEvaluated:
11237 // Relevant diagnostics should be produced by constant evaluation.
11238 break;
11239
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011240 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011241 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011242 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011243 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011244 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011245 }
11246 else
11247 Diag(Loc, PD);
11248
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011249 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011250 }
11251
11252 return false;
11253}
11254
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011255bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11256 CallExpr *CE, FunctionDecl *FD) {
11257 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11258 return false;
11259
Richard Smith76f3f692012-02-22 02:04:18 +000011260 // If we're inside a decltype's expression, don't check for a valid return
11261 // type or construct temporaries until we know whether this is the last call.
11262 if (ExprEvalContexts.back().IsDecltype) {
11263 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11264 return false;
11265 }
11266
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011267 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011268 FunctionDecl *FD;
11269 CallExpr *CE;
11270
11271 public:
11272 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11273 : FD(FD), CE(CE) { }
11274
11275 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11276 if (!FD) {
11277 S.Diag(Loc, diag::err_call_incomplete_return)
11278 << T << CE->getSourceRange();
11279 return;
11280 }
11281
11282 S.Diag(Loc, diag::err_call_function_incomplete_return)
11283 << CE->getSourceRange() << FD->getDeclName() << T;
11284 S.Diag(FD->getLocation(),
11285 diag::note_function_with_incomplete_return_type_declared_here)
11286 << FD->getDeclName();
11287 }
11288 } Diagnoser(FD, CE);
11289
11290 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011291 return true;
11292
11293 return false;
11294}
11295
Douglas Gregor92c3a042011-01-19 16:50:08 +000011296// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011297// will prevent this condition from triggering, which is what we want.
11298void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11299 SourceLocation Loc;
11300
John McCalla52ef082009-11-11 02:41:58 +000011301 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011302 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011303
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011304 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011305 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011306 return;
11307
Douglas Gregor92c3a042011-01-19 16:50:08 +000011308 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11309
John McCallc8d8ac52009-11-12 00:06:05 +000011310 // Greylist some idioms by putting them into a warning subcategory.
11311 if (ObjCMessageExpr *ME
11312 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11313 Selector Sel = ME->getSelector();
11314
John McCallc8d8ac52009-11-12 00:06:05 +000011315 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011316 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011317 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11318
11319 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011320 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011321 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11322 }
John McCalla52ef082009-11-11 02:41:58 +000011323
John McCall5a881bb2009-10-12 21:59:07 +000011324 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011325 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011326 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011327 return;
11328
Douglas Gregor92c3a042011-01-19 16:50:08 +000011329 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011330 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011331 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11332 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11333 else {
John McCall5a881bb2009-10-12 21:59:07 +000011334 // Not an assignment.
11335 return;
11336 }
11337
Douglas Gregor55b38842010-04-14 16:09:52 +000011338 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011339
Daniel Dunbar96a00142012-03-09 18:35:03 +000011340 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011341 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11342 Diag(Loc, diag::note_condition_assign_silence)
11343 << FixItHint::CreateInsertion(Open, "(")
11344 << FixItHint::CreateInsertion(Close, ")");
11345
Douglas Gregor92c3a042011-01-19 16:50:08 +000011346 if (IsOrAssign)
11347 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11348 << FixItHint::CreateReplacement(Loc, "!=");
11349 else
11350 Diag(Loc, diag::note_condition_assign_to_comparison)
11351 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011352}
11353
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011354/// \brief Redundant parentheses over an equality comparison can indicate
11355/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011356void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011357 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011358 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011359 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11360 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011361 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011362 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011363 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011364
Richard Trieuccd891a2011-09-09 01:45:06 +000011365 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011366
11367 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011368 if (opE->getOpcode() == BO_EQ &&
11369 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11370 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011371 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011372
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011373 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011374 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011375 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011376 << FixItHint::CreateRemoval(ParenERange.getBegin())
11377 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011378 Diag(Loc, diag::note_equality_comparison_to_assign)
11379 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011380 }
11381}
11382
John Wiegley429bb272011-04-08 18:41:53 +000011383ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011384 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011385 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11386 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011387
John McCall864c0412011-04-26 20:42:42 +000011388 ExprResult result = CheckPlaceholderExpr(E);
11389 if (result.isInvalid()) return ExprError();
11390 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011391
John McCall864c0412011-04-26 20:42:42 +000011392 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011393 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011394 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11395
John Wiegley429bb272011-04-08 18:41:53 +000011396 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11397 if (ERes.isInvalid())
11398 return ExprError();
11399 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011400
11401 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011402 if (!T->isScalarType()) { // C99 6.8.4.1p1
11403 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11404 << T << E->getSourceRange();
11405 return ExprError();
11406 }
John McCall5a881bb2009-10-12 21:59:07 +000011407 }
11408
John Wiegley429bb272011-04-08 18:41:53 +000011409 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011410}
Douglas Gregor586596f2010-05-06 17:25:47 +000011411
John McCall60d7b3a2010-08-24 06:29:42 +000011412ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011413 Expr *SubExpr) {
11414 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011415 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011416
Richard Trieuccd891a2011-09-09 01:45:06 +000011417 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011418}
John McCall2a984ca2010-10-12 00:20:44 +000011419
John McCall1de4d4e2011-04-07 08:22:57 +000011420namespace {
John McCall755d8492011-04-12 00:42:48 +000011421 /// A visitor for rebuilding a call to an __unknown_any expression
11422 /// to have an appropriate type.
11423 struct RebuildUnknownAnyFunction
11424 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11425
11426 Sema &S;
11427
11428 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11429
11430 ExprResult VisitStmt(Stmt *S) {
11431 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011432 }
11433
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011434 ExprResult VisitExpr(Expr *E) {
11435 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11436 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011437 return ExprError();
11438 }
11439
11440 /// Rebuild an expression which simply semantically wraps another
11441 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011442 template <class T> ExprResult rebuildSugarExpr(T *E) {
11443 ExprResult SubResult = Visit(E->getSubExpr());
11444 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011445
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011446 Expr *SubExpr = SubResult.take();
11447 E->setSubExpr(SubExpr);
11448 E->setType(SubExpr->getType());
11449 E->setValueKind(SubExpr->getValueKind());
11450 assert(E->getObjectKind() == OK_Ordinary);
11451 return E;
John McCall755d8492011-04-12 00:42:48 +000011452 }
11453
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011454 ExprResult VisitParenExpr(ParenExpr *E) {
11455 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011456 }
11457
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011458 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11459 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011460 }
11461
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011462 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11463 ExprResult SubResult = Visit(E->getSubExpr());
11464 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011465
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011466 Expr *SubExpr = SubResult.take();
11467 E->setSubExpr(SubExpr);
11468 E->setType(S.Context.getPointerType(SubExpr->getType()));
11469 assert(E->getValueKind() == VK_RValue);
11470 assert(E->getObjectKind() == OK_Ordinary);
11471 return E;
John McCall755d8492011-04-12 00:42:48 +000011472 }
11473
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011474 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11475 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011476
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011477 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011478
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011479 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011480 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011481 !(isa<CXXMethodDecl>(VD) &&
11482 cast<CXXMethodDecl>(VD)->isInstance()))
11483 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011484
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011485 return E;
John McCall755d8492011-04-12 00:42:48 +000011486 }
11487
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011488 ExprResult VisitMemberExpr(MemberExpr *E) {
11489 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011490 }
11491
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011492 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11493 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011494 }
11495 };
11496}
11497
11498/// Given a function expression of unknown-any type, try to rebuild it
11499/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011500static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11501 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11502 if (Result.isInvalid()) return ExprError();
11503 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011504}
11505
11506namespace {
John McCall379b5152011-04-11 07:02:50 +000011507 /// A visitor for rebuilding an expression of type __unknown_anytype
11508 /// into one which resolves the type directly on the referring
11509 /// expression. Strict preservation of the original source
11510 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011511 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011512 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011513
11514 Sema &S;
11515
11516 /// The current destination type.
11517 QualType DestType;
11518
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011519 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11520 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011521
John McCalla5fc4722011-04-09 22:50:59 +000011522 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011523 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011524 }
11525
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011526 ExprResult VisitExpr(Expr *E) {
11527 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11528 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011529 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011530 }
11531
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011532 ExprResult VisitCallExpr(CallExpr *E);
11533 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011534
John McCalla5fc4722011-04-09 22:50:59 +000011535 /// Rebuild an expression which simply semantically wraps another
11536 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011537 template <class T> ExprResult rebuildSugarExpr(T *E) {
11538 ExprResult SubResult = Visit(E->getSubExpr());
11539 if (SubResult.isInvalid()) return ExprError();
11540 Expr *SubExpr = SubResult.take();
11541 E->setSubExpr(SubExpr);
11542 E->setType(SubExpr->getType());
11543 E->setValueKind(SubExpr->getValueKind());
11544 assert(E->getObjectKind() == OK_Ordinary);
11545 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011546 }
John McCall1de4d4e2011-04-07 08:22:57 +000011547
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011548 ExprResult VisitParenExpr(ParenExpr *E) {
11549 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011550 }
11551
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011552 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11553 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011554 }
11555
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011556 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11557 const PointerType *Ptr = DestType->getAs<PointerType>();
11558 if (!Ptr) {
11559 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11560 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011561 return ExprError();
11562 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011563 assert(E->getValueKind() == VK_RValue);
11564 assert(E->getObjectKind() == OK_Ordinary);
11565 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011566
11567 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011568 DestType = Ptr->getPointeeType();
11569 ExprResult SubResult = Visit(E->getSubExpr());
11570 if (SubResult.isInvalid()) return ExprError();
11571 E->setSubExpr(SubResult.take());
11572 return E;
John McCall755d8492011-04-12 00:42:48 +000011573 }
11574
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011575 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011576
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011577 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011578
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011579 ExprResult VisitMemberExpr(MemberExpr *E) {
11580 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011581 }
John McCalla5fc4722011-04-09 22:50:59 +000011582
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011583 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11584 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011585 }
11586 };
11587}
11588
John McCall379b5152011-04-11 07:02:50 +000011589/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011590ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11591 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011592
11593 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011594 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011595 FK_FunctionPointer,
11596 FK_BlockPointer
11597 };
11598
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011599 FnKind Kind;
11600 QualType CalleeType = CalleeExpr->getType();
11601 if (CalleeType == S.Context.BoundMemberTy) {
11602 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11603 Kind = FK_MemberFunction;
11604 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11605 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11606 CalleeType = Ptr->getPointeeType();
11607 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011608 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011609 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11610 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011611 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011612 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011613
11614 // Verify that this is a legal result type of a function.
11615 if (DestType->isArrayType() || DestType->isFunctionType()) {
11616 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011617 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011618 diagID = diag::err_block_returning_array_function;
11619
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011620 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011621 << DestType->isFunctionType() << DestType;
11622 return ExprError();
11623 }
11624
11625 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011626 E->setType(DestType.getNonLValueExprType(S.Context));
11627 E->setValueKind(Expr::getValueKindForType(DestType));
11628 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011629
11630 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011631 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011632 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011633 Proto->arg_type_begin(),
11634 Proto->getNumArgs(),
11635 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011636 else
11637 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011638 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011639
11640 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011641 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011642 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011643 // Nothing to do.
11644 break;
11645
11646 case FK_FunctionPointer:
11647 DestType = S.Context.getPointerType(DestType);
11648 break;
11649
11650 case FK_BlockPointer:
11651 DestType = S.Context.getBlockPointerType(DestType);
11652 break;
11653 }
11654
11655 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011656 ExprResult CalleeResult = Visit(CalleeExpr);
11657 if (!CalleeResult.isUsable()) return ExprError();
11658 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011659
11660 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011661 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011662}
11663
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011664ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011665 // Verify that this is a legal result type of a call.
11666 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011667 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011668 << DestType->isFunctionType() << DestType;
11669 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011670 }
11671
John McCall48218c62011-07-13 17:56:40 +000011672 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011673 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11674 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11675 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011676 }
John McCall755d8492011-04-12 00:42:48 +000011677
John McCall379b5152011-04-11 07:02:50 +000011678 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011679 E->setType(DestType.getNonReferenceType());
11680 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011681
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011682 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011683}
11684
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011685ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011686 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011687 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011688 assert(E->getValueKind() == VK_RValue);
11689 assert(E->getObjectKind() == OK_Ordinary);
11690
11691 E->setType(DestType);
11692
11693 // Rebuild the sub-expression as the pointee (function) type.
11694 DestType = DestType->castAs<PointerType>()->getPointeeType();
11695
11696 ExprResult Result = Visit(E->getSubExpr());
11697 if (!Result.isUsable()) return ExprError();
11698
11699 E->setSubExpr(Result.take());
11700 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011701 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011702 assert(E->getValueKind() == VK_RValue);
11703 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011704
Sean Callanance9c8312012-03-06 21:34:12 +000011705 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011706
Sean Callanance9c8312012-03-06 21:34:12 +000011707 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011708
Sean Callanance9c8312012-03-06 21:34:12 +000011709 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11710 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011711
Sean Callanance9c8312012-03-06 21:34:12 +000011712 ExprResult Result = Visit(E->getSubExpr());
11713 if (!Result.isUsable()) return ExprError();
11714
11715 E->setSubExpr(Result.take());
11716 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011717 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011718 llvm_unreachable("Unhandled cast type!");
11719 }
John McCall379b5152011-04-11 07:02:50 +000011720}
11721
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011722ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11723 ExprValueKind ValueKind = VK_LValue;
11724 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011725
11726 // We know how to make this work for certain kinds of decls:
11727
11728 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11730 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11731 DestType = Ptr->getPointeeType();
11732 ExprResult Result = resolveDecl(E, VD);
11733 if (Result.isInvalid()) return ExprError();
11734 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011735 CK_FunctionToPointerDecay, VK_RValue);
11736 }
11737
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011738 if (!Type->isFunctionType()) {
11739 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11740 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011741 return ExprError();
11742 }
John McCall379b5152011-04-11 07:02:50 +000011743
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011744 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11745 if (MD->isInstance()) {
11746 ValueKind = VK_RValue;
11747 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011748 }
11749
John McCall379b5152011-04-11 07:02:50 +000011750 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011751 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011752 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011753
11754 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011755 } else if (isa<VarDecl>(VD)) {
11756 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11757 Type = RefTy->getPointeeType();
11758 } else if (Type->isFunctionType()) {
11759 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11760 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011761 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011762 }
11763
11764 // - nothing else
11765 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011766 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11767 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011768 return ExprError();
11769 }
11770
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011771 VD->setType(DestType);
11772 E->setType(Type);
11773 E->setValueKind(ValueKind);
11774 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011775}
11776
John McCall1de4d4e2011-04-07 08:22:57 +000011777/// Check a cast of an unknown-any type. We intentionally only
11778/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011779ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11780 Expr *CastExpr, CastKind &CastKind,
11781 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011782 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011783 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011784 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011785
Richard Trieuccd891a2011-09-09 01:45:06 +000011786 CastExpr = result.take();
11787 VK = CastExpr->getValueKind();
11788 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011789
Richard Trieuccd891a2011-09-09 01:45:06 +000011790 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011791}
11792
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011793ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11794 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11795}
11796
Richard Trieuccd891a2011-09-09 01:45:06 +000011797static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11798 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011799 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011800 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011801 E = E->IgnoreParenImpCasts();
11802 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11803 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011804 diagID = diag::err_uncasted_call_of_unknown_any;
11805 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011806 break;
John McCall379b5152011-04-11 07:02:50 +000011807 }
John McCall1de4d4e2011-04-07 08:22:57 +000011808 }
11809
John McCall379b5152011-04-11 07:02:50 +000011810 SourceLocation loc;
11811 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011812 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011813 loc = ref->getLocation();
11814 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011815 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011816 loc = mem->getMemberLoc();
11817 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011818 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011819 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011820 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011821 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011822 if (!d) {
11823 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11824 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11825 << orig->getSourceRange();
11826 return ExprError();
11827 }
John McCall379b5152011-04-11 07:02:50 +000011828 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011829 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11830 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011831 return ExprError();
11832 }
11833
11834 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011835
11836 // Never recoverable.
11837 return ExprError();
11838}
11839
John McCall2a984ca2010-10-12 00:20:44 +000011840/// Check for operands with placeholder types and complain if found.
11841/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011842ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011843 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11844 if (!placeholderType) return Owned(E);
11845
11846 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011847
John McCall1de4d4e2011-04-07 08:22:57 +000011848 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011849 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011850 // Try to resolve a single function template specialization.
11851 // This is obligatory.
11852 ExprResult result = Owned(E);
11853 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11854 return result;
11855
11856 // If that failed, try to recover with a call.
11857 } else {
11858 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11859 /*complain*/ true);
11860 return result;
11861 }
11862 }
John McCall1de4d4e2011-04-07 08:22:57 +000011863
John McCall864c0412011-04-26 20:42:42 +000011864 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011865 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011866 ExprResult result = Owned(E);
11867 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11868 /*complain*/ true);
11869 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011870 }
11871
11872 // ARC unbridged casts.
11873 case BuiltinType::ARCUnbridgedCast: {
11874 Expr *realCast = stripARCUnbridgedCast(E);
11875 diagnoseARCUnbridgedCast(realCast);
11876 return Owned(realCast);
11877 }
John McCall864c0412011-04-26 20:42:42 +000011878
John McCall1de4d4e2011-04-07 08:22:57 +000011879 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011880 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011881 return diagnoseUnknownAnyExpr(*this, E);
11882
John McCall3c3b7f92011-10-25 17:37:35 +000011883 // Pseudo-objects.
11884 case BuiltinType::PseudoObject:
11885 return checkPseudoObjectRValue(E);
11886
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011887 case BuiltinType::BuiltinFn:
11888 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11889 return ExprError();
11890
John McCalle0a22d02011-10-18 21:02:43 +000011891 // Everything else should be impossible.
11892#define BUILTIN_TYPE(Id, SingletonId) \
11893 case BuiltinType::Id:
11894#define PLACEHOLDER_TYPE(Id, SingletonId)
11895#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011896 break;
11897 }
11898
11899 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011900}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011901
Richard Trieuccd891a2011-09-09 01:45:06 +000011902bool Sema::CheckCaseExpression(Expr *E) {
11903 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011904 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011905 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11906 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011907 return false;
11908}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011909
11910/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11911ExprResult
11912Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11913 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11914 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011915 QualType BoolT = Context.ObjCBuiltinBoolTy;
11916 if (!Context.getBOOLDecl()) {
11917 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11918 Sema::LookupOrdinaryName);
11919 if (LookupName(Result, getCurScope())) {
11920 NamedDecl *ND = Result.getFoundDecl();
11921 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11922 Context.setBOOLDecl(TD);
11923 }
11924 }
11925 if (Context.getBOOLDecl())
11926 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011927 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011928 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011929}