blob: 96196e06931641cd56bb389c220c0a34a96759b8 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "clang/Sema/DelayedDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000036#include "clang/Sema/Designator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
John McCall19510852010-08-20 18:27:03 +000040#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000041#include "clang/Sema/ScopeInfo.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000045using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000046
Sebastian Redl14b0c192011-09-24 17:48:00 +000047/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50 // See if this is an auto-typed variable whose initializer we are parsing.
51 if (ParsingInitForAutoVars.count(D))
52 return false;
53
54 // See if this is a deleted function.
55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56 if (FD->isDeleted())
57 return false;
58 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000059
60 // See if this function is unavailable.
61 if (D->getAvailability() == AR_Unavailable &&
62 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
63 return false;
64
Sebastian Redl14b0c192011-09-24 17:48:00 +000065 return true;
66}
David Chisnall0f436562009-08-17 16:35:33 +000067
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000068static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69 // Warn if this is used but marked unused.
70 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000071 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000072 if (!DC->hasAttr<UnusedAttr>())
73 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
74 }
75}
76
Ted Kremenekd6cf9122012-02-10 02:45:47 +000077static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000078 NamedDecl *D, SourceLocation Loc,
79 const ObjCInterfaceDecl *UnknownObjCClass) {
80 // See if this declaration is unavailable or deprecated.
81 std::string Message;
82 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000083 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84 if (Result == AR_Available) {
85 const DeclContext *DC = ECD->getDeclContext();
86 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87 Result = TheEnumDecl->getAvailability(&Message);
88 }
Jordan Rose04bec392012-10-10 16:42:54 +000089
Fariborz Jahanianfd090882012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000091 if (Result == AR_Deprecated || Result == AR_Unavailable) {
92 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94 AvailabilityResult PDeclResult = PD->getAvailability(0);
95 if (PDeclResult == Result)
96 ObjCPDecl = PD;
97 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000098 }
Jordan Rose04bec392012-10-10 16:42:54 +000099 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000100
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000101 switch (Result) {
102 case AR_Available:
103 case AR_NotYetIntroduced:
104 break;
105
106 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000107 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000108 break;
109
110 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000111 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000112 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000113 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000114 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000115 if (ObjCPDecl)
116 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117 << ObjCPDecl->getDeclName() << 1;
118 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000119 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000120 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000121 << D->getDeclName();
122 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000123 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000124 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000125 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000126 S.Diag(D->getLocation(), diag::note_unavailable_here)
127 << isa<FunctionDecl>(D) << false;
128 if (ObjCPDecl)
129 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000131 }
132 break;
133 }
134 return Result;
135}
136
Richard Smith6c4c36c2012-03-30 20:53:28 +0000137/// \brief Emit a note explaining that this function is deleted or unavailable.
138void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
140
Richard Smith5bdaac52012-04-02 20:59:25 +0000141 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142 // If the method was explicitly defaulted, point at that declaration.
143 if (!Method->isImplicit())
144 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
145
146 // Try to diagnose why this special member function was implicitly
147 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000148 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000149 if (CSM != CXXInvalid)
150 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
151
152 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000153 }
154
155 Diag(Decl->getLocation(), diag::note_unavailable_here)
156 << 1 << Decl->isDeleted();
157}
158
Jordan Rose0eb3f452012-06-18 22:09:19 +0000159/// \brief Determine whether a FunctionDecl was ever declared with an
160/// explicit storage class.
161static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163 E = D->redecls_end();
164 I != E; ++I) {
165 if (I->getStorageClassAsWritten() != SC_None)
166 return true;
167 }
168 return false;
169}
170
171/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000172/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000175/// in many cases it will not behave correctly. This is not enabled in C++ mode
176/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177/// and so while there may still be user mistakes, most of the time we can't
178/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000179static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
180 const NamedDecl *D,
181 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000182 // This is disabled under C++; there are too many ways for this to fire in
183 // contexts where the warning is a false positive, or where it is technically
184 // correct but benign.
185 if (S.getLangOpts().CPlusPlus)
186 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000187
188 // Check if this is an inlined function or method.
189 FunctionDecl *Current = S.getCurFunctionDecl();
190 if (!Current)
191 return;
192 if (!Current->isInlined())
193 return;
194 if (Current->getLinkage() != ExternalLinkage)
195 return;
196
197 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000198 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000199 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000200
Jordan Rose05233272012-06-21 05:54:50 +0000201 // Downgrade from ExtWarn to Extension if
202 // (1) the supposedly external inline function is in the main file,
203 // and probably won't be included anywhere else.
204 // (2) the thing we're referencing is a pure function.
205 // (3) the thing we're referencing is another inline function.
206 // This last can give us false negatives, but it's better than warning on
207 // wrappers for simple C library functions.
208 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210 if (!DowngradeWarning && UsedFn)
211 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
212
213 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214 : diag::warn_internal_in_extern_inline)
215 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000216
217 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000218 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000219 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
220 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
221 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224
225 S.Diag(D->getCanonicalDecl()->getLocation(),
226 diag::note_internal_decl_declared_here)
227 << D;
228}
229
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000230/// \brief Determine whether the use of this declaration is valid, and
231/// emit any corresponding diagnostics.
232///
233/// This routine diagnoses various problems with referencing
234/// declarations that can occur when using a declaration. For example,
235/// it might warn if a deprecated or unavailable declaration is being
236/// used, or produce an error (and return true) if a C++0x deleted
237/// function is being used.
238///
239/// \returns true if there was an error (this declaration cannot be
240/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000241///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000242bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000243 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000244 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000245 // If there were any diagnostics suppressed by template argument deduction,
246 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000247 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000248 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
249 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000250 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000251 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
252 Diag(Suppressed[I].first, Suppressed[I].second);
253
254 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000255 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000256 // entry from the table, because we want to avoid ever emitting these
257 // diagnostics again.
258 Suppressed.clear();
259 }
260 }
261
Richard Smith34b41d92011-02-20 03:19:35 +0000262 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000263 if (ParsingInitForAutoVars.count(D)) {
264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << D->getDeclName();
266 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000267 }
268
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000269 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000271 if (FD->isDeleted()) {
272 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000273 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000274 return true;
275 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000276 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000277 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000278
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000279 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000280
Jordan Rose0eb3f452012-06-18 22:09:19 +0000281 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000282
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000283 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000284}
285
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000286/// \brief Retrieve the message suffix that should be added to a
287/// diagnostic complaining about the given function being deleted or
288/// unavailable.
289std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000290 std::string Message;
291 if (FD->getAvailability(&Message))
292 return ": " + Message;
293
294 return std::string();
295}
296
John McCall3323fad2011-09-09 07:56:05 +0000297/// DiagnoseSentinelCalls - This routine checks whether a call or
298/// message-send is to a declaration with the sentinel attribute, and
299/// if so, it checks that the requirements of the sentinel are
300/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000301void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000302 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000303 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000304 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000305 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000306
John McCall3323fad2011-09-09 07:56:05 +0000307 // The number of formal parameters of the declaration.
308 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000309
John McCall3323fad2011-09-09 07:56:05 +0000310 // The kind of declaration. This is also an index into a %select in
311 // the diagnostic.
312 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
313
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000314 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000315 numFormalParams = MD->param_size();
316 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000317 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000318 numFormalParams = FD->param_size();
319 calleeType = CT_Function;
320 } else if (isa<VarDecl>(D)) {
321 QualType type = cast<ValueDecl>(D)->getType();
322 const FunctionType *fn = 0;
323 if (const PointerType *ptr = type->getAs<PointerType>()) {
324 fn = ptr->getPointeeType()->getAs<FunctionType>();
325 if (!fn) return;
326 calleeType = CT_Function;
327 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
328 fn = ptr->getPointeeType()->castAs<FunctionType>();
329 calleeType = CT_Block;
330 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000331 return;
John McCall3323fad2011-09-09 07:56:05 +0000332 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000333
John McCall3323fad2011-09-09 07:56:05 +0000334 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
335 numFormalParams = proto->getNumArgs();
336 } else {
337 numFormalParams = 0;
338 }
339 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000340 return;
341 }
John McCall3323fad2011-09-09 07:56:05 +0000342
343 // "nullPos" is the number of formal parameters at the end which
344 // effectively count as part of the variadic arguments. This is
345 // useful if you would prefer to not have *any* formal parameters,
346 // but the language forces you to have at least one.
347 unsigned nullPos = attr->getNullPos();
348 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
349 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
350
351 // The number of arguments which should follow the sentinel.
352 unsigned numArgsAfterSentinel = attr->getSentinel();
353
354 // If there aren't enough arguments for all the formal parameters,
355 // the sentinel, and the args after the sentinel, complain.
356 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000357 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000358 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000359 return;
360 }
John McCall3323fad2011-09-09 07:56:05 +0000361
362 // Otherwise, find the sentinel expression.
363 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000364 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000365 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000366 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000367
John McCall3323fad2011-09-09 07:56:05 +0000368 // Pick a reasonable string to insert. Optimistically use 'nil' or
369 // 'NULL' if those are actually defined in the context. Only use
370 // 'nil' for ObjC methods, where it's much more likely that the
371 // variadic arguments form a list of object pointers.
372 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000373 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
374 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000375 if (calleeType == CT_Method &&
376 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000377 NullValue = "nil";
378 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
379 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 else
John McCall3323fad2011-09-09 07:56:05 +0000381 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000382
383 if (MissingNilLoc.isInvalid())
384 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
385 else
386 Diag(MissingNilLoc, diag::warn_missing_sentinel)
387 << calleeType
388 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000389 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000390}
391
Richard Trieuccd891a2011-09-09 01:45:06 +0000392SourceRange Sema::getExprRange(Expr *E) const {
393 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000394}
395
Chris Lattnere7a2e912008-07-25 21:10:04 +0000396//===----------------------------------------------------------------------===//
397// Standard Promotions and Conversions
398//===----------------------------------------------------------------------===//
399
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000401ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000402 // Handle any placeholder expressions which made it here.
403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
406 E = result.take();
407 }
408
Chris Lattnere7a2e912008-07-25 21:10:04 +0000409 QualType Ty = E->getType();
410 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
411
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, Context.getPointerType(Ty),
414 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000415 else if (Ty->isArrayType()) {
416 // In C90 mode, arrays only promote to pointers if the array expression is
417 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
418 // type 'array of type' is converted to an expression that has type 'pointer
419 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
420 // that has type 'array of type' ...". The relevant change is "an lvalue"
421 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000422 //
423 // C++ 4.2p1:
424 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
425 // T" can be converted to an rvalue of type "pointer to T".
426 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000427 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000428 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
429 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000430 }
John Wiegley429bb272011-04-08 18:41:53 +0000431 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000432}
433
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000434static void CheckForNullPointerDereference(Sema &S, Expr *E) {
435 // Check to see if we are dereferencing a null pointer. If so,
436 // and if not volatile-qualified, this is undefined behavior that the
437 // optimizer will delete, so warn about it. People sometimes try to use this
438 // to get a deterministic trap and are surprised by clang's behavior. This
439 // only handles the pattern "*null", which is a very syntactic check.
440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
441 if (UO->getOpcode() == UO_Deref &&
442 UO->getSubExpr()->IgnoreParenCasts()->
443 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
444 !UO->getType().isVolatileQualified()) {
445 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
446 S.PDiag(diag::warn_indirection_through_null)
447 << UO->getSubExpr()->getSourceRange());
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::note_indirection_through_null));
450 }
451}
452
John Wiegley429bb272011-04-08 18:41:53 +0000453ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000454 // Handle any placeholder expressions which made it here.
455 if (E->getType()->isPlaceholderType()) {
456 ExprResult result = CheckPlaceholderExpr(E);
457 if (result.isInvalid()) return ExprError();
458 E = result.take();
459 }
460
John McCall0ae287a2010-12-01 04:43:34 +0000461 // C++ [conv.lval]p1:
462 // A glvalue of a non-function, non-array type T can be
463 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000464 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000465
John McCall409fa9a2010-12-06 20:48:59 +0000466 QualType T = E->getType();
467 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // We don't want to throw lvalue-to-rvalue casts on top of
470 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000472 (E->getType() == Context.OverloadTy ||
473 T->isDependentType() ||
474 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000475 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000476
477 // The C standard is actually really unclear on this point, and
478 // DR106 tells us what the result should be but not why. It's
479 // generally best to say that void types just doesn't undergo
480 // lvalue-to-rvalue at all. Note that expressions of unqualified
481 // 'void' type are never l-values, but qualified void can be.
482 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000483 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000484
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000485 CheckForNullPointerDereference(*this, E);
486
John McCall409fa9a2010-12-06 20:48:59 +0000487 // C++ [conv.lval]p1:
488 // [...] If T is a non-class type, the type of the prvalue is the
489 // cv-unqualified version of T. Otherwise, the type of the
490 // rvalue is T.
491 //
492 // C99 6.3.2.1p2:
493 // If the lvalue has qualified type, the value has the unqualified
494 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000495 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000496 if (T.hasQualifiers())
497 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000498
Eli Friedmand2cce132012-02-02 23:15:15 +0000499 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +0000500
501 // Loading a __weak object implicitly retains the value, so we need a cleanup to
502 // balance that.
503 if (getLangOpts().ObjCAutoRefCount &&
504 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
505 ExprNeedsCleanups = true;
Eli Friedmand2cce132012-02-02 23:15:15 +0000506
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000507 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
508 E, 0, VK_RValue));
509
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000510 // C11 6.3.2.1p2:
511 // ... if the lvalue has atomic type, the value has the non-atomic version
512 // of the type of the lvalue ...
513 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
514 T = Atomic->getValueType().getUnqualifiedType();
515 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
516 Res.get(), 0, VK_RValue));
517 }
518
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000519 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000520}
521
John Wiegley429bb272011-04-08 18:41:53 +0000522ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
523 ExprResult Res = DefaultFunctionArrayConversion(E);
524 if (Res.isInvalid())
525 return ExprError();
526 Res = DefaultLvalueConversion(Res.take());
527 if (Res.isInvalid())
528 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000529 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000530}
531
532
Chris Lattnere7a2e912008-07-25 21:10:04 +0000533/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000534/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000535/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000536/// apply if the array is an argument to the sizeof or address (&) operators.
537/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000538ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000539 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000540 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
541 if (Res.isInvalid())
542 return Owned(E);
543 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000544
John McCall0ae287a2010-12-01 04:43:34 +0000545 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000546 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000547
548 // Half FP is a bit different: it's a storage-only type, meaning that any
549 // "use" of it should be promoted to float.
550 if (Ty->isHalfType())
551 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
552
John McCall0ae287a2010-12-01 04:43:34 +0000553 // Try to perform integral promotions if the object has a theoretically
554 // promotable type.
555 if (Ty->isIntegralOrUnscopedEnumerationType()) {
556 // C99 6.3.1.1p2:
557 //
558 // The following may be used in an expression wherever an int or
559 // unsigned int may be used:
560 // - an object or expression with an integer type whose integer
561 // conversion rank is less than or equal to the rank of int
562 // and unsigned int.
563 // - A bit-field of type _Bool, int, signed int, or unsigned int.
564 //
565 // If an int can represent all values of the original type, the
566 // value is converted to an int; otherwise, it is converted to an
567 // unsigned int. These are called the integer promotions. All
568 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000569
John McCall0ae287a2010-12-01 04:43:34 +0000570 QualType PTy = Context.isPromotableBitField(E);
571 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000572 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
573 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000574 }
575 if (Ty->isPromotableIntegerType()) {
576 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000577 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
578 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000579 }
Eli Friedman04e83572009-08-20 04:21:42 +0000580 }
John Wiegley429bb272011-04-08 18:41:53 +0000581 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000582}
583
Chris Lattner05faf172008-07-25 22:25:12 +0000584/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000585/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000586/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000587ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
588 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000589 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John Wiegley429bb272011-04-08 18:41:53 +0000591 ExprResult Res = UsualUnaryConversions(E);
592 if (Res.isInvalid())
593 return Owned(E);
594 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000595
Chris Lattner05faf172008-07-25 22:25:12 +0000596 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000597 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000598 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
599
John McCall96a914a2011-08-27 22:06:17 +0000600 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000601 // promotion, even on class types, but note:
602 // C++11 [conv.lval]p2:
603 // When an lvalue-to-rvalue conversion occurs in an unevaluated
604 // operand or a subexpression thereof the value contained in the
605 // referenced object is not accessed. Otherwise, if the glvalue
606 // has a class type, the conversion copy-initializes a temporary
607 // of type T from the glvalue and the result of the conversion
608 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000609 // FIXME: add some way to gate this entire thing for correctness in
610 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000611 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000612 ExprResult Temp = PerformCopyInitialization(
613 InitializedEntity::InitializeTemporary(E->getType()),
614 E->getExprLoc(),
615 Owned(E));
616 if (Temp.isInvalid())
617 return ExprError();
618 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000619 }
620
John Wiegley429bb272011-04-08 18:41:53 +0000621 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000622}
623
Richard Smith831421f2012-06-25 20:30:08 +0000624/// Determine the degree of POD-ness for an expression.
625/// Incomplete types are considered POD, since this check can be performed
626/// when we're in an unevaluated context.
627Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000628 if (Ty->isIncompleteType()) {
629 if (Ty->isObjCObjectType())
630 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000631 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000632 }
633
634 if (Ty.isCXX98PODType(Context))
635 return VAK_Valid;
636
Richard Smith426391c2012-11-16 00:53:38 +0000637 // C++11 [expr.call]p7:
638 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith831421f2012-06-25 20:30:08 +0000639 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith426391c2012-11-16 00:53:38 +0000640 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith831421f2012-06-25 20:30:08 +0000641 // is conditionally-supported with implementation-defined semantics.
Richard Smith80ad52f2013-01-02 11:42:31 +0000642 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith831421f2012-06-25 20:30:08 +0000643 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith426391c2012-11-16 00:53:38 +0000644 if (!Record->hasNonTrivialCopyConstructor() &&
645 !Record->hasNonTrivialMoveConstructor() &&
646 !Record->hasNonTrivialDestructor())
Richard Smith831421f2012-06-25 20:30:08 +0000647 return VAK_ValidInCXX11;
648
649 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
650 return VAK_Valid;
651 return VAK_Invalid;
652}
653
654bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
655 // Don't allow one to pass an Objective-C interface to a vararg.
656 const QualType & Ty = E->getType();
657
658 // Complain about passing non-POD types through varargs.
659 switch (isValidVarArgType(Ty)) {
660 case VAK_Valid:
661 break;
662 case VAK_ValidInCXX11:
663 DiagRuntimeBehavior(E->getLocStart(), 0,
664 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
665 << E->getType() << CT);
666 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000667 case VAK_Invalid: {
668 if (Ty->isObjCObjectType())
669 return DiagRuntimeBehavior(E->getLocStart(), 0,
670 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
671 << Ty << CT);
672
Richard Smith831421f2012-06-25 20:30:08 +0000673 return DiagRuntimeBehavior(E->getLocStart(), 0,
674 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Richard Smith80ad52f2013-01-02 11:42:31 +0000675 << getLangOpts().CPlusPlus11 << Ty << CT);
Richard Smith831421f2012-06-25 20:30:08 +0000676 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000677 }
Richard Smith831421f2012-06-25 20:30:08 +0000678 // c++ rules are enforced elsewhere.
679 return false;
680}
681
Chris Lattner312531a2009-04-12 08:11:20 +0000682/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000683/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000684ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000685 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000686 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000687 // Strip the unbridged-cast placeholder expression off, if applicable.
688 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
689 (CT == VariadicMethod ||
690 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
691 E = stripARCUnbridgedCast(E);
692
693 // Otherwise, do normal placeholder checking.
694 } else {
695 ExprResult ExprRes = CheckPlaceholderExpr(E);
696 if (ExprRes.isInvalid())
697 return ExprError();
698 E = ExprRes.take();
699 }
700 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000701
John McCall5acb0c92011-10-17 18:40:02 +0000702 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000703 if (ExprRes.isInvalid())
704 return ExprError();
705 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Richard Smith831421f2012-06-25 20:30:08 +0000707 // Diagnostics regarding non-POD argument types are
708 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000709 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000710 // Turn this into a trap.
711 CXXScopeSpec SS;
712 SourceLocation TemplateKWLoc;
713 UnqualifiedId Name;
714 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
715 E->getLocStart());
716 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
717 Name, true, false);
718 if (TrapFn.isInvalid())
719 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000720
Richard Smith831421f2012-06-25 20:30:08 +0000721 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
722 E->getLocStart(), MultiExprArg(),
723 E->getLocEnd());
724 if (Call.isInvalid())
725 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000726
Richard Smith831421f2012-06-25 20:30:08 +0000727 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
728 Call.get(), E);
729 if (Comma.isInvalid())
730 return ExprError();
731 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000732 }
Richard Smith831421f2012-06-25 20:30:08 +0000733
David Blaikie4e4d0842012-03-11 07:00:24 +0000734 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000735 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000736 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000737 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000738
John Wiegley429bb272011-04-08 18:41:53 +0000739 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000740}
741
Richard Trieu8289f492011-09-02 20:58:51 +0000742/// \brief Converts an integer to complex float type. Helper function of
743/// UsualArithmeticConversions()
744///
745/// \return false if the integer expression is an integer type and is
746/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000747static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
748 ExprResult &ComplexExpr,
749 QualType IntTy,
750 QualType ComplexTy,
751 bool SkipCast) {
752 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
753 if (SkipCast) return false;
754 if (IntTy->isIntegerType()) {
755 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
756 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
757 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000758 CK_FloatingRealToComplex);
759 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000760 assert(IntTy->isComplexIntegerType());
761 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000762 CK_IntegralComplexToFloatingComplex);
763 }
764 return false;
765}
766
767/// \brief Takes two complex float types and converts them to the same type.
768/// Helper function of UsualArithmeticConversions()
769static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000770handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
771 ExprResult &RHS, QualType LHSType,
772 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000773 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000774 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000775
776 if (order < 0) {
777 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000778 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000779 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
780 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000781 }
782 if (order > 0)
783 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000784 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
785 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000786}
787
788/// \brief Converts otherExpr to complex float and promotes complexExpr if
789/// necessary. Helper function of UsualArithmeticConversions()
790static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000791 ExprResult &ComplexExpr,
792 ExprResult &OtherExpr,
793 QualType ComplexTy,
794 QualType OtherTy,
795 bool ConvertComplexExpr,
796 bool ConvertOtherExpr) {
797 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000798
799 // If just the complexExpr is complex, the otherExpr needs to be converted,
800 // and the complexExpr might need to be promoted.
801 if (order > 0) { // complexExpr is wider
802 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000803 if (ConvertOtherExpr) {
804 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
805 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000807 CK_FloatingRealToComplex);
808 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000809 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000810 }
811
812 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000813 QualType result = (order == 0 ? ComplexTy :
814 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000815
816 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000817 if (ConvertOtherExpr)
818 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000819 CK_FloatingRealToComplex);
820
821 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000822 if (ConvertComplexExpr && order < 0)
823 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000824 CK_FloatingComplexCast);
825
826 return result;
827}
828
829/// \brief Handle arithmetic conversion with complex types. Helper function of
830/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000831static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
832 ExprResult &RHS, QualType LHSType,
833 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000834 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000835 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000836 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000837 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000838 return LHSType;
839 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000840 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000841 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000842
843 // This handles complex/complex, complex/float, or float/complex.
844 // When both operands are complex, the shorter operand is converted to the
845 // type of the longer, and that is the type of the result. This corresponds
846 // to what is done when combining two real floating-point operands.
847 // The fun begins when size promotion occur across type domains.
848 // From H&S 6.3.4: When one operand is complex and the other is a real
849 // floating-point type, the less precise type is converted, within it's
850 // real or complex domain, to the precision of the other type. For example,
851 // when combining a "long double" with a "double _Complex", the
852 // "double _Complex" is promoted to "long double _Complex".
853
Richard Trieucafd30b2011-09-06 18:25:09 +0000854 bool LHSComplexFloat = LHSType->isComplexType();
855 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000856
857 // If both are complex, just cast to the more precise type.
858 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000859 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
860 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000861 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000862
863 // If only one operand is complex, promote it if necessary and convert the
864 // other operand to complex.
865 if (LHSComplexFloat)
866 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000868 /*convertOtherExpr*/ true);
869
870 assert(RHSComplexFloat);
871 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000872 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000873 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000874}
875
876/// \brief Hande arithmetic conversion from integer to float. Helper function
877/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000878static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
879 ExprResult &IntExpr,
880 QualType FloatTy, QualType IntTy,
881 bool ConvertFloat, bool ConvertInt) {
882 if (IntTy->isIntegerType()) {
883 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000884 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000885 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000886 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000887 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000888 }
889
890 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000891 assert(IntTy->isComplexIntegerType());
892 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000893
894 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000895 if (ConvertInt)
896 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000897 CK_IntegralComplexToFloatingComplex);
898
899 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000900 if (ConvertFloat)
901 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000902 CK_FloatingRealToComplex);
903
904 return result;
905}
906
907/// \brief Handle arithmethic conversion with floating point types. Helper
908/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000909static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
910 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000911 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000912 bool LHSFloat = LHSType->isRealFloatingType();
913 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000914
915 // If we have two real floating types, convert the smaller operand
916 // to the bigger result.
917 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000918 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000919 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000920 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
921 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000922 }
923
924 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000925 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000926 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
927 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000928 }
929
930 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000931 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000932 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000933 /*convertInt=*/ true);
934 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000935 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000936 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000937 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000938}
939
940/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000941/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000942// FIXME: if the operands are (int, _Complex long), we currently
943// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000944static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
945 ExprResult &RHS, QualType LHSType,
946 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000947 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000948 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
949 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000950
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000951 if (LHSComplexInt && RHSComplexInt) {
952 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
953 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000954 assert(order && "inequal types with equal element ordering");
955 if (order > 0) {
956 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000957 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
958 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000959 }
960
Richard Trieuccd891a2011-09-09 01:45:06 +0000961 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000962 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
963 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000964 }
965
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000966 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000967 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000968 // FIXME: This needs to take integer ranks into account
969 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
970 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000971 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
972 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000973 }
974
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000975 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000976 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000977 // FIXME: This needs to take integer ranks into account
978 if (!IsCompAssign) {
979 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
980 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000981 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000982 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000983 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000984}
985
986/// \brief Handle integer arithmetic conversions. Helper function of
987/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000988static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
989 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000990 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000991 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
993 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
994 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
995 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000996 // Same signedness; use the higher-ranked type
997 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000998 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
999 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001000 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001001 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1002 return RHSType;
1003 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001004 // The unsigned type has greater than or equal rank to the
1005 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001006 if (RHSSigned) {
1007 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1008 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001009 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001010 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1011 return RHSType;
1012 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001013 // The two types are different widths; if we are here, that
1014 // means the signed type is larger than the unsigned type, so
1015 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001016 if (LHSSigned) {
1017 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1018 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001019 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001020 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1021 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001022 } else {
1023 // The signed type is higher-ranked than the unsigned type,
1024 // but isn't actually any bigger (like unsigned int and long
1025 // on most 32-bit systems). Use the unsigned type corresponding
1026 // to the signed type.
1027 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001028 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1029 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001030 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001031 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001032 return result;
1033 }
1034}
1035
Chris Lattnere7a2e912008-07-25 21:10:04 +00001036/// UsualArithmeticConversions - Performs various conversions that are common to
1037/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001038/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001039/// responsible for emitting appropriate error diagnostics.
1040/// FIXME: verify the conversion rules for "complex int" are consistent with
1041/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001042QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001043 bool IsCompAssign) {
1044 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001045 LHS = UsualUnaryConversions(LHS.take());
1046 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001047 return QualType();
1048 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001049
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001050 RHS = UsualUnaryConversions(RHS.take());
1051 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001052 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001053
Mike Stump1eb44332009-09-09 15:08:12 +00001054 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001055 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001056 QualType LHSType =
1057 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1058 QualType RHSType =
1059 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001060
Eli Friedman860a3192012-06-16 02:19:17 +00001061 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1062 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1063 LHSType = AtomicLHS->getValueType();
1064
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001065 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001066 if (LHSType == RHSType)
1067 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001068
1069 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1070 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001071 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001072 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001073
John McCallcf33b242010-11-13 08:17:45 +00001074 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001075 QualType LHSUnpromotedType = LHSType;
1076 if (LHSType->isPromotableIntegerType())
1077 LHSType = Context.getPromotedIntegerType(LHSType);
1078 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001079 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001080 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001081 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001082 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001083
John McCallcf33b242010-11-13 08:17:45 +00001084 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001085 if (LHSType == RHSType)
1086 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001087
1088 // At this point, we have two different arithmetic types.
1089
1090 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001091 if (LHSType->isComplexType() || RHSType->isComplexType())
1092 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001093 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001094
1095 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001096 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1097 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001098 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001099
1100 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001101 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001102 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001103 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001104
1105 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001106 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001107 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001108}
1109
Chris Lattnere7a2e912008-07-25 21:10:04 +00001110//===----------------------------------------------------------------------===//
1111// Semantic Analysis for various Expression Types
1112//===----------------------------------------------------------------------===//
1113
1114
Peter Collingbournef111d932011-04-15 00:35:48 +00001115ExprResult
1116Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1117 SourceLocation DefaultLoc,
1118 SourceLocation RParenLoc,
1119 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001120 MultiTypeArg ArgTypes,
1121 MultiExprArg ArgExprs) {
1122 unsigned NumAssocs = ArgTypes.size();
1123 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001124
Benjamin Kramer5354e772012-08-23 23:38:35 +00001125 ParsedType *ParsedTypes = ArgTypes.data();
1126 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001127
1128 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1129 for (unsigned i = 0; i < NumAssocs; ++i) {
1130 if (ParsedTypes[i])
1131 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1132 else
1133 Types[i] = 0;
1134 }
1135
1136 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1137 ControllingExpr, Types, Exprs,
1138 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001139 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001140 return ER;
1141}
1142
1143ExprResult
1144Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1145 SourceLocation DefaultLoc,
1146 SourceLocation RParenLoc,
1147 Expr *ControllingExpr,
1148 TypeSourceInfo **Types,
1149 Expr **Exprs,
1150 unsigned NumAssocs) {
1151 bool TypeErrorFound = false,
1152 IsResultDependent = ControllingExpr->isTypeDependent(),
1153 ContainsUnexpandedParameterPack
1154 = ControllingExpr->containsUnexpandedParameterPack();
1155
1156 for (unsigned i = 0; i < NumAssocs; ++i) {
1157 if (Exprs[i]->containsUnexpandedParameterPack())
1158 ContainsUnexpandedParameterPack = true;
1159
1160 if (Types[i]) {
1161 if (Types[i]->getType()->containsUnexpandedParameterPack())
1162 ContainsUnexpandedParameterPack = true;
1163
1164 if (Types[i]->getType()->isDependentType()) {
1165 IsResultDependent = true;
1166 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001167 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001168 // complete object type other than a variably modified type."
1169 unsigned D = 0;
1170 if (Types[i]->getType()->isIncompleteType())
1171 D = diag::err_assoc_type_incomplete;
1172 else if (!Types[i]->getType()->isObjectType())
1173 D = diag::err_assoc_type_nonobject;
1174 else if (Types[i]->getType()->isVariablyModifiedType())
1175 D = diag::err_assoc_type_variably_modified;
1176
1177 if (D != 0) {
1178 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1179 << Types[i]->getTypeLoc().getSourceRange()
1180 << Types[i]->getType();
1181 TypeErrorFound = true;
1182 }
1183
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001184 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001185 // selection shall specify compatible types."
1186 for (unsigned j = i+1; j < NumAssocs; ++j)
1187 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1188 Context.typesAreCompatible(Types[i]->getType(),
1189 Types[j]->getType())) {
1190 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1191 diag::err_assoc_compatible_types)
1192 << Types[j]->getTypeLoc().getSourceRange()
1193 << Types[j]->getType()
1194 << Types[i]->getType();
1195 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1196 diag::note_compat_assoc)
1197 << Types[i]->getTypeLoc().getSourceRange()
1198 << Types[i]->getType();
1199 TypeErrorFound = true;
1200 }
1201 }
1202 }
1203 }
1204 if (TypeErrorFound)
1205 return ExprError();
1206
1207 // If we determined that the generic selection is result-dependent, don't
1208 // try to compute the result expression.
1209 if (IsResultDependent)
1210 return Owned(new (Context) GenericSelectionExpr(
1211 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001212 llvm::makeArrayRef(Types, NumAssocs),
1213 llvm::makeArrayRef(Exprs, NumAssocs),
1214 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001215
Chris Lattner5f9e2722011-07-23 10:55:15 +00001216 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001217 unsigned DefaultIndex = -1U;
1218 for (unsigned i = 0; i < NumAssocs; ++i) {
1219 if (!Types[i])
1220 DefaultIndex = i;
1221 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1222 Types[i]->getType()))
1223 CompatIndices.push_back(i);
1224 }
1225
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001226 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001227 // type compatible with at most one of the types named in its generic
1228 // association list."
1229 if (CompatIndices.size() > 1) {
1230 // We strip parens here because the controlling expression is typically
1231 // parenthesized in macro definitions.
1232 ControllingExpr = ControllingExpr->IgnoreParens();
1233 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1234 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1235 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001236 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001237 E = CompatIndices.end(); I != E; ++I) {
1238 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1239 diag::note_compat_assoc)
1240 << Types[*I]->getTypeLoc().getSourceRange()
1241 << Types[*I]->getType();
1242 }
1243 return ExprError();
1244 }
1245
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001246 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001247 // its controlling expression shall have type compatible with exactly one of
1248 // the types named in its generic association list."
1249 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1250 // We strip parens here because the controlling expression is typically
1251 // parenthesized in macro definitions.
1252 ControllingExpr = ControllingExpr->IgnoreParens();
1253 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1254 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1255 return ExprError();
1256 }
1257
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001258 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001259 // type name that is compatible with the type of the controlling expression,
1260 // then the result expression of the generic selection is the expression
1261 // in that generic association. Otherwise, the result expression of the
1262 // generic selection is the expression in the default generic association."
1263 unsigned ResultIndex =
1264 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1265
1266 return Owned(new (Context) GenericSelectionExpr(
1267 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001268 llvm::makeArrayRef(Types, NumAssocs),
1269 llvm::makeArrayRef(Exprs, NumAssocs),
1270 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001271 ResultIndex));
1272}
1273
Richard Smithdd66be72012-03-08 01:34:56 +00001274/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1275/// location of the token and the offset of the ud-suffix within it.
1276static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1277 unsigned Offset) {
1278 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001279 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001280}
1281
Richard Smith36f5cfe2012-03-09 08:00:36 +00001282/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1283/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1284static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1285 IdentifierInfo *UDSuffix,
1286 SourceLocation UDSuffixLoc,
1287 ArrayRef<Expr*> Args,
1288 SourceLocation LitEndLoc) {
1289 assert(Args.size() <= 2 && "too many arguments for literal operator");
1290
1291 QualType ArgTy[2];
1292 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1293 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1294 if (ArgTy[ArgIdx]->isArrayType())
1295 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1296 }
1297
1298 DeclarationName OpName =
1299 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1300 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1301 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1302
1303 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1304 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1305 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1306 return ExprError();
1307
1308 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1309}
1310
Steve Narofff69936d2007-09-16 03:34:24 +00001311/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001312/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1313/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1314/// multiple tokens. However, the common case is that StringToks points to one
1315/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001316///
John McCall60d7b3a2010-08-24 06:29:42 +00001317ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001318Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1319 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 assert(NumStringToks && "Must have at least one string!");
1321
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001322 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001324 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001325
Chris Lattner5f9e2722011-07-23 10:55:15 +00001326 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 for (unsigned i = 0; i != NumStringToks; ++i)
1328 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001329
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001330 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001331 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001332 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001333 else if (Literal.isUTF16())
1334 StrTy = Context.Char16Ty;
1335 else if (Literal.isUTF32())
1336 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001337 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001338 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001339
Douglas Gregor5cee1192011-07-27 05:40:30 +00001340 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1341 if (Literal.isWide())
1342 Kind = StringLiteral::Wide;
1343 else if (Literal.isUTF8())
1344 Kind = StringLiteral::UTF8;
1345 else if (Literal.isUTF16())
1346 Kind = StringLiteral::UTF16;
1347 else if (Literal.isUTF32())
1348 Kind = StringLiteral::UTF32;
1349
Douglas Gregor77a52232008-09-12 00:47:35 +00001350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001351 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001352 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001353
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001354 // Get an array type for the string, according to C99 6.4.5. This includes
1355 // the nul terminator character as well as the string length for pascal
1356 // strings.
1357 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001358 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001359 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001362 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1363 Kind, Literal.Pascal, StrTy,
1364 &StringTokLocs[0],
1365 StringTokLocs.size());
1366 if (Literal.getUDSuffix().empty())
1367 return Owned(Lit);
1368
1369 // We're building a user-defined literal.
1370 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001371 SourceLocation UDSuffixLoc =
1372 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1373 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001374
Richard Smith36f5cfe2012-03-09 08:00:36 +00001375 // Make sure we're allowed user-defined literals here.
1376 if (!UDLScope)
1377 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1378
Richard Smith9fcce652012-03-07 08:35:16 +00001379 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1380 // operator "" X (str, len)
1381 QualType SizeType = Context.getSizeType();
1382 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1383 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1384 StringTokLocs[0]);
1385 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001386 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1387 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001388}
1389
John McCall60d7b3a2010-08-24 06:29:42 +00001390ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001391Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001392 SourceLocation Loc,
1393 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001394 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001395 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001396}
1397
John McCall76a40212011-02-09 01:13:10 +00001398/// BuildDeclRefExpr - Build an expression that references a
1399/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001400ExprResult
John McCall76a40212011-02-09 01:13:10 +00001401Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001402 const DeclarationNameInfo &NameInfo,
1403 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001404 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001405 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1406 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1407 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1408 CalleeTarget = IdentifyCUDATarget(Callee);
1409 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1410 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1411 << CalleeTarget << D->getIdentifier() << CallerTarget;
1412 Diag(D->getLocation(), diag::note_previous_decl)
1413 << D->getIdentifier();
1414 return ExprError();
1415 }
1416 }
1417
John McCallf4b88a42012-03-10 09:33:50 +00001418 bool refersToEnclosingScope =
1419 (CurContext != D->getDeclContext() &&
1420 D->getDeclContext()->isFunctionOrMethod());
1421
Eli Friedman5f2987c2012-02-02 03:46:19 +00001422 DeclRefExpr *E = DeclRefExpr::Create(Context,
1423 SS ? SS->getWithLocInContext(Context)
1424 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001425 SourceLocation(),
1426 D, refersToEnclosingScope,
1427 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Eli Friedman5f2987c2012-02-02 03:46:19 +00001429 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001430
Jordan Rose7a270482012-09-28 22:21:35 +00001431 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1432 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1433 DiagnosticsEngine::Level Level =
1434 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1435 E->getLocStart());
1436 if (Level != DiagnosticsEngine::Ignored)
1437 getCurFunction()->recordUseOfWeak(E);
1438 }
1439
John McCall7eb0a9e2010-11-24 05:12:34 +00001440 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001441 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1442 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001443 E->setObjectKind(OK_BitField);
1444
1445 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001446}
1447
Abramo Bagnara25777432010-08-11 22:01:17 +00001448/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001449/// possibly a list of template arguments.
1450///
1451/// If this produces template arguments, it is permitted to call
1452/// DecomposeTemplateName.
1453///
1454/// This actually loses a lot of source location information for
1455/// non-standard name kinds; we should consider preserving that in
1456/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001457void
1458Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1459 TemplateArgumentListInfo &Buffer,
1460 DeclarationNameInfo &NameInfo,
1461 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001462 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1463 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1464 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1465
Benjamin Kramer5354e772012-08-23 23:38:35 +00001466 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001467 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001468 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001469
John McCall2b5289b2010-08-23 07:28:44 +00001470 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001471 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001473 TemplateArgs = &Buffer;
1474 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001475 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001476 TemplateArgs = 0;
1477 }
1478}
1479
John McCall578b69b2009-12-16 08:11:27 +00001480/// Diagnose an empty lookup.
1481///
1482/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001483bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001484 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001485 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001486 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001487 DeclarationName Name = R.getLookupName();
1488
John McCall578b69b2009-12-16 08:11:27 +00001489 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001490 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001491 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1492 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001493 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001494 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001495 diagnostic_suggest = diag::err_undeclared_use_suggest;
1496 }
John McCall578b69b2009-12-16 08:11:27 +00001497
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001498 // If the original lookup was an unqualified lookup, fake an
1499 // unqualified lookup. This is useful when (for example) the
1500 // original lookup would not have found something because it was a
1501 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001502 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1503 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001504 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001505 if (isa<CXXRecordDecl>(DC)) {
1506 LookupQualifiedName(R, DC);
1507
1508 if (!R.empty()) {
1509 // Don't give errors about ambiguities in this lookup.
1510 R.suppressDiagnostics();
1511
Francois Pichete6226ae2011-11-17 03:44:24 +00001512 // During a default argument instantiation the CurContext points
1513 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1514 // function parameter list, hence add an explicit check.
1515 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1516 ActiveTemplateInstantiations.back().Kind ==
1517 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001518 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1519 bool isInstance = CurMethod &&
1520 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001521 DC == CurMethod->getParent() && !isDefaultArgument;
1522
John McCall578b69b2009-12-16 08:11:27 +00001523
1524 // Give a code modification hint to insert 'this->'.
1525 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1526 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001527 if (getLangOpts().MicrosoftMode)
1528 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001529 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001530 Diag(R.getNameLoc(), diagnostic) << Name
1531 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001532 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1533 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001534
1535
1536 CXXMethodDecl *DepMethod;
1537 if (CurMethod->getTemplatedKind() ==
1538 FunctionDecl::TK_FunctionTemplateSpecialization)
1539 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1540 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1541 else
1542 DepMethod = cast<CXXMethodDecl>(
1543 CurMethod->getInstantiatedFromMemberFunction());
1544 assert(DepMethod && "No template pattern found");
1545
1546 QualType DepThisType = DepMethod->getThisType(Context);
1547 CheckCXXThisCapture(R.getNameLoc());
1548 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1549 R.getNameLoc(), DepThisType, false);
1550 TemplateArgumentListInfo TList;
1551 if (ULE->hasExplicitTemplateArgs())
1552 ULE->copyTemplateArgumentsInto(TList);
1553
1554 CXXScopeSpec SS;
1555 SS.Adopt(ULE->getQualifierLoc());
1556 CXXDependentScopeMemberExpr *DepExpr =
1557 CXXDependentScopeMemberExpr::Create(
1558 Context, DepThis, DepThisType, true, SourceLocation(),
1559 SS.getWithLocInContext(Context),
1560 ULE->getTemplateKeywordLoc(), 0,
1561 R.getLookupNameInfo(),
1562 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1563 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001564 } else {
John McCall578b69b2009-12-16 08:11:27 +00001565 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001566 }
John McCall578b69b2009-12-16 08:11:27 +00001567
1568 // Do we really want to note all of these?
1569 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1570 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1571
Francois Pichete6226ae2011-11-17 03:44:24 +00001572 // Return true if we are inside a default argument instantiation
1573 // and the found name refers to an instance member function, otherwise
1574 // the function calling DiagnoseEmptyLookup will try to create an
1575 // implicit member call and this is wrong for default argument.
1576 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1577 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1578 return true;
1579 }
1580
John McCall578b69b2009-12-16 08:11:27 +00001581 // Tell the callee to try to recover.
1582 return false;
1583 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001584
1585 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001586 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001587
1588 // In Microsoft mode, if we are performing lookup from within a friend
1589 // function definition declared at class scope then we must set
1590 // DC to the lexical parent to be able to search into the parent
1591 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001592 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001593 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1594 DC->getLexicalParent()->isRecord())
1595 DC = DC->getLexicalParent();
1596 else
1597 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001598 }
1599
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001600 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001601 TypoCorrection Corrected;
1602 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001603 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001604 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1605 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001606 R.setLookupName(Corrected.getCorrection());
1607
Hans Wennborg701d1e72011-07-12 08:45:31 +00001608 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001609 if (Corrected.isOverloaded()) {
1610 OverloadCandidateSet OCS(R.getNameLoc());
1611 OverloadCandidateSet::iterator Best;
1612 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1613 CDEnd = Corrected.end();
1614 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001615 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001616 dyn_cast<FunctionTemplateDecl>(*CD))
1617 AddTemplateOverloadCandidate(
1618 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001619 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001620 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1621 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1622 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001623 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001624 }
1625 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1626 case OR_Success:
1627 ND = Best->Function;
1628 break;
1629 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001630 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001631 }
1632 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001633 R.addDecl(ND);
1634 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001635 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001636 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1637 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001638 else
1639 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001640 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001641 << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00001642 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1643 CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001644 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,
Richard Smithefeeccf2012-10-21 03:28:35 +00001897 const DeclarationNameInfo &NameInfo,
1898 bool IsAddressOfOperand) {
Richard Smith713c2872012-10-23 19:56:01 +00001899 DeclContext *DC = computeDeclContext(SS, false);
1900 if (!DC)
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001901 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1902 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001903
John McCall77bb1aa2010-05-01 00:40:08 +00001904 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001905 return ExprError();
1906
Abramo Bagnara25777432010-08-11 22:01:17 +00001907 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001908 LookupQualifiedName(R, DC);
1909
1910 if (R.isAmbiguous())
1911 return ExprError();
1912
Richard Smith713c2872012-10-23 19:56:01 +00001913 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1914 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1915 NameInfo, /*TemplateArgs=*/0);
1916
John McCallf7a1a742009-11-24 19:00:30 +00001917 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001918 Diag(NameInfo.getLoc(), diag::err_no_member)
1919 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001920 return ExprError();
1921 }
1922
Richard Smithefeeccf2012-10-21 03:28:35 +00001923 // Defend against this resolving to an implicit member access. We usually
1924 // won't get here if this might be a legitimate a class member (we end up in
1925 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1926 // a pointer-to-member or in an unevaluated context in C++11.
1927 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1928 return BuildPossibleImplicitMemberExpr(SS,
1929 /*TemplateKWLoc=*/SourceLocation(),
1930 R, /*TemplateArgs=*/0);
1931
1932 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00001933}
1934
1935/// LookupInObjCMethod - The parser has read a name in, and Sema has
1936/// detected that we're currently inside an ObjC method. Perform some
1937/// additional lookup.
1938///
1939/// Ideally, most of this would be done by lookup, but there's
1940/// actually quite a lot of extra work involved.
1941///
1942/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001943ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001944Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001945 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001946 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001947 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001948
John McCallf7a1a742009-11-24 19:00:30 +00001949 // There are two cases to handle here. 1) scoped lookup could have failed,
1950 // in which case we should look for an ivar. 2) scoped lookup could have
1951 // found a decl, but that decl is outside the current instance method (i.e.
1952 // a global variable). In these two cases, we do a lookup for an ivar with
1953 // this name, if the lookup sucedes, we replace it our current decl.
1954
1955 // If we're in a class method, we don't normally want to look for
1956 // ivars. But if we don't find anything else, and there's an
1957 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001958 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001959
1960 bool LookForIvars;
1961 if (Lookup.empty())
1962 LookForIvars = true;
1963 else if (IsClassMethod)
1964 LookForIvars = false;
1965 else
1966 LookForIvars = (Lookup.isSingleResult() &&
1967 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001968 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001969 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001970 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001971 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001972 ObjCIvarDecl *IV = 0;
1973 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001974 // Diagnose using an ivar in a class method.
1975 if (IsClassMethod)
1976 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1977 << IV->getDeclName());
1978
1979 // If we're referencing an invalid decl, just return this as a silent
1980 // error node. The error diagnostic was already emitted on the decl.
1981 if (IV->isInvalidDecl())
1982 return ExprError();
1983
1984 // Check if referencing a field with __attribute__((deprecated)).
1985 if (DiagnoseUseOfDecl(IV, Loc))
1986 return ExprError();
1987
1988 // Diagnose the use of an ivar outside of the declaring class.
1989 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001990 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001991 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001992 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1993
1994 // FIXME: This should use a new expr for a direct reference, don't
1995 // turn this into Self->ivar, just return a BareIVarExpr or something.
1996 IdentifierInfo &II = Context.Idents.get("self");
1997 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001998 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001999 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00002000 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002001 SourceLocation TemplateKWLoc;
2002 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002003 SelfName, false, false);
2004 if (SelfExpr.isInvalid())
2005 return ExprError();
2006
John Wiegley429bb272011-04-08 18:41:53 +00002007 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2008 if (SelfExpr.isInvalid())
2009 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002010
Eli Friedman5f2987c2012-02-02 03:46:19 +00002011 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002012
2013 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2014 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2015 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002016
2017 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2018 Loc,
2019 SelfExpr.take(),
2020 true, true);
2021
2022 if (getLangOpts().ObjCAutoRefCount) {
2023 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2024 DiagnosticsEngine::Level Level =
2025 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2026 if (Level != DiagnosticsEngine::Ignored)
2027 getCurFunction()->recordUseOfWeak(Result);
2028 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002029 if (CurContext->isClosure())
2030 Diag(Loc, diag::warn_implicitly_retains_self)
2031 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002032 }
2033
2034 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002035 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002036 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002037 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002038 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2039 ObjCInterfaceDecl *ClassDeclared;
2040 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2041 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002042 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002043 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2044 }
John McCallf7a1a742009-11-24 19:00:30 +00002045 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002046 } else if (Lookup.isSingleResult() &&
2047 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2048 // If accessing a stand-alone ivar in a class method, this is an error.
2049 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2050 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2051 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002052 }
2053
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002054 if (Lookup.empty() && II && AllowBuiltinCreation) {
2055 // FIXME. Consolidate this with similar code in LookupName.
2056 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002057 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002058 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2059 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2060 S, Lookup.isForRedeclaration(),
2061 Lookup.getNameLoc());
2062 if (D) Lookup.addDecl(D);
2063 }
2064 }
2065 }
John McCallf7a1a742009-11-24 19:00:30 +00002066 // Sentinel value saying that we didn't do anything special.
2067 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002068}
John McCallba135432009-11-21 08:51:07 +00002069
John McCall6bb80172010-03-30 21:47:33 +00002070/// \brief Cast a base object to a member's actual type.
2071///
2072/// Logically this happens in three phases:
2073///
2074/// * First we cast from the base type to the naming class.
2075/// The naming class is the class into which we were looking
2076/// when we found the member; it's the qualifier type if a
2077/// qualifier was provided, and otherwise it's the base type.
2078///
2079/// * Next we cast from the naming class to the declaring class.
2080/// If the member we found was brought into a class's scope by
2081/// a using declaration, this is that class; otherwise it's
2082/// the class declaring the member.
2083///
2084/// * Finally we cast from the declaring class to the "true"
2085/// declaring class of the member. This conversion does not
2086/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002087ExprResult
2088Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002089 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002090 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002091 NamedDecl *Member) {
2092 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2093 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002094 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002095
Douglas Gregor5fccd362010-03-03 23:55:11 +00002096 QualType DestRecordType;
2097 QualType DestType;
2098 QualType FromRecordType;
2099 QualType FromType = From->getType();
2100 bool PointerConversions = false;
2101 if (isa<FieldDecl>(Member)) {
2102 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002103
Douglas Gregor5fccd362010-03-03 23:55:11 +00002104 if (FromType->getAs<PointerType>()) {
2105 DestType = Context.getPointerType(DestRecordType);
2106 FromRecordType = FromType->getPointeeType();
2107 PointerConversions = true;
2108 } else {
2109 DestType = DestRecordType;
2110 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002111 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002112 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2113 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002114 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002115
Douglas Gregor5fccd362010-03-03 23:55:11 +00002116 DestType = Method->getThisType(Context);
2117 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002118
Douglas Gregor5fccd362010-03-03 23:55:11 +00002119 if (FromType->getAs<PointerType>()) {
2120 FromRecordType = FromType->getPointeeType();
2121 PointerConversions = true;
2122 } else {
2123 FromRecordType = FromType;
2124 DestType = DestRecordType;
2125 }
2126 } else {
2127 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002128 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002129 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002130
Douglas Gregor5fccd362010-03-03 23:55:11 +00002131 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002132 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002133
Douglas Gregor5fccd362010-03-03 23:55:11 +00002134 // If the unqualified types are the same, no conversion is necessary.
2135 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002136 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002137
John McCall6bb80172010-03-30 21:47:33 +00002138 SourceRange FromRange = From->getSourceRange();
2139 SourceLocation FromLoc = FromRange.getBegin();
2140
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002141 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002142
Douglas Gregor5fccd362010-03-03 23:55:11 +00002143 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002144 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002145 // class name.
2146 //
2147 // If the member was a qualified name and the qualified referred to a
2148 // specific base subobject type, we'll cast to that intermediate type
2149 // first and then to the object in which the member is declared. That allows
2150 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2151 //
2152 // class Base { public: int x; };
2153 // class Derived1 : public Base { };
2154 // class Derived2 : public Base { };
2155 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2156 //
2157 // void VeryDerived::f() {
2158 // x = 17; // error: ambiguous base subobjects
2159 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2160 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002161 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002162 QualType QType = QualType(Qualifier->getAsType(), 0);
2163 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2164 assert(QType->isRecordType() && "lookup done with non-record type");
2165
2166 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2167
2168 // In C++98, the qualifier type doesn't actually have to be a base
2169 // type of the object type, in which case we just ignore it.
2170 // Otherwise build the appropriate casts.
2171 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002172 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002173 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002174 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002175 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002176
Douglas Gregor5fccd362010-03-03 23:55:11 +00002177 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002178 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002179 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2180 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002181
2182 FromType = QType;
2183 FromRecordType = QRecordType;
2184
2185 // If the qualifier type was the same as the destination type,
2186 // we're done.
2187 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002188 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002189 }
2190 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002191
John McCall6bb80172010-03-30 21:47:33 +00002192 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002193
John McCall6bb80172010-03-30 21:47:33 +00002194 // If we actually found the member through a using declaration, cast
2195 // down to the using declaration's type.
2196 //
2197 // Pointer equality is fine here because only one declaration of a
2198 // class ever has member declarations.
2199 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2200 assert(isa<UsingShadowDecl>(FoundDecl));
2201 QualType URecordType = Context.getTypeDeclType(
2202 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2203
2204 // We only need to do this if the naming-class to declaring-class
2205 // conversion is non-trivial.
2206 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2207 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002208 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002209 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002210 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002211 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002212
John McCall6bb80172010-03-30 21:47:33 +00002213 QualType UType = URecordType;
2214 if (PointerConversions)
2215 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002216 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2217 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002218 FromType = UType;
2219 FromRecordType = URecordType;
2220 }
2221
2222 // We don't do access control for the conversion from the
2223 // declaring class to the true declaring class.
2224 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002225 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002226
John McCallf871d0c2010-08-07 06:22:56 +00002227 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002228 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2229 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002230 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002231 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002232
John Wiegley429bb272011-04-08 18:41:53 +00002233 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2234 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002235}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002236
John McCallf7a1a742009-11-24 19:00:30 +00002237bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002238 const LookupResult &R,
2239 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002240 // Only when used directly as the postfix-expression of a call.
2241 if (!HasTrailingLParen)
2242 return false;
2243
2244 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002245 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002246 return false;
2247
2248 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002249 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002250 return false;
2251
2252 // Turn off ADL when we find certain kinds of declarations during
2253 // normal lookup:
2254 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2255 NamedDecl *D = *I;
2256
2257 // C++0x [basic.lookup.argdep]p3:
2258 // -- a declaration of a class member
2259 // Since using decls preserve this property, we check this on the
2260 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002261 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002262 return false;
2263
2264 // C++0x [basic.lookup.argdep]p3:
2265 // -- a block-scope function declaration that is not a
2266 // using-declaration
2267 // NOTE: we also trigger this for function templates (in fact, we
2268 // don't check the decl type at all, since all other decl types
2269 // turn off ADL anyway).
2270 if (isa<UsingShadowDecl>(D))
2271 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2272 else if (D->getDeclContext()->isFunctionOrMethod())
2273 return false;
2274
2275 // C++0x [basic.lookup.argdep]p3:
2276 // -- a declaration that is neither a function or a function
2277 // template
2278 // And also for builtin functions.
2279 if (isa<FunctionDecl>(D)) {
2280 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2281
2282 // But also builtin functions.
2283 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2284 return false;
2285 } else if (!isa<FunctionTemplateDecl>(D))
2286 return false;
2287 }
2288
2289 return true;
2290}
2291
2292
John McCallba135432009-11-21 08:51:07 +00002293/// Diagnoses obvious problems with the use of the given declaration
2294/// as an expression. This is only actually called for lookups that
2295/// were not overloaded, and it doesn't promise that the declaration
2296/// will in fact be used.
2297static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002298 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002299 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2300 return true;
2301 }
2302
2303 if (isa<ObjCInterfaceDecl>(D)) {
2304 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2305 return true;
2306 }
2307
2308 if (isa<NamespaceDecl>(D)) {
2309 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2310 return true;
2311 }
2312
2313 return false;
2314}
2315
John McCall60d7b3a2010-08-24 06:29:42 +00002316ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002317Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002318 LookupResult &R,
2319 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002320 // If this is a single, fully-resolved result and we don't need ADL,
2321 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002322 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002323 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2324 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002325
2326 // We only need to check the declaration if there's exactly one
2327 // result, because in the overloaded case the results can only be
2328 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002329 if (R.isSingleResult() &&
2330 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002331 return ExprError();
2332
John McCallc373d482010-01-27 01:50:18 +00002333 // Otherwise, just build an unresolved lookup expression. Suppress
2334 // any lookup-related diagnostics; we'll hash these out later, when
2335 // we've picked a target.
2336 R.suppressDiagnostics();
2337
John McCallba135432009-11-21 08:51:07 +00002338 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002339 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002340 SS.getWithLocInContext(Context),
2341 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002342 NeedsADL, R.isOverloadedResult(),
2343 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002344
2345 return Owned(ULE);
2346}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002347
John McCallba135432009-11-21 08:51:07 +00002348/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002349ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002350Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002351 const DeclarationNameInfo &NameInfo,
2352 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002353 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002354 assert(!isa<FunctionTemplateDecl>(D) &&
2355 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002356
Abramo Bagnara25777432010-08-11 22:01:17 +00002357 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002358 if (CheckDeclInExpr(*this, Loc, D))
2359 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002360
Douglas Gregor9af2f522009-12-01 16:58:18 +00002361 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2362 // Specifically diagnose references to class templates that are missing
2363 // a template argument list.
2364 Diag(Loc, diag::err_template_decl_ref)
2365 << Template << SS.getRange();
2366 Diag(Template->getLocation(), diag::note_template_decl_here);
2367 return ExprError();
2368 }
2369
2370 // Make sure that we're referring to a value.
2371 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2372 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002373 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002374 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002375 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002376 return ExprError();
2377 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002378
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002379 // Check whether this declaration can be used. Note that we suppress
2380 // this check when we're going to perform argument-dependent lookup
2381 // on this function name, because this might not be the function
2382 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002383 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002384 return ExprError();
2385
Steve Naroffdd972f22008-09-05 22:11:13 +00002386 // Only create DeclRefExpr's for valid Decl's.
2387 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002388 return ExprError();
2389
John McCall5808ce42011-02-03 08:15:49 +00002390 // Handle members of anonymous structs and unions. If we got here,
2391 // and the reference is to a class member indirect field, then this
2392 // must be the subject of a pointer-to-member expression.
2393 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2394 if (!indirectField->isCXXClassMember())
2395 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2396 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002397
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002398 {
John McCall76a40212011-02-09 01:13:10 +00002399 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002400 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002401
2402 switch (D->getKind()) {
2403 // Ignore all the non-ValueDecl kinds.
2404#define ABSTRACT_DECL(kind)
2405#define VALUE(type, base)
2406#define DECL(type, base) \
2407 case Decl::type:
2408#include "clang/AST/DeclNodes.inc"
2409 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002410
2411 // These shouldn't make it here.
2412 case Decl::ObjCAtDefsField:
2413 case Decl::ObjCIvar:
2414 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002415
2416 // Enum constants are always r-values and never references.
2417 // Unresolved using declarations are dependent.
2418 case Decl::EnumConstant:
2419 case Decl::UnresolvedUsingValue:
2420 valueKind = VK_RValue;
2421 break;
2422
2423 // Fields and indirect fields that got here must be for
2424 // pointer-to-member expressions; we just call them l-values for
2425 // internal consistency, because this subexpression doesn't really
2426 // exist in the high-level semantics.
2427 case Decl::Field:
2428 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002429 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002430 "building reference to field in C?");
2431
2432 // These can't have reference type in well-formed programs, but
2433 // for internal consistency we do this anyway.
2434 type = type.getNonReferenceType();
2435 valueKind = VK_LValue;
2436 break;
2437
2438 // Non-type template parameters are either l-values or r-values
2439 // depending on the type.
2440 case Decl::NonTypeTemplateParm: {
2441 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2442 type = reftype->getPointeeType();
2443 valueKind = VK_LValue; // even if the parameter is an r-value reference
2444 break;
2445 }
2446
2447 // For non-references, we need to strip qualifiers just in case
2448 // the template parameter was declared as 'const int' or whatever.
2449 valueKind = VK_RValue;
2450 type = type.getUnqualifiedType();
2451 break;
2452 }
2453
2454 case Decl::Var:
2455 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002456 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002457 !type.hasQualifiers() &&
2458 type->isVoidType()) {
2459 valueKind = VK_RValue;
2460 break;
2461 }
2462 // fallthrough
2463
2464 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002465 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002466 // These are always l-values.
2467 valueKind = VK_LValue;
2468 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002469
Douglas Gregor68932842012-02-18 05:51:20 +00002470 // FIXME: Does the addition of const really only apply in
2471 // potentially-evaluated contexts? Since the variable isn't actually
2472 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002473 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002474 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2475 if (!CapturedType.isNull())
2476 type = CapturedType;
2477 }
2478
John McCall76a40212011-02-09 01:13:10 +00002479 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002480 }
2481
John McCall76a40212011-02-09 01:13:10 +00002482 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002483 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2485 type = Context.BuiltinFnTy;
2486 valueKind = VK_RValue;
2487 break;
2488 }
2489 }
2490
John McCall755d8492011-04-12 00:42:48 +00002491 const FunctionType *fty = type->castAs<FunctionType>();
2492
2493 // If we're referring to a function with an __unknown_anytype
2494 // result type, make the entire expression __unknown_anytype.
2495 if (fty->getResultType() == Context.UnknownAnyTy) {
2496 type = Context.UnknownAnyTy;
2497 valueKind = VK_RValue;
2498 break;
2499 }
2500
John McCall76a40212011-02-09 01:13:10 +00002501 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002502 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002503 valueKind = VK_LValue;
2504 break;
2505 }
2506
2507 // C99 DR 316 says that, if a function type comes from a
2508 // function definition (without a prototype), that type is only
2509 // used for checking compatibility. Therefore, when referencing
2510 // the function, we pretend that we don't have the full function
2511 // type.
John McCall755d8492011-04-12 00:42:48 +00002512 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2513 isa<FunctionProtoType>(fty))
2514 type = Context.getFunctionNoProtoType(fty->getResultType(),
2515 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002516
2517 // Functions are r-values in C.
2518 valueKind = VK_RValue;
2519 break;
2520 }
2521
2522 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002523 // If we're referring to a method with an __unknown_anytype
2524 // result type, make the entire expression __unknown_anytype.
2525 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002526 if (const FunctionProtoType *proto
2527 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002528 if (proto->getResultType() == Context.UnknownAnyTy) {
2529 type = Context.UnknownAnyTy;
2530 valueKind = VK_RValue;
2531 break;
2532 }
2533
John McCall76a40212011-02-09 01:13:10 +00002534 // C++ methods are l-values if static, r-values if non-static.
2535 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2536 valueKind = VK_LValue;
2537 break;
2538 }
2539 // fallthrough
2540
2541 case Decl::CXXConversion:
2542 case Decl::CXXDestructor:
2543 case Decl::CXXConstructor:
2544 valueKind = VK_RValue;
2545 break;
2546 }
2547
2548 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2549 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002550}
2551
John McCall755d8492011-04-12 00:42:48 +00002552ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002553 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002554
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002556 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002557 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2558 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002559 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002560 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002562
Chris Lattnerfa28b302008-01-12 08:14:25 +00002563 // Pre-defined identifiers are of type char[x], where x is the length of the
2564 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Anders Carlsson3a082d82009-09-08 18:24:21 +00002566 Decl *currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer42427402012-12-06 15:42:21 +00002567 // Blocks and lambdas can occur at global scope. Don't emit a warning.
2568 if (!currentDecl) {
2569 if (const BlockScopeInfo *BSI = getCurBlock())
2570 currentDecl = BSI->TheDecl;
2571 else if (const LambdaScopeInfo *LSI = getCurLambda())
2572 currentDecl = LSI->CallOperator;
2573 }
2574
Anders Carlsson3a082d82009-09-08 18:24:21 +00002575 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002576 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002577 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002578 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002579
Anders Carlsson773f3972009-09-11 01:22:35 +00002580 QualType ResTy;
2581 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2582 ResTy = Context.DependentTy;
2583 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002584 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002585
Anders Carlsson773f3972009-09-11 01:22:35 +00002586 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002587 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002588 ResTy = Context.WCharTy.withConst();
2589 else
2590 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002591 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2592 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002593 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002594}
2595
Richard Smith36f5cfe2012-03-09 08:00:36 +00002596ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002597 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002598 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002599 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002600 if (Invalid)
2601 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002602
Benjamin Kramerddeea562010-02-27 13:44:12 +00002603 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002604 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002606 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002607
Chris Lattnere8337df2009-12-30 21:19:39 +00002608 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002609 if (Literal.isWide())
2610 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002611 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002612 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002613 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002614 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002615 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002616 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002617 else
2618 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002619
Douglas Gregor5cee1192011-07-27 05:40:30 +00002620 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2621 if (Literal.isWide())
2622 Kind = CharacterLiteral::Wide;
2623 else if (Literal.isUTF16())
2624 Kind = CharacterLiteral::UTF16;
2625 else if (Literal.isUTF32())
2626 Kind = CharacterLiteral::UTF32;
2627
Richard Smithdd66be72012-03-08 01:34:56 +00002628 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2629 Tok.getLocation());
2630
2631 if (Literal.getUDSuffix().empty())
2632 return Owned(Lit);
2633
2634 // We're building a user-defined literal.
2635 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2636 SourceLocation UDSuffixLoc =
2637 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2638
Richard Smith36f5cfe2012-03-09 08:00:36 +00002639 // Make sure we're allowed user-defined literals here.
2640 if (!UDLScope)
2641 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2642
Richard Smithdd66be72012-03-08 01:34:56 +00002643 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2644 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002645 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2646 llvm::makeArrayRef(&Lit, 1),
2647 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002648}
2649
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002650ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2651 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2652 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2653 Context.IntTy, Loc));
2654}
2655
Richard Smithb453ad32012-03-08 08:45:32 +00002656static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2657 QualType Ty, SourceLocation Loc) {
2658 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2659
2660 using llvm::APFloat;
2661 APFloat Val(Format);
2662
2663 APFloat::opStatus result = Literal.GetFloatValue(Val);
2664
2665 // Overflow is always an error, but underflow is only an error if
2666 // we underflowed to zero (APFloat reports denormals as underflow).
2667 if ((result & APFloat::opOverflow) ||
2668 ((result & APFloat::opUnderflow) && Val.isZero())) {
2669 unsigned diagnostic;
2670 SmallString<20> buffer;
2671 if (result & APFloat::opOverflow) {
2672 diagnostic = diag::warn_float_overflow;
2673 APFloat::getLargest(Format).toString(buffer);
2674 } else {
2675 diagnostic = diag::warn_float_underflow;
2676 APFloat::getSmallest(Format).toString(buffer);
2677 }
2678
2679 S.Diag(Loc, diagnostic)
2680 << Ty
2681 << StringRef(buffer.data(), buffer.size());
2682 }
2683
2684 bool isExact = (result == APFloat::opOK);
2685 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2686}
2687
Richard Smith36f5cfe2012-03-09 08:00:36 +00002688ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002689 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002690 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002692 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002693 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 }
Ted Kremenek28396602009-01-13 23:19:12 +00002695
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002696 SmallString<128> SpellingBuffer;
2697 // NumericLiteralParser wants to overread by one character. Add padding to
2698 // the buffer in case the token is copied to the buffer. If getSpelling()
2699 // returns a StringRef to the memory buffer, it should have a null char at
2700 // the EOF, so it is also safe.
2701 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002702
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002704 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002705 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002706 if (Invalid)
2707 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002708
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002709 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002711 return ExprError();
2712
Richard Smithb453ad32012-03-08 08:45:32 +00002713 if (Literal.hasUDSuffix()) {
2714 // We're building a user-defined literal.
2715 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2716 SourceLocation UDSuffixLoc =
2717 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2718
Richard Smith36f5cfe2012-03-09 08:00:36 +00002719 // Make sure we're allowed user-defined literals here.
2720 if (!UDLScope)
2721 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002722
Richard Smith36f5cfe2012-03-09 08:00:36 +00002723 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002724 if (Literal.isFloatingLiteral()) {
2725 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2726 // long double, the literal is treated as a call of the form
2727 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002728 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002729 } else {
2730 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2731 // unsigned long long, the literal is treated as a call of the form
2732 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002733 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002734 }
2735
Richard Smith36f5cfe2012-03-09 08:00:36 +00002736 DeclarationName OpName =
2737 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2738 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2739 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2740
2741 // Perform literal operator lookup to determine if we're building a raw
2742 // literal or a cooked one.
2743 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2744 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2745 /*AllowRawAndTemplate*/true)) {
2746 case LOLR_Error:
2747 return ExprError();
2748
2749 case LOLR_Cooked: {
2750 Expr *Lit;
2751 if (Literal.isFloatingLiteral()) {
2752 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2753 } else {
2754 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2755 if (Literal.GetIntegerValue(ResultVal))
2756 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2757 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2758 Tok.getLocation());
2759 }
2760 return BuildLiteralOperatorCall(R, OpNameInfo,
2761 llvm::makeArrayRef(&Lit, 1),
2762 Tok.getLocation());
2763 }
2764
2765 case LOLR_Raw: {
2766 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2767 // literal is treated as a call of the form
2768 // operator "" X ("n")
2769 SourceLocation TokLoc = Tok.getLocation();
2770 unsigned Length = Literal.getUDSuffixOffset();
2771 QualType StrTy = Context.getConstantArrayType(
2772 Context.CharTy, llvm::APInt(32, Length + 1),
2773 ArrayType::Normal, 0);
2774 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002775 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002776 /*Pascal*/false, StrTy, &TokLoc, 1);
2777 return BuildLiteralOperatorCall(R, OpNameInfo,
2778 llvm::makeArrayRef(&Lit, 1), TokLoc);
2779 }
2780
2781 case LOLR_Template:
2782 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2783 // template), L is treated as a call fo the form
2784 // operator "" X <'c1', 'c2', ... 'ck'>()
2785 // where n is the source character sequence c1 c2 ... ck.
2786 TemplateArgumentListInfo ExplicitArgs;
2787 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2788 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2789 llvm::APSInt Value(CharBits, CharIsUnsigned);
2790 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002791 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002792 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002793 TemplateArgumentLocInfo ArgInfo;
2794 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2795 }
2796 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2797 Tok.getLocation(), &ExplicitArgs);
2798 }
2799
2800 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002801 }
2802
Chris Lattner5d661452007-08-26 03:42:43 +00002803 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002804
Chris Lattner5d661452007-08-26 03:42:43 +00002805 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002806 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002807 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002808 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002809 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002810 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002811 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002812 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002813
Richard Smithb453ad32012-03-08 08:45:32 +00002814 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002815
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002816 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002817 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002818 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002819 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002820 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002821 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002822 }
2823 }
Chris Lattner5d661452007-08-26 03:42:43 +00002824 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002825 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002826 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002827 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002828
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002829 // 'long long' is a C99 or C++11 feature.
2830 if (!getLangOpts().C99 && Literal.isLongLong) {
2831 if (getLangOpts().CPlusPlus)
2832 Diag(Tok.getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002833 getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002834 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2835 else
2836 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2837 }
Neil Boothb9449512007-08-29 22:00:19 +00002838
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002840 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2841 // The microsoft literal suffix extensions support 128-bit literals, which
2842 // may be wider than [u]intmax_t.
Richard Smith84268902012-11-29 05:41:51 +00002843 // FIXME: Actually, they don't. We seem to have accidentally invented the
2844 // i128 suffix.
2845 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2846 PP.getTargetInfo().hasInt128Type())
Stephen Canonb9e05f12012-05-03 22:49:43 +00002847 MaxWidth = 128;
2848 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002849
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 if (Literal.GetIntegerValue(ResultVal)) {
2851 // If this value didn't fit into uintmax_t, warn and force to ull.
2852 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002853 Ty = Context.UnsignedLongLongTy;
2854 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002855 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 } else {
2857 // If this value fits into a ULL, try to figure out what else it fits into
2858 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002859
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2861 // be an unsigned int.
2862 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2863
2864 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002865 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002866 if (!Literal.isLong && !Literal.isLongLong) {
2867 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002868 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002869
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 // Does it fit in a unsigned int?
2871 if (ResultVal.isIntN(IntSize)) {
2872 // Does it fit in a signed int?
2873 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002874 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002875 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002876 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002877 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002879 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002880
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002882 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002883 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002884
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 // Does it fit in a unsigned long?
2886 if (ResultVal.isIntN(LongSize)) {
2887 // Does it fit in a signed long?
2888 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002889 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002891 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002892 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002893 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002894 }
2895
Stephen Canonb9e05f12012-05-03 22:49:43 +00002896 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002897 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002898 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002899
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 // Does it fit in a unsigned long long?
2901 if (ResultVal.isIntN(LongLongSize)) {
2902 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002903 // To be compatible with MSVC, hex integer literals ending with the
2904 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002905 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002906 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002907 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002908 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002909 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002910 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002911 }
2912 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002913
2914 // If it doesn't fit in unsigned long long, and we're using Microsoft
2915 // extensions, then its a 128-bit integer literal.
Richard Smith84268902012-11-29 05:41:51 +00002916 if (Ty.isNull() && Literal.isMicrosoftInteger &&
2917 PP.getTargetInfo().hasInt128Type()) {
Stephen Canonb9e05f12012-05-03 22:49:43 +00002918 if (Literal.isUnsigned)
2919 Ty = Context.UnsignedInt128Ty;
2920 else
2921 Ty = Context.Int128Ty;
2922 Width = 128;
2923 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002924
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 // If we still couldn't decide a type, we probably have something that
2926 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002927 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002929 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002930 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002932
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002933 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002934 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002935 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002936 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002938
Chris Lattner5d661452007-08-26 03:42:43 +00002939 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2940 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002941 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002942 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002943
2944 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002945}
2946
Richard Trieuccd891a2011-09-09 01:45:06 +00002947ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002948 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002949 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002950}
2951
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002952static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2953 SourceLocation Loc,
2954 SourceRange ArgRange) {
2955 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2956 // scalar or vector data type argument..."
2957 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2958 // type (C99 6.2.5p18) or void.
2959 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2960 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2961 << T << ArgRange;
2962 return true;
2963 }
2964
2965 assert((T->isVoidType() || !T->isIncompleteType()) &&
2966 "Scalar types should always be complete");
2967 return false;
2968}
2969
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002970static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2971 SourceLocation Loc,
2972 SourceRange ArgRange,
2973 UnaryExprOrTypeTrait TraitKind) {
2974 // C99 6.5.3.4p1:
2975 if (T->isFunctionType()) {
2976 // alignof(function) is allowed as an extension.
2977 if (TraitKind == UETT_SizeOf)
2978 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2979 return false;
2980 }
2981
2982 // Allow sizeof(void)/alignof(void) as an extension.
2983 if (T->isVoidType()) {
2984 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2985 return false;
2986 }
2987
2988 return true;
2989}
2990
2991static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2992 SourceLocation Loc,
2993 SourceRange ArgRange,
2994 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002995 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2996 // runtime doesn't allow it.
2997 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002998 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2999 << T << (TraitKind == UETT_SizeOf)
3000 << ArgRange;
3001 return true;
3002 }
3003
3004 return false;
3005}
3006
Chandler Carruth9d342d02011-05-26 08:53:10 +00003007/// \brief Check the constrains on expression operands to unary type expression
3008/// and type traits.
3009///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003010/// Completes any types necessary and validates the constraints on the operand
3011/// expression. The logic mostly mirrors the type-based overload, but may modify
3012/// the expression as it completes the type for that expression through template
3013/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003014bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003015 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003016 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003017
3018 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3019 // the result is the size of the referenced type."
3020 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3021 // result shall be the alignment of the referenced type."
3022 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3023 ExprTy = Ref->getPointeeType();
3024
3025 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003026 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3027 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003028
3029 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003030 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3031 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003032 return false;
3033
Richard Trieuccd891a2011-09-09 01:45:06 +00003034 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003035 diag::err_sizeof_alignof_incomplete_type,
3036 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003037 return true;
3038
3039 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003040 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003041 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3042 ExprTy = Ref->getPointeeType();
3043
Richard Trieuccd891a2011-09-09 01:45:06 +00003044 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3045 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003046 return true;
3047
Nico Webercf739922011-06-15 02:47:03 +00003048 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003049 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003050 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3051 QualType OType = PVD->getOriginalType();
3052 QualType Type = PVD->getType();
3053 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003054 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003055 << Type << OType;
3056 Diag(PVD->getLocation(), diag::note_declared_at);
3057 }
3058 }
3059 }
3060 }
3061
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003062 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003063}
3064
3065/// \brief Check the constraints on operands to unary expression and type
3066/// traits.
3067///
3068/// This will complete any types necessary, and validate the various constraints
3069/// on those operands.
3070///
Reid Spencer5f016e22007-07-11 17:01:13 +00003071/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003072/// C99 6.3.2.1p[2-4] all state:
3073/// Except when it is the operand of the sizeof operator ...
3074///
3075/// C++ [expr.sizeof]p4
3076/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3077/// standard conversions are not applied to the operand of sizeof.
3078///
3079/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003080bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003081 SourceLocation OpLoc,
3082 SourceRange ExprRange,
3083 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003084 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003085 return false;
3086
Sebastian Redl5d484e82009-11-23 17:18:46 +00003087 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3088 // the result is the size of the referenced type."
3089 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3090 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003091 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3092 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003093
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003094 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003095 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003096
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003097 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003098 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003099 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003100 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Richard Trieuccd891a2011-09-09 01:45:06 +00003102 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003103 diag::err_sizeof_alignof_incomplete_type,
3104 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003105 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Richard Trieuccd891a2011-09-09 01:45:06 +00003107 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003108 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003109 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Chris Lattner1efaa952009-04-24 00:30:45 +00003111 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003112}
3113
Chandler Carruth9d342d02011-05-26 08:53:10 +00003114static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003115 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003116
Mike Stump1eb44332009-09-09 15:08:12 +00003117 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003118 if (isa<DeclRefExpr>(E))
3119 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003120
3121 // Cannot know anything else if the expression is dependent.
3122 if (E->isTypeDependent())
3123 return false;
3124
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003125 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003126 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3127 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003128 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003129 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003130
3131 // Alignment of a field access is always okay, so long as it isn't a
3132 // bit-field.
3133 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003134 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003135 return false;
3136
Chandler Carruth9d342d02011-05-26 08:53:10 +00003137 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138}
3139
Chandler Carruth9d342d02011-05-26 08:53:10 +00003140bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003141 E = E->IgnoreParens();
3142
3143 // Cannot know anything else if the expression is dependent.
3144 if (E->isTypeDependent())
3145 return false;
3146
Chandler Carruth9d342d02011-05-26 08:53:10 +00003147 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003148}
3149
Douglas Gregorba498172009-03-13 21:01:28 +00003150/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003151ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003152Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3153 SourceLocation OpLoc,
3154 UnaryExprOrTypeTrait ExprKind,
3155 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003156 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003157 return ExprError();
3158
John McCalla93c9342009-12-07 02:54:59 +00003159 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003160
Douglas Gregorba498172009-03-13 21:01:28 +00003161 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003162 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003163 return ExprError();
3164
3165 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003166 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3167 Context.getSizeType(),
3168 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003169}
3170
3171/// \brief Build a sizeof or alignof expression given an expression
3172/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003173ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003174Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3175 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003176 ExprResult PE = CheckPlaceholderExpr(E);
3177 if (PE.isInvalid())
3178 return ExprError();
3179
3180 E = PE.get();
3181
Douglas Gregorba498172009-03-13 21:01:28 +00003182 // Verify that the operand is valid.
3183 bool isInvalid = false;
3184 if (E->isTypeDependent()) {
3185 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003186 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003187 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003188 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003189 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003190 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003191 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003192 isInvalid = true;
3193 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003194 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003195 }
3196
3197 if (isInvalid)
3198 return ExprError();
3199
Eli Friedman71b8fb52012-01-21 01:01:51 +00003200 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Krameraccaf192012-11-14 15:08:31 +00003201 PE = TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +00003202 if (PE.isInvalid()) return ExprError();
3203 E = PE.take();
3204 }
3205
Douglas Gregorba498172009-03-13 21:01:28 +00003206 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003207 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003208 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003209 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003210}
3211
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003212/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3213/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003214/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003215ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003216Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003217 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003218 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003219 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003220 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003221
Richard Trieuccd891a2011-09-09 01:45:06 +00003222 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003223 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003224 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003225 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003226 }
Sebastian Redl05189992008-11-11 17:56:53 +00003227
Douglas Gregorba498172009-03-13 21:01:28 +00003228 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003229 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003230 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003231}
3232
John Wiegley429bb272011-04-08 18:41:53 +00003233static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003234 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003235 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003236 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003237
John McCallf6a16482010-12-04 03:47:34 +00003238 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003239 if (V.get()->getObjectKind() != OK_Ordinary) {
3240 V = S.DefaultLvalueConversion(V.take());
3241 if (V.isInvalid())
3242 return QualType();
3243 }
John McCallf6a16482010-12-04 03:47:34 +00003244
Chris Lattnercc26ed72007-08-26 05:39:26 +00003245 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003246 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003247 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003248
Chris Lattnercc26ed72007-08-26 05:39:26 +00003249 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003250 if (V.get()->getType()->isArithmeticType())
3251 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003252
John McCall2cd11fe2010-10-12 02:09:17 +00003253 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003254 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003255 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003256 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003257 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003258 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003259 }
3260
Chris Lattnercc26ed72007-08-26 05:39:26 +00003261 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003262 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003263 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003264 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003265}
3266
3267
Reid Spencer5f016e22007-07-11 17:01:13 +00003268
John McCall60d7b3a2010-08-24 06:29:42 +00003269ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003270Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003271 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003272 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003273 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003274 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003275 case tok::plusplus: Opc = UO_PostInc; break;
3276 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003277 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003278
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003279 // Since this might is a postfix expression, get rid of ParenListExprs.
3280 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3281 if (Result.isInvalid()) return ExprError();
3282 Input = Result.take();
3283
John McCall9ae2f072010-08-23 23:25:46 +00003284 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003285}
3286
John McCall1503f0d2012-07-31 05:14:30 +00003287/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3288///
3289/// \return true on error
3290static bool checkArithmeticOnObjCPointer(Sema &S,
3291 SourceLocation opLoc,
3292 Expr *op) {
3293 assert(op->getType()->isObjCObjectPointerType());
3294 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3295 return false;
3296
3297 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3298 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3299 << op->getSourceRange();
3300 return true;
3301}
3302
John McCall60d7b3a2010-08-24 06:29:42 +00003303ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003304Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3305 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003306 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003307 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003308 if (Result.isInvalid()) return ExprError();
3309 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003310
John McCall9ae2f072010-08-23 23:25:46 +00003311 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003312
David Blaikie4e4d0842012-03-11 07:00:24 +00003313 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003314 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003315 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003316 Context.DependentTy,
3317 VK_LValue, OK_Ordinary,
3318 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003319 }
3320
David Blaikie4e4d0842012-03-11 07:00:24 +00003321 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003322 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003323 LHSExp->getType()->isEnumeralType() ||
3324 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003325 RHSExp->getType()->isEnumeralType()) &&
3326 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003327 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003328 }
3329
John McCall9ae2f072010-08-23 23:25:46 +00003330 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003331}
3332
John McCall60d7b3a2010-08-24 06:29:42 +00003333ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003334Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003335 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003336 Expr *LHSExp = Base;
3337 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003338
Chris Lattner12d9ff62007-07-16 00:14:47 +00003339 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003340 if (!LHSExp->getType()->getAs<VectorType>()) {
3341 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3342 if (Result.isInvalid())
3343 return ExprError();
3344 LHSExp = Result.take();
3345 }
3346 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3347 if (Result.isInvalid())
3348 return ExprError();
3349 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003350
Chris Lattner12d9ff62007-07-16 00:14:47 +00003351 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003352 ExprValueKind VK = VK_LValue;
3353 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003354
Reid Spencer5f016e22007-07-11 17:01:13 +00003355 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003356 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003357 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003359 Expr *BaseExpr, *IndexExpr;
3360 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003361 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3362 BaseExpr = LHSExp;
3363 IndexExpr = RHSExp;
3364 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003365 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003366 BaseExpr = LHSExp;
3367 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003368 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003369 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003370 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003371 BaseExpr = LHSExp;
3372 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003373
3374 // Use custom logic if this should be the pseudo-object subscript
3375 // expression.
3376 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3377 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3378
Steve Naroff14108da2009-07-10 23:34:53 +00003379 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003380 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3381 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3382 << ResultType << BaseExpr->getSourceRange();
3383 return ExprError();
3384 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003385 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3386 // Handle the uncommon case of "123[Ptr]".
3387 BaseExpr = RHSExp;
3388 IndexExpr = LHSExp;
3389 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003390 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003391 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003392 // Handle the uncommon case of "123[Ptr]".
3393 BaseExpr = RHSExp;
3394 IndexExpr = LHSExp;
3395 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003396 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3397 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3398 << ResultType << BaseExpr->getSourceRange();
3399 return ExprError();
3400 }
John McCall183700f2009-09-21 23:43:11 +00003401 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003402 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003403 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003404 VK = LHSExp->getValueKind();
3405 if (VK != VK_RValue)
3406 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003407
Chris Lattner12d9ff62007-07-16 00:14:47 +00003408 // FIXME: need to deal with const...
3409 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003410 } else if (LHSTy->isArrayType()) {
3411 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003412 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003413 // wasn't promoted because of the C90 rule that doesn't
3414 // allow promoting non-lvalue arrays. Warn, then
3415 // force the promotion here.
3416 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3417 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003418 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3419 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003420 LHSTy = LHSExp->getType();
3421
3422 BaseExpr = LHSExp;
3423 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003424 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003425 } else if (RHSTy->isArrayType()) {
3426 // Same as previous, except for 123[f().a] case
3427 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3428 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003429 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3430 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003431 RHSTy = RHSExp->getType();
3432
3433 BaseExpr = RHSExp;
3434 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003435 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003436 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003437 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3438 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003439 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003440 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003441 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003442 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3443 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003444
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003445 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003446 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3447 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003448 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3449
Douglas Gregore7450f52009-03-24 19:52:54 +00003450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003451 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3452 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003453 // incomplete types are not object types.
3454 if (ResultType->isFunctionType()) {
3455 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3456 << ResultType << BaseExpr->getSourceRange();
3457 return ExprError();
3458 }
Mike Stump1eb44332009-09-09 15:08:12 +00003459
David Blaikie4e4d0842012-03-11 07:00:24 +00003460 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003461 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003462 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3463 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003464
3465 // C forbids expressions of unqualified void type from being l-values.
3466 // See IsCForbiddenLValueType.
3467 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003468 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003469 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003470 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003471 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003472
John McCall09431682010-11-18 19:01:18 +00003473 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003474 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003475
Mike Stumpeed9cac2009-02-19 03:04:26 +00003476 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003477 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003478}
3479
John McCall60d7b3a2010-08-24 06:29:42 +00003480ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003481 FunctionDecl *FD,
3482 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003483 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003484 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003485 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003486 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003487 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003488 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003489 return ExprError();
3490 }
3491
3492 if (Param->hasUninstantiatedDefaultArg()) {
3493 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003494
Richard Smithadb1d4c2012-07-22 23:45:10 +00003495 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3496 Param);
3497
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003498 // Instantiate the expression.
3499 MultiLevelTemplateArgumentList ArgList
3500 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003501
Nico Weber08e41a62010-11-29 18:19:25 +00003502 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003503 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003504 InstantiatingTemplate Inst(*this, CallLoc, Param,
3505 ArrayRef<TemplateArgument>(Innermost.first,
3506 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003507 if (Inst)
3508 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003509
Nico Weber08e41a62010-11-29 18:19:25 +00003510 ExprResult Result;
3511 {
3512 // C++ [dcl.fct.default]p5:
3513 // The names in the [default argument] expression are bound, and
3514 // the semantic constraints are checked, at the point where the
3515 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003516 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003517 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003518 Result = SubstExpr(UninstExpr, ArgList);
3519 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003520 if (Result.isInvalid())
3521 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003523 // Check the expression as an initializer for the parameter.
3524 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003525 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003526 InitializationKind Kind
3527 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003528 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003529 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003530
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003531 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003532 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003533 if (Result.isInvalid())
3534 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003535
David Blaikiec1c07252012-04-30 18:21:31 +00003536 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003537 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003538 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003539 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003540 }
3541
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003542 // If the default expression creates temporaries, we need to
3543 // push them to the current stack of expression temporaries so they'll
3544 // be properly destroyed.
3545 // FIXME: We should really be rebuilding the default argument with new
3546 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003547 // We don't need to do that with block decls, though, because
3548 // blocks in default argument expression can never capture anything.
3549 if (isa<ExprWithCleanups>(Param->getInit())) {
3550 // Set the "needs cleanups" bit regardless of whether there are
3551 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003552 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003553
3554 // Append all the objects to the cleanup list. Right now, this
3555 // should always be a no-op, because blocks in default argument
3556 // expressions should never be able to capture anything.
3557 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3558 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003559 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003560
3561 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003562 // Just mark all of the declarations in this potentially-evaluated expression
3563 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003564 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3565 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003566 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003567}
3568
Richard Smith831421f2012-06-25 20:30:08 +00003569
3570Sema::VariadicCallType
3571Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3572 Expr *Fn) {
3573 if (Proto && Proto->isVariadic()) {
3574 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3575 return VariadicConstructor;
3576 else if (Fn && Fn->getType()->isBlockPointerType())
3577 return VariadicBlock;
3578 else if (FDecl) {
3579 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3580 if (Method->isInstance())
3581 return VariadicMethod;
3582 }
3583 return VariadicFunction;
3584 }
3585 return VariadicDoesNotApply;
3586}
3587
Douglas Gregor88a35142008-12-22 05:46:06 +00003588/// ConvertArgumentsForCall - Converts the arguments specified in
3589/// Args/NumArgs to the parameter types of the function FDecl with
3590/// function prototype Proto. Call is the call expression itself, and
3591/// Fn is the function expression. For a C++ member function, this
3592/// routine does not attempt to convert the object argument. Returns
3593/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003594bool
3595Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003596 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003597 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003598 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003599 SourceLocation RParenLoc,
3600 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003601 // Bail out early if calling a builtin with custom typechecking.
3602 // We don't need to do this in the
3603 if (FDecl)
3604 if (unsigned ID = FDecl->getBuiltinID())
3605 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3606 return false;
3607
Mike Stumpeed9cac2009-02-19 03:04:26 +00003608 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003609 // assignment, to the types of the corresponding parameter, ...
3610 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003611 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003612 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003613 unsigned FnKind = Fn->getType()->isBlockPointerType()
3614 ? 1 /* block */
3615 : (IsExecConfig ? 3 /* kernel function (exec config) */
3616 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003617
Douglas Gregor88a35142008-12-22 05:46:06 +00003618 // If too few arguments are available (and we don't have default
3619 // arguments for the remaining parameters), don't make the call.
3620 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003621 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003622 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3623 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3624 ? diag::err_typecheck_call_too_few_args_one
3625 : diag::err_typecheck_call_too_few_args_at_least_one)
3626 << FnKind
3627 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3628 else
3629 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3630 ? diag::err_typecheck_call_too_few_args
3631 : diag::err_typecheck_call_too_few_args_at_least)
3632 << FnKind
3633 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003634
3635 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003636 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003637 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3638 << FDecl;
3639
3640 return true;
3641 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003642 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003643 }
3644
3645 // If too many are passed and not variadic, error on the extras and drop
3646 // them.
3647 if (NumArgs > NumArgsInProto) {
3648 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003649 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3650 Diag(Args[NumArgsInProto]->getLocStart(),
3651 MinArgs == NumArgsInProto
3652 ? diag::err_typecheck_call_too_many_args_one
3653 : diag::err_typecheck_call_too_many_args_at_most_one)
3654 << FnKind
3655 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3656 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3657 Args[NumArgs-1]->getLocEnd());
3658 else
3659 Diag(Args[NumArgsInProto]->getLocStart(),
3660 MinArgs == NumArgsInProto
3661 ? diag::err_typecheck_call_too_many_args
3662 : diag::err_typecheck_call_too_many_args_at_most)
3663 << FnKind
3664 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3665 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3666 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003667
3668 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003669 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003670 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3671 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003672
Douglas Gregor88a35142008-12-22 05:46:06 +00003673 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003674 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003675 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003676 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003677 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003678 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003679 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3680
Daniel Dunbar96a00142012-03-09 18:35:03 +00003681 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003682 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003683 if (Invalid)
3684 return true;
3685 unsigned TotalNumArgs = AllArgs.size();
3686 for (unsigned i = 0; i < TotalNumArgs; ++i)
3687 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003688
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003689 return false;
3690}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003691
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003692bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3693 FunctionDecl *FDecl,
3694 const FunctionProtoType *Proto,
3695 unsigned FirstProtoArg,
3696 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003697 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003698 VariadicCallType CallType,
3699 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003700 unsigned NumArgsInProto = Proto->getNumArgs();
3701 unsigned NumArgsToCheck = NumArgs;
3702 bool Invalid = false;
3703 if (NumArgs != NumArgsInProto)
3704 // Use default arguments for missing arguments
3705 NumArgsToCheck = NumArgsInProto;
3706 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003707 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003708 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003709 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003710
Douglas Gregor88a35142008-12-22 05:46:06 +00003711 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003712 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003713 if (ArgIx < NumArgs) {
3714 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003715
Daniel Dunbar96a00142012-03-09 18:35:03 +00003716 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003717 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003718 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003719 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003720
Douglas Gregora188ff22009-12-22 16:09:06 +00003721 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003722 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003723 if (FDecl && i < FDecl->getNumParams())
3724 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003725
John McCall5acb0c92011-10-17 18:40:02 +00003726 // Strip the unbridged-cast placeholder expression off, if applicable.
3727 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3728 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3729 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3730 Arg = stripARCUnbridgedCast(Arg);
3731
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00003732 InitializedEntity Entity = Param ?
3733 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3734 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3735 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003736 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003737 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003738 Owned(Arg),
3739 /*TopLevelOfInitList=*/false,
3740 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003741 if (ArgE.isInvalid())
3742 return true;
3743
3744 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003745 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003746 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003747
John McCall60d7b3a2010-08-24 06:29:42 +00003748 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003749 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003750 if (ArgExpr.isInvalid())
3751 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003752
Anders Carlsson56c5e332009-08-25 03:49:14 +00003753 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003754 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003755
3756 // Check for array bounds violations for each argument to the call. This
3757 // check only triggers warnings when the argument isn't a more complex Expr
3758 // with its own checking, such as a BinaryOperator.
3759 CheckArrayAccess(Arg);
3760
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003761 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3762 CheckStaticArrayArgument(CallLoc, Param, Arg);
3763
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003764 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003765 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003766
Douglas Gregor88a35142008-12-22 05:46:06 +00003767 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003768 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003769 // Assume that extern "C" functions with variadic arguments that
3770 // return __unknown_anytype aren't *really* variadic.
3771 if (Proto->getResultType() == Context.UnknownAnyTy &&
3772 FDecl && FDecl->isExternC()) {
3773 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3774 ExprResult arg;
3775 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3776 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3777 else
3778 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3779 Invalid |= arg.isInvalid();
3780 AllArgs.push_back(arg.take());
3781 }
3782
3783 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3784 } else {
3785 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003786 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3787 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003788 Invalid |= Arg.isInvalid();
3789 AllArgs.push_back(Arg.take());
3790 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003791 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003792
3793 // Check for array bounds violations.
3794 for (unsigned i = ArgIx; i != NumArgs; ++i)
3795 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003796 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003797 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003798}
3799
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003800static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3801 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3802 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3803 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3804 << ATL->getLocalSourceRange();
3805}
3806
3807/// CheckStaticArrayArgument - If the given argument corresponds to a static
3808/// array parameter, check that it is non-null, and that if it is formed by
3809/// array-to-pointer decay, the underlying array is sufficiently large.
3810///
3811/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3812/// array type derivation, then for each call to the function, the value of the
3813/// corresponding actual argument shall provide access to the first element of
3814/// an array with at least as many elements as specified by the size expression.
3815void
3816Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3817 ParmVarDecl *Param,
3818 const Expr *ArgExpr) {
3819 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003820 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003821 return;
3822
3823 QualType OrigTy = Param->getOriginalType();
3824
3825 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3826 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3827 return;
3828
3829 if (ArgExpr->isNullPointerConstant(Context,
3830 Expr::NPC_NeverValueDependent)) {
3831 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3832 DiagnoseCalleeStaticArrayParam(*this, Param);
3833 return;
3834 }
3835
3836 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3837 if (!CAT)
3838 return;
3839
3840 const ConstantArrayType *ArgCAT =
3841 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3842 if (!ArgCAT)
3843 return;
3844
3845 if (ArgCAT->getSize().ult(CAT->getSize())) {
3846 Diag(CallLoc, diag::warn_static_array_too_small)
3847 << ArgExpr->getSourceRange()
3848 << (unsigned) ArgCAT->getSize().getZExtValue()
3849 << (unsigned) CAT->getSize().getZExtValue();
3850 DiagnoseCalleeStaticArrayParam(*this, Param);
3851 }
3852}
3853
John McCall755d8492011-04-12 00:42:48 +00003854/// Given a function expression of unknown-any type, try to rebuild it
3855/// to have a function type.
3856static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3857
Steve Narofff69936d2007-09-16 03:34:24 +00003858/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003859/// This provides the location of the left/right parens and a list of comma
3860/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003861ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003862Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003863 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003864 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003865 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003866 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003867 if (Result.isInvalid()) return ExprError();
3868 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003869
David Blaikie4e4d0842012-03-11 07:00:24 +00003870 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003871 // If this is a pseudo-destructor expression, build the call immediately.
3872 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003873 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003874 // Pseudo-destructor calls should not have any arguments.
3875 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003876 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003877 SourceRange(ArgExprs[0]->getLocStart(),
3878 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003879 }
Mike Stump1eb44332009-09-09 15:08:12 +00003880
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003881 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3882 Context.VoidTy, VK_RValue,
3883 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003884 }
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Douglas Gregor17330012009-02-04 15:01:18 +00003886 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003887 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003888 // FIXME: Will need to cache the results of name lookup (including ADL) in
3889 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003890 bool Dependent = false;
3891 if (Fn->isTypeDependent())
3892 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003893 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003894 Dependent = true;
3895
Peter Collingbournee08ce652011-02-09 21:07:24 +00003896 if (Dependent) {
3897 if (ExecConfig) {
3898 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003899 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003900 Context.DependentTy, VK_RValue, RParenLoc));
3901 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003902 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003903 Context.DependentTy, VK_RValue,
3904 RParenLoc));
3905 }
3906 }
Douglas Gregor17330012009-02-04 15:01:18 +00003907
3908 // Determine whether this is a call to an object (C++ [over.call.object]).
3909 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003910 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3911 ArgExprs.data(),
3912 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003913
John McCall755d8492011-04-12 00:42:48 +00003914 if (Fn->getType() == Context.UnknownAnyTy) {
3915 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3916 if (result.isInvalid()) return ExprError();
3917 Fn = result.take();
3918 }
3919
John McCall864c0412011-04-26 20:42:42 +00003920 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003921 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3922 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003923 }
John McCall864c0412011-04-26 20:42:42 +00003924 }
John McCall129e2df2009-11-30 22:42:35 +00003925
John McCall864c0412011-04-26 20:42:42 +00003926 // Check for overloaded calls. This can happen even in C due to extensions.
3927 if (Fn->getType() == Context.OverloadTy) {
3928 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3929
Douglas Gregoree697e62011-10-13 18:10:35 +00003930 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003931 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003932 OverloadExpr *ovl = find.Expression;
3933 if (isa<UnresolvedLookupExpr>(ovl)) {
3934 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003935 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3936 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003937 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003938 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3939 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003940 }
3941 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003942 }
3943
Douglas Gregorfa047642009-02-04 00:32:51 +00003944 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003945 if (Fn->getType() == Context.UnknownAnyTy) {
3946 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3947 if (result.isInvalid()) return ExprError();
3948 Fn = result.take();
3949 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003950
Eli Friedmanefa42f72009-12-26 03:35:45 +00003951 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003952
John McCall3b4294e2009-12-16 12:17:52 +00003953 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003954 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3955 if (UnOp->getOpcode() == UO_AddrOf)
3956 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3957
John McCall3b4294e2009-12-16 12:17:52 +00003958 if (isa<DeclRefExpr>(NakedFn))
3959 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003960 else if (isa<MemberExpr>(NakedFn))
3961 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003962
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003963 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3964 ArgExprs.size(), RParenLoc, ExecConfig,
3965 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003966}
3967
3968ExprResult
3969Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003970 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003971 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3972 if (!ConfigDecl)
3973 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3974 << "cudaConfigureCall");
3975 QualType ConfigQTy = ConfigDecl->getType();
3976
3977 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003978 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003979 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003980
Peter Collingbourne1f240762011-10-02 23:49:29 +00003981 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3982 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003983}
3984
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003985/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3986///
3987/// __builtin_astype( value, dst type )
3988///
Richard Trieuccd891a2011-09-09 01:45:06 +00003989ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003990 SourceLocation BuiltinLoc,
3991 SourceLocation RParenLoc) {
3992 ExprValueKind VK = VK_RValue;
3993 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003994 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3995 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003996 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3997 return ExprError(Diag(BuiltinLoc,
3998 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003999 << DstTy
4000 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00004001 << E->getSourceRange());
4002 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00004003 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004004}
4005
John McCall3b4294e2009-12-16 12:17:52 +00004006/// BuildResolvedCallExpr - Build a call to a resolved expression,
4007/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004008/// unary-convert to an expression of function-pointer or
4009/// block-pointer type.
4010///
4011/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004012ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004013Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4014 SourceLocation LParenLoc,
4015 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004016 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004017 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004018 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004019 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004020
Chris Lattner04421082008-04-08 04:40:51 +00004021 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004022 // We special-case function promotion here because we only allow promoting
4023 // builtin functions to function pointers in the callee of a call.
4024 ExprResult Result;
4025 if (BuiltinID &&
4026 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4027 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4028 CK_BuiltinFnToFnPtr).take();
4029 } else {
4030 Result = UsualUnaryConversions(Fn);
4031 }
John Wiegley429bb272011-04-08 18:41:53 +00004032 if (Result.isInvalid())
4033 return ExprError();
4034 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004035
Chris Lattner925e60d2007-12-28 05:29:59 +00004036 // Make the call expr early, before semantic checks. This guarantees cleanup
4037 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004038 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004039 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004040 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4041 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004042 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004043 Context.BoolTy,
4044 VK_RValue,
4045 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004046 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004047 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004048 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004049 Context.BoolTy,
4050 VK_RValue,
4051 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004052
John McCall8e10f3b2011-02-26 05:39:39 +00004053 // Bail out early if calling a builtin with custom typechecking.
4054 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4055 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4056
John McCall1de4d4e2011-04-07 08:22:57 +00004057 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004058 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004059 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004060 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4061 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004062 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004063 if (FuncT == 0)
4064 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4065 << Fn->getType() << Fn->getSourceRange());
4066 } else if (const BlockPointerType *BPT =
4067 Fn->getType()->getAs<BlockPointerType>()) {
4068 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4069 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004070 // Handle calls to expressions of unknown-any type.
4071 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004072 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004073 if (rewrite.isInvalid()) return ExprError();
4074 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004075 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004076 goto retry;
4077 }
4078
Sebastian Redl0eb23302009-01-19 00:08:26 +00004079 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4080 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004081 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004082
David Blaikie4e4d0842012-03-11 07:00:24 +00004083 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004084 if (Config) {
4085 // CUDA: Kernel calls must be to global functions
4086 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4087 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4088 << FDecl->getName() << Fn->getSourceRange());
4089
4090 // CUDA: Kernel function must have 'void' return type
4091 if (!FuncT->getResultType()->isVoidType())
4092 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4093 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004094 } else {
4095 // CUDA: Calls to global functions must be configured
4096 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4097 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4098 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004099 }
4100 }
4101
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004102 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004103 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004104 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004105 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004106 return ExprError();
4107
Chris Lattner925e60d2007-12-28 05:29:59 +00004108 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004109 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004110 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004111
Richard Smith831421f2012-06-25 20:30:08 +00004112 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4113 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004114 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004115 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004116 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004117 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004118 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004119
Douglas Gregor74734d52009-04-02 15:37:10 +00004120 if (FDecl) {
4121 // Check if we have too few/too many template arguments, based
4122 // on our knowledge of the function definition.
4123 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004124 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004125 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004126 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004127 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4128 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004129 }
Douglas Gregor46542412010-10-25 20:39:23 +00004130
4131 // If the function we're calling isn't a function prototype, but we have
4132 // a function prototype from a prior declaratiom, use that prototype.
4133 if (!FDecl->hasPrototype())
4134 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004135 }
4136
Steve Naroffb291ab62007-08-28 23:30:39 +00004137 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004138 for (unsigned i = 0; i != NumArgs; i++) {
4139 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004140
4141 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004142 InitializedEntity Entity
4143 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004144 Proto->getArgType(i),
4145 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004146 ExprResult ArgE = PerformCopyInitialization(Entity,
4147 SourceLocation(),
4148 Owned(Arg));
4149 if (ArgE.isInvalid())
4150 return true;
4151
4152 Arg = ArgE.takeAs<Expr>();
4153
4154 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004155 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4156
4157 if (ArgE.isInvalid())
4158 return true;
4159
4160 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004161 }
4162
Daniel Dunbar96a00142012-03-09 18:35:03 +00004163 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004164 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004165 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004166 return ExprError();
4167
Chris Lattner925e60d2007-12-28 05:29:59 +00004168 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004169 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004170 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004171
Douglas Gregor88a35142008-12-22 05:46:06 +00004172 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4173 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004174 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4175 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004176
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004177 // Check for sentinels
4178 if (NDecl)
4179 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Chris Lattner59907c42007-08-10 20:18:51 +00004181 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004182 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004183 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004184 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004185
John McCall8e10f3b2011-02-26 05:39:39 +00004186 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004187 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004188 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004189 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004190 return ExprError();
4191 }
Chris Lattner59907c42007-08-10 20:18:51 +00004192
John McCall9ae2f072010-08-23 23:25:46 +00004193 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004194}
4195
John McCall60d7b3a2010-08-24 06:29:42 +00004196ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004197Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004198 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004199 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004200 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004201 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004202
4203 TypeSourceInfo *TInfo;
4204 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4205 if (!TInfo)
4206 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4207
John McCall9ae2f072010-08-23 23:25:46 +00004208 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004209}
4210
John McCall60d7b3a2010-08-24 06:29:42 +00004211ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004212Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004213 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004214 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004215
Eli Friedman6223c222008-05-20 05:22:08 +00004216 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004217 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004218 diag::err_illegal_decl_array_incomplete_type,
4219 SourceRange(LParenLoc,
4220 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004221 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004222 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004223 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004224 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004225 } else if (!literalType->isDependentType() &&
4226 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004227 diag::err_typecheck_decl_incomplete_type,
4228 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004229 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004230
Douglas Gregor99a2e602009-12-16 01:38:02 +00004231 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004232 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004233 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004234 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004235 SourceRange(LParenLoc, RParenLoc),
4236 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004237 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004238 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4239 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004240 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004241 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004242 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004243
Chris Lattner371f2582008-12-04 23:50:19 +00004244 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004245 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004246 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004247 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004248 }
Eli Friedman08544622009-12-22 02:35:53 +00004249
John McCallf89e55a2010-11-18 06:31:45 +00004250 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004251 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004252
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004253 return MaybeBindToTemporary(
4254 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004255 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004256}
4257
John McCall60d7b3a2010-08-24 06:29:42 +00004258ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004259Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004260 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004261 // Immediately handle non-overload placeholders. Overloads can be
4262 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004263 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4264 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4265 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004266
4267 // Ignore failures; dropping the entire initializer list because
4268 // of one failure would be terrible for indexing/etc.
4269 if (result.isInvalid()) continue;
4270
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004271 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004272 }
4273 }
4274
Steve Naroff08d92e42007-09-15 18:49:24 +00004275 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004276 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004277
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004278 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4279 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004280 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004281 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004282}
4283
John McCalldc05b112011-09-10 01:16:55 +00004284/// Do an explicit extend of the given block pointer if we're in ARC.
4285static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4286 assert(E.get()->getType()->isBlockPointerType());
4287 assert(E.get()->isRValue());
4288
4289 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004290 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004291
4292 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004293 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004294 /*base path*/ 0, VK_RValue);
4295 S.ExprNeedsCleanups = true;
4296}
4297
4298/// Prepare a conversion of the given expression to an ObjC object
4299/// pointer type.
4300CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4301 QualType type = E.get()->getType();
4302 if (type->isObjCObjectPointerType()) {
4303 return CK_BitCast;
4304 } else if (type->isBlockPointerType()) {
4305 maybeExtendBlockObject(*this, E);
4306 return CK_BlockPointerToObjCPointerCast;
4307 } else {
4308 assert(type->isPointerType());
4309 return CK_CPointerToObjCPointerCast;
4310 }
4311}
4312
John McCallf3ea8cf2010-11-14 08:17:51 +00004313/// Prepares for a scalar cast, performing all the necessary stages
4314/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004315CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004316 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4317 // Also, callers should have filtered out the invalid cases with
4318 // pointers. Everything else should be possible.
4319
John Wiegley429bb272011-04-08 18:41:53 +00004320 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004321 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004322 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004323
John McCall1d9b3b22011-09-09 05:25:32 +00004324 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004325 case Type::STK_MemberPointer:
4326 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004327
John McCall1d9b3b22011-09-09 05:25:32 +00004328 case Type::STK_CPointer:
4329 case Type::STK_BlockPointer:
4330 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004331 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004332 case Type::STK_CPointer:
4333 return CK_BitCast;
4334 case Type::STK_BlockPointer:
4335 return (SrcKind == Type::STK_BlockPointer
4336 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4337 case Type::STK_ObjCObjectPointer:
4338 if (SrcKind == Type::STK_ObjCObjectPointer)
4339 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004340 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004341 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004342 maybeExtendBlockObject(*this, Src);
4343 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004344 case Type::STK_Bool:
4345 return CK_PointerToBoolean;
4346 case Type::STK_Integral:
4347 return CK_PointerToIntegral;
4348 case Type::STK_Floating:
4349 case Type::STK_FloatingComplex:
4350 case Type::STK_IntegralComplex:
4351 case Type::STK_MemberPointer:
4352 llvm_unreachable("illegal cast from pointer");
4353 }
David Blaikie7530c032012-01-17 06:56:22 +00004354 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004355
John McCalldaa8e4e2010-11-15 09:13:47 +00004356 case Type::STK_Bool: // casting from bool is like casting from an integer
4357 case Type::STK_Integral:
4358 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004359 case Type::STK_CPointer:
4360 case Type::STK_ObjCObjectPointer:
4361 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004362 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004363 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004364 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004365 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004366 case Type::STK_Bool:
4367 return CK_IntegralToBoolean;
4368 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004369 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004370 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004371 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004372 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004373 Src = ImpCastExprToType(Src.take(),
4374 DestTy->castAs<ComplexType>()->getElementType(),
4375 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004376 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004377 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004378 Src = ImpCastExprToType(Src.take(),
4379 DestTy->castAs<ComplexType>()->getElementType(),
4380 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004381 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004382 case Type::STK_MemberPointer:
4383 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004384 }
David Blaikie7530c032012-01-17 06:56:22 +00004385 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004386
John McCalldaa8e4e2010-11-15 09:13:47 +00004387 case Type::STK_Floating:
4388 switch (DestTy->getScalarTypeKind()) {
4389 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004390 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004391 case Type::STK_Bool:
4392 return CK_FloatingToBoolean;
4393 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004394 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004395 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004396 Src = ImpCastExprToType(Src.take(),
4397 DestTy->castAs<ComplexType>()->getElementType(),
4398 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004399 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004400 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004401 Src = ImpCastExprToType(Src.take(),
4402 DestTy->castAs<ComplexType>()->getElementType(),
4403 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004404 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004405 case Type::STK_CPointer:
4406 case Type::STK_ObjCObjectPointer:
4407 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004408 llvm_unreachable("valid float->pointer cast?");
4409 case Type::STK_MemberPointer:
4410 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004411 }
David Blaikie7530c032012-01-17 06:56:22 +00004412 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004413
John McCalldaa8e4e2010-11-15 09:13:47 +00004414 case Type::STK_FloatingComplex:
4415 switch (DestTy->getScalarTypeKind()) {
4416 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004417 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004418 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004419 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004420 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004421 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4422 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004423 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004424 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004425 return CK_FloatingCast;
4426 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004427 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004428 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004429 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004430 Src = ImpCastExprToType(Src.take(),
4431 SrcTy->castAs<ComplexType>()->getElementType(),
4432 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004433 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004434 case Type::STK_CPointer:
4435 case Type::STK_ObjCObjectPointer:
4436 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004437 llvm_unreachable("valid complex float->pointer cast?");
4438 case Type::STK_MemberPointer:
4439 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004440 }
David Blaikie7530c032012-01-17 06:56:22 +00004441 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004442
John McCalldaa8e4e2010-11-15 09:13:47 +00004443 case Type::STK_IntegralComplex:
4444 switch (DestTy->getScalarTypeKind()) {
4445 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004446 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004447 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004448 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004449 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004450 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4451 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004452 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004453 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004454 return CK_IntegralCast;
4455 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004456 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004457 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004458 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004459 Src = ImpCastExprToType(Src.take(),
4460 SrcTy->castAs<ComplexType>()->getElementType(),
4461 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004462 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004463 case Type::STK_CPointer:
4464 case Type::STK_ObjCObjectPointer:
4465 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004466 llvm_unreachable("valid complex int->pointer cast?");
4467 case Type::STK_MemberPointer:
4468 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004469 }
David Blaikie7530c032012-01-17 06:56:22 +00004470 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004471 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004472
John McCallf3ea8cf2010-11-14 08:17:51 +00004473 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004474}
4475
Anders Carlssonc3516322009-10-16 02:48:28 +00004476bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004477 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004478 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004479
Anders Carlssona64db8f2007-11-27 05:51:55 +00004480 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004481 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004482 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004483 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004484 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004485 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004486 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004487 } else
4488 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004489 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004490 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004491
John McCall2de56d12010-08-25 11:45:40 +00004492 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004493 return false;
4494}
4495
John Wiegley429bb272011-04-08 18:41:53 +00004496ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4497 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004498 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004499
Anders Carlsson16a89042009-10-16 05:23:41 +00004500 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004501
Nate Begeman9b10da62009-06-27 22:05:55 +00004502 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4503 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004504 // In OpenCL, casts between vectors of different types are not allowed.
4505 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004506 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004507 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004508 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004509 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004510 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004511 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004512 return ExprError();
4513 }
John McCall2de56d12010-08-25 11:45:40 +00004514 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004515 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004516 }
4517
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004518 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004519 // conversion will take place first from scalar to elt type, and then
4520 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004521 if (SrcTy->isPointerType())
4522 return Diag(R.getBegin(),
4523 diag::err_invalid_conversion_between_vector_and_scalar)
4524 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004525
4526 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004527 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004528 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004529 if (CastExprRes.isInvalid())
4530 return ExprError();
4531 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004532
John McCall2de56d12010-08-25 11:45:40 +00004533 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004534 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004535}
4536
John McCall60d7b3a2010-08-24 06:29:42 +00004537ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004538Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4539 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004540 SourceLocation RParenLoc, Expr *CastExpr) {
4541 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004542 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004543
Richard Trieuccd891a2011-09-09 01:45:06 +00004544 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004545 if (D.isInvalidType())
4546 return ExprError();
4547
David Blaikie4e4d0842012-03-11 07:00:24 +00004548 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004549 // Check that there are no default arguments (C++ only).
4550 CheckExtraCXXDefaultArguments(D);
4551 }
4552
John McCalle82247a2011-10-01 05:17:03 +00004553 checkUnusedDeclAttributes(D);
4554
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004555 QualType castType = castTInfo->getType();
4556 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004557
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004558 bool isVectorLiteral = false;
4559
4560 // Check for an altivec or OpenCL literal,
4561 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004562 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4563 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004564 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004565 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004566 if (PLE && PLE->getNumExprs() == 0) {
4567 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4568 return ExprError();
4569 }
4570 if (PE || PLE->getNumExprs() == 1) {
4571 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4572 if (!E->getType()->isVectorType())
4573 isVectorLiteral = true;
4574 }
4575 else
4576 isVectorLiteral = true;
4577 }
4578
4579 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4580 // then handle it as such.
4581 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004582 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004583
Nate Begeman2ef13e52009-08-10 23:49:36 +00004584 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004585 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4586 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004587 if (isa<ParenListExpr>(CastExpr)) {
4588 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004589 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004590 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004591 }
John McCallb042fdf2010-01-15 18:56:44 +00004592
Richard Trieuccd891a2011-09-09 01:45:06 +00004593 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004594}
4595
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004596ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4597 SourceLocation RParenLoc, Expr *E,
4598 TypeSourceInfo *TInfo) {
4599 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4600 "Expected paren or paren list expression");
4601
4602 Expr **exprs;
4603 unsigned numExprs;
4604 Expr *subExpr;
4605 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4606 exprs = PE->getExprs();
4607 numExprs = PE->getNumExprs();
4608 } else {
4609 subExpr = cast<ParenExpr>(E)->getSubExpr();
4610 exprs = &subExpr;
4611 numExprs = 1;
4612 }
4613
4614 QualType Ty = TInfo->getType();
4615 assert(Ty->isVectorType() && "Expected vector type");
4616
Chris Lattner5f9e2722011-07-23 10:55:15 +00004617 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004618 const VectorType *VTy = Ty->getAs<VectorType>();
4619 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4620
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004621 // '(...)' form of vector initialization in AltiVec: the number of
4622 // initializers must be one or must match the size of the vector.
4623 // If a single value is specified in the initializer then it will be
4624 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004625 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004626 // The number of initializers must be one or must match the size of the
4627 // vector. If a single value is specified in the initializer then it will
4628 // be replicated to all the components of the vector
4629 if (numExprs == 1) {
4630 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004631 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4632 if (Literal.isInvalid())
4633 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004634 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004635 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004636 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4637 }
4638 else if (numExprs < numElems) {
4639 Diag(E->getExprLoc(),
4640 diag::err_incorrect_number_of_vector_initializers);
4641 return ExprError();
4642 }
4643 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004644 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004645 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004646 else {
4647 // For OpenCL, when the number of initializers is a single value,
4648 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004649 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004650 VTy->getVectorKind() == VectorType::GenericVector &&
4651 numExprs == 1) {
4652 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004653 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4654 if (Literal.isInvalid())
4655 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004656 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004657 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004658 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4659 }
4660
Benjamin Kramer14c59822012-02-14 12:06:21 +00004661 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004662 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004663 // FIXME: This means that pretty-printing the final AST will produce curly
4664 // braces instead of the original commas.
4665 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004666 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004667 initE->setType(Ty);
4668 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4669}
4670
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004671/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4672/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004673ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004674Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4675 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004676 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004677 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
John McCall60d7b3a2010-08-24 06:29:42 +00004679 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Nate Begeman2ef13e52009-08-10 23:49:36 +00004681 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004682 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4683 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004684
John McCall9ae2f072010-08-23 23:25:46 +00004685 if (Result.isInvalid()) return ExprError();
4686
4687 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004688}
4689
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004690ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4691 SourceLocation R,
4692 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004693 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004694 return Owned(expr);
4695}
4696
Chandler Carruth82214a82011-02-18 23:54:50 +00004697/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004698/// constant and the other is not a pointer. Returns true if a diagnostic is
4699/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004700bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004701 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004702 Expr *NullExpr = LHSExpr;
4703 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004704 Expr::NullPointerConstantKind NullKind =
4705 NullExpr->isNullPointerConstant(Context,
4706 Expr::NPC_ValueDependentIsNotNull);
4707
4708 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004709 NullExpr = RHSExpr;
4710 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004711 NullKind =
4712 NullExpr->isNullPointerConstant(Context,
4713 Expr::NPC_ValueDependentIsNotNull);
4714 }
4715
4716 if (NullKind == Expr::NPCK_NotNull)
4717 return false;
4718
David Blaikie50800fc2012-08-08 17:33:31 +00004719 if (NullKind == Expr::NPCK_ZeroExpression)
4720 return false;
4721
4722 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004723 // In this case, check to make sure that we got here from a "NULL"
4724 // string in the source code.
4725 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004726 SourceLocation loc = NullExpr->getExprLoc();
4727 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004728 return false;
4729 }
4730
Richard Smith4e24f0f2013-01-02 12:01:23 +00004731 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carruth82214a82011-02-18 23:54:50 +00004732 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4733 << NonPointerExpr->getType() << DiagType
4734 << NonPointerExpr->getSourceRange();
4735 return true;
4736}
4737
Richard Trieu26f96072011-09-02 01:51:02 +00004738/// \brief Return false if the condition expression is valid, true otherwise.
4739static bool checkCondition(Sema &S, Expr *Cond) {
4740 QualType CondTy = Cond->getType();
4741
4742 // C99 6.5.15p2
4743 if (CondTy->isScalarType()) return false;
4744
4745 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004746 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004747 return false;
4748
4749 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004750 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004751 diag::err_typecheck_cond_expect_scalar :
4752 diag::err_typecheck_cond_expect_scalar_or_vector)
4753 << CondTy;
4754 return true;
4755}
4756
4757/// \brief Return false if the two expressions can be converted to a vector,
4758/// true otherwise
4759static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4760 ExprResult &RHS,
4761 QualType CondTy) {
4762 // Both operands should be of scalar type.
4763 if (!LHS.get()->getType()->isScalarType()) {
4764 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4765 << CondTy;
4766 return true;
4767 }
4768 if (!RHS.get()->getType()->isScalarType()) {
4769 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4770 << CondTy;
4771 return true;
4772 }
4773
4774 // Implicity convert these scalars to the type of the condition.
4775 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4776 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4777 return false;
4778}
4779
4780/// \brief Handle when one or both operands are void type.
4781static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4782 ExprResult &RHS) {
4783 Expr *LHSExpr = LHS.get();
4784 Expr *RHSExpr = RHS.get();
4785
4786 if (!LHSExpr->getType()->isVoidType())
4787 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4788 << RHSExpr->getSourceRange();
4789 if (!RHSExpr->getType()->isVoidType())
4790 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4791 << LHSExpr->getSourceRange();
4792 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4793 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4794 return S.Context.VoidTy;
4795}
4796
4797/// \brief Return false if the NullExpr can be promoted to PointerTy,
4798/// true otherwise.
4799static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4800 QualType PointerTy) {
4801 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4802 !NullExpr.get()->isNullPointerConstant(S.Context,
4803 Expr::NPC_ValueDependentIsNull))
4804 return true;
4805
4806 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4807 return false;
4808}
4809
4810/// \brief Checks compatibility between two pointers and return the resulting
4811/// type.
4812static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4813 ExprResult &RHS,
4814 SourceLocation Loc) {
4815 QualType LHSTy = LHS.get()->getType();
4816 QualType RHSTy = RHS.get()->getType();
4817
4818 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4819 // Two identical pointers types are always compatible.
4820 return LHSTy;
4821 }
4822
4823 QualType lhptee, rhptee;
4824
4825 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004826 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4827 lhptee = LHSBTy->getPointeeType();
4828 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004829 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004830 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4831 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004832 }
4833
Eli Friedmanae916a12012-04-05 22:30:04 +00004834 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4835 // differently qualified versions of compatible types, the result type is
4836 // a pointer to an appropriately qualified version of the composite
4837 // type.
4838
4839 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4840 // clause doesn't make sense for our extensions. E.g. address space 2 should
4841 // be incompatible with address space 3: they may live on different devices or
4842 // anything.
4843 Qualifiers lhQual = lhptee.getQualifiers();
4844 Qualifiers rhQual = rhptee.getQualifiers();
4845
4846 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4847 lhQual.removeCVRQualifiers();
4848 rhQual.removeCVRQualifiers();
4849
4850 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4851 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4852
4853 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4854
4855 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004856 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4857 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4858 << RHS.get()->getSourceRange();
4859 // In this situation, we assume void* type. No especially good
4860 // reason, but this is what gcc does, and we do have to pick
4861 // to get a consistent AST.
4862 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4863 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4864 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4865 return incompatTy;
4866 }
4867
4868 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004869 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4870 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004871
Eli Friedmanae916a12012-04-05 22:30:04 +00004872 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4873 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4874 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004875}
4876
4877/// \brief Return the resulting type when the operands are both block pointers.
4878static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4879 ExprResult &LHS,
4880 ExprResult &RHS,
4881 SourceLocation Loc) {
4882 QualType LHSTy = LHS.get()->getType();
4883 QualType RHSTy = RHS.get()->getType();
4884
4885 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4886 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4887 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4888 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4889 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4890 return destType;
4891 }
4892 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4893 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4894 << RHS.get()->getSourceRange();
4895 return QualType();
4896 }
4897
4898 // We have 2 block pointer types.
4899 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4900}
4901
4902/// \brief Return the resulting type when the operands are both pointers.
4903static QualType
4904checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4905 ExprResult &RHS,
4906 SourceLocation Loc) {
4907 // get the pointer types
4908 QualType LHSTy = LHS.get()->getType();
4909 QualType RHSTy = RHS.get()->getType();
4910
4911 // get the "pointed to" types
4912 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4913 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4914
4915 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4916 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4917 // Figure out necessary qualifiers (C99 6.5.15p6)
4918 QualType destPointee
4919 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4920 QualType destType = S.Context.getPointerType(destPointee);
4921 // Add qualifiers if necessary.
4922 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4923 // Promote to void*.
4924 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4925 return destType;
4926 }
4927 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4928 QualType destPointee
4929 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4930 QualType destType = S.Context.getPointerType(destPointee);
4931 // Add qualifiers if necessary.
4932 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4933 // Promote to void*.
4934 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4935 return destType;
4936 }
4937
4938 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4939}
4940
4941/// \brief Return false if the first expression is not an integer and the second
4942/// expression is not a pointer, true otherwise.
4943static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4944 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004945 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004946 if (!PointerExpr->getType()->isPointerType() ||
4947 !Int.get()->getType()->isIntegerType())
4948 return false;
4949
Richard Trieuccd891a2011-09-09 01:45:06 +00004950 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4951 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004952
4953 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4954 << Expr1->getType() << Expr2->getType()
4955 << Expr1->getSourceRange() << Expr2->getSourceRange();
4956 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4957 CK_IntegralToPointer);
4958 return true;
4959}
4960
Richard Trieu33fc7572011-09-06 20:06:39 +00004961/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4962/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004963/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004964QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4965 ExprResult &RHS, ExprValueKind &VK,
4966 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004967 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004968
Richard Trieu33fc7572011-09-06 20:06:39 +00004969 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4970 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004971 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004972
Richard Trieu33fc7572011-09-06 20:06:39 +00004973 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4974 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004975 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004976
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004977 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004978 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004979 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004980
4981 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004982 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004983
John Wiegley429bb272011-04-08 18:41:53 +00004984 Cond = UsualUnaryConversions(Cond.take());
4985 if (Cond.isInvalid())
4986 return QualType();
4987 LHS = UsualUnaryConversions(LHS.take());
4988 if (LHS.isInvalid())
4989 return QualType();
4990 RHS = UsualUnaryConversions(RHS.take());
4991 if (RHS.isInvalid())
4992 return QualType();
4993
4994 QualType CondTy = Cond.get()->getType();
4995 QualType LHSTy = LHS.get()->getType();
4996 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004997
Reid Spencer5f016e22007-07-11 17:01:13 +00004998 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004999 if (checkCondition(*this, Cond.get()))
5000 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005001
Chris Lattner70d67a92008-01-06 22:42:25 +00005002 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005003 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005004 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00005005
Nate Begeman6155d732010-09-20 22:41:17 +00005006 // OpenCL: If the condition is a vector, and both operands are scalar,
5007 // attempt to implicity convert them to the vector type to act like the
5008 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00005009 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00005010 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00005011 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00005012
Chris Lattner70d67a92008-01-06 22:42:25 +00005013 // If both operands have arithmetic type, do the usual arithmetic conversions
5014 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005015 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5016 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005017 if (LHS.isInvalid() || RHS.isInvalid())
5018 return QualType();
5019 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005020 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005021
Chris Lattner70d67a92008-01-06 22:42:25 +00005022 // If both operands are the same structure or union type, the result is that
5023 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005024 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5025 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005026 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005027 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005028 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005029 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005030 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005031 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005032
Chris Lattner70d67a92008-01-06 22:42:25 +00005033 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005034 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005035 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005036 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005037 }
Richard Trieu26f96072011-09-02 01:51:02 +00005038
Steve Naroffb6d54e52008-01-08 01:11:38 +00005039 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5040 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005041 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5042 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005043
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005044 // All objective-c pointer type analysis is done here.
5045 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5046 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005047 if (LHS.isInvalid() || RHS.isInvalid())
5048 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005049 if (!compositeType.isNull())
5050 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005051
5052
Steve Naroff7154a772009-07-01 14:36:47 +00005053 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005054 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5055 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5056 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005057
Steve Naroff7154a772009-07-01 14:36:47 +00005058 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005059 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5060 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5061 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005062
John McCall404cd162010-11-13 01:35:44 +00005063 // GCC compatibility: soften pointer/integer mismatch. Note that
5064 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005065 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5066 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005067 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005068 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5069 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005070 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005071
Chandler Carruth82214a82011-02-18 23:54:50 +00005072 // Emit a better diagnostic if one of the expressions is a null pointer
5073 // constant and the other is not a pointer type. In this case, the user most
5074 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005075 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005076 return QualType();
5077
Chris Lattner70d67a92008-01-06 22:42:25 +00005078 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005079 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005080 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5081 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005082 return QualType();
5083}
5084
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005085/// FindCompositeObjCPointerType - Helper method to find composite type of
5086/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005087QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005088 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005089 QualType LHSTy = LHS.get()->getType();
5090 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005091
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005092 // Handle things like Class and struct objc_class*. Here we case the result
5093 // to the pseudo-builtin, because that will be implicitly cast back to the
5094 // redefinition type if an attempt is made to access its fields.
5095 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005096 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005097 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005098 return LHSTy;
5099 }
5100 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005101 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005102 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005103 return RHSTy;
5104 }
5105 // And the same for struct objc_object* / id
5106 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005107 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005108 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005109 return LHSTy;
5110 }
5111 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005112 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005113 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005114 return RHSTy;
5115 }
5116 // And the same for struct objc_selector* / SEL
5117 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005118 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005119 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005120 return LHSTy;
5121 }
5122 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005123 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005124 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005125 return RHSTy;
5126 }
5127 // Check constraints for Objective-C object pointers types.
5128 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005129
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005130 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5131 // Two identical object pointer types are always compatible.
5132 return LHSTy;
5133 }
John McCall1d9b3b22011-09-09 05:25:32 +00005134 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5135 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005136 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005137
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005138 // If both operands are interfaces and either operand can be
5139 // assigned to the other, use that type as the composite
5140 // type. This allows
5141 // xxx ? (A*) a : (B*) b
5142 // where B is a subclass of A.
5143 //
5144 // Additionally, as for assignment, if either type is 'id'
5145 // allow silent coercion. Finally, if the types are
5146 // incompatible then make sure to use 'id' as the composite
5147 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005148
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005149 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5150 // It could return the composite type.
5151 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5152 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5153 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5154 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5155 } else if ((LHSTy->isObjCQualifiedIdType() ||
5156 RHSTy->isObjCQualifiedIdType()) &&
5157 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5158 // Need to handle "id<xx>" explicitly.
5159 // GCC allows qualified id and any Objective-C type to devolve to
5160 // id. Currently localizing to here until clear this should be
5161 // part of ObjCQualifiedIdTypesAreCompatible.
5162 compositeType = Context.getObjCIdType();
5163 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5164 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005165 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005166 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5167 ;
5168 else {
5169 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5170 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005172 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005173 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5174 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005175 return incompatTy;
5176 }
5177 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005178 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5179 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005180 return compositeType;
5181 }
5182 // Check Objective-C object pointer types and 'void *'
5183 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005184 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005185 // ARC forbids the implicit conversion of object pointers to 'void *',
5186 // so these types are not compatible.
5187 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5188 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5189 LHS = RHS = true;
5190 return QualType();
5191 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005192 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5193 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5194 QualType destPointee
5195 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5196 QualType destType = Context.getPointerType(destPointee);
5197 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005198 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005199 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005200 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005201 return destType;
5202 }
5203 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005204 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005205 // ARC forbids the implicit conversion of object pointers to 'void *',
5206 // so these types are not compatible.
5207 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5208 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5209 LHS = RHS = true;
5210 return QualType();
5211 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005212 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5213 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5214 QualType destPointee
5215 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5216 QualType destType = Context.getPointerType(destPointee);
5217 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005218 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005219 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005220 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005221 return destType;
5222 }
5223 return QualType();
5224}
5225
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005226/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005227/// ParenRange in parentheses.
5228static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005229 const PartialDiagnostic &Note,
5230 SourceRange ParenRange) {
5231 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5232 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5233 EndLoc.isValid()) {
5234 Self.Diag(Loc, Note)
5235 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5236 << FixItHint::CreateInsertion(EndLoc, ")");
5237 } else {
5238 // We can't display the parentheses, so just show the bare note.
5239 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005240 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005241}
5242
5243static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5244 return Opc >= BO_Mul && Opc <= BO_Shr;
5245}
5246
Hans Wennborg2f072b42011-06-09 17:06:51 +00005247/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5248/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005249/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5250/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005251static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005252 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005253 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5254 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005255 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005256 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005257
5258 // Built-in binary operator.
5259 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5260 if (IsArithmeticOp(OP->getOpcode())) {
5261 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005262 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005263 return true;
5264 }
5265 }
5266
5267 // Overloaded operator.
5268 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5269 if (Call->getNumArgs() != 2)
5270 return false;
5271
5272 // Make sure this is really a binary operator that is safe to pass into
5273 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5274 OverloadedOperatorKind OO = Call->getOperator();
5275 if (OO < OO_Plus || OO > OO_Arrow)
5276 return false;
5277
5278 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5279 if (IsArithmeticOp(OpKind)) {
5280 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005281 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005282 return true;
5283 }
5284 }
5285
5286 return false;
5287}
5288
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005289static bool IsLogicOp(BinaryOperatorKind Opc) {
5290 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5291}
5292
Hans Wennborg2f072b42011-06-09 17:06:51 +00005293/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5294/// or is a logical expression such as (x==y) which has int type, but is
5295/// commonly interpreted as boolean.
5296static bool ExprLooksBoolean(Expr *E) {
5297 E = E->IgnoreParenImpCasts();
5298
5299 if (E->getType()->isBooleanType())
5300 return true;
5301 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5302 return IsLogicOp(OP->getOpcode());
5303 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5304 return OP->getOpcode() == UO_LNot;
5305
5306 return false;
5307}
5308
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005309/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5310/// and binary operator are mixed in a way that suggests the programmer assumed
5311/// the conditional operator has higher precedence, for example:
5312/// "int x = a + someBinaryCondition ? 1 : 2".
5313static void DiagnoseConditionalPrecedence(Sema &Self,
5314 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005315 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005316 Expr *LHSExpr,
5317 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005318 BinaryOperatorKind CondOpcode;
5319 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005320
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005321 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005322 return;
5323 if (!ExprLooksBoolean(CondRHS))
5324 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005325
Hans Wennborg2f072b42011-06-09 17:06:51 +00005326 // The condition is an arithmetic binary expression, with a right-
5327 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005328
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005329 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005330 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005331 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005332
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005333 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005334 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005335 << BinaryOperator::getOpcodeStr(CondOpcode),
5336 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005337
5338 SuggestParentheses(Self, OpLoc,
5339 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005340 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005341}
5342
Steve Narofff69936d2007-09-16 03:34:24 +00005343/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005344/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005345ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005346 SourceLocation ColonLoc,
5347 Expr *CondExpr, Expr *LHSExpr,
5348 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005349 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5350 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005351 OpaqueValueExpr *opaqueValue = 0;
5352 Expr *commonExpr = 0;
5353 if (LHSExpr == 0) {
5354 commonExpr = CondExpr;
5355
5356 // We usually want to apply unary conversions *before* saving, except
5357 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005358 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005359 && !commonExpr->isTypeDependent()
5360 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5361 && commonExpr->isGLValue()
5362 && commonExpr->isOrdinaryOrBitFieldObject()
5363 && RHSExpr->isOrdinaryOrBitFieldObject()
5364 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005365 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5366 if (commonRes.isInvalid())
5367 return ExprError();
5368 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005369 }
5370
5371 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5372 commonExpr->getType(),
5373 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005374 commonExpr->getObjectKind(),
5375 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005376 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005377 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005378
John McCallf89e55a2010-11-18 06:31:45 +00005379 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005380 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005381 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5382 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005383 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005384 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5385 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005386 return ExprError();
5387
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005388 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5389 RHS.get());
5390
John McCall56ca35d2011-02-17 10:25:35 +00005391 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005392 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5393 LHS.take(), ColonLoc,
5394 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005395
5396 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005397 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005398 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5399 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005400}
5401
John McCalle4be87e2011-01-31 23:13:11 +00005402// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005403// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005404// routine is it effectively iqnores the qualifiers on the top level pointee.
5405// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5406// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005407static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005408checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5409 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5410 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005411
Reid Spencer5f016e22007-07-11 17:01:13 +00005412 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005413 const Type *lhptee, *rhptee;
5414 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005415 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5416 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005417
John McCalle4be87e2011-01-31 23:13:11 +00005418 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005419
5420 // C99 6.5.16.1p1: This following citation is common to constraints
5421 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5422 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005423 Qualifiers lq;
5424
John McCallf85e1932011-06-15 23:02:42 +00005425 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5426 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5427 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5428 // Ignore lifetime for further calculation.
5429 lhq.removeObjCLifetime();
5430 rhq.removeObjCLifetime();
5431 }
5432
John McCall86c05f32011-02-01 00:10:29 +00005433 if (!lhq.compatiblyIncludes(rhq)) {
5434 // Treat address-space mismatches as fatal. TODO: address subspaces
5435 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5436 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5437
John McCallf85e1932011-06-15 23:02:42 +00005438 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005439 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005440 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005441 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005442 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005443 && (lhptee->isVoidType() || rhptee->isVoidType()))
5444 ; // keep old
5445
John McCallf85e1932011-06-15 23:02:42 +00005446 // Treat lifetime mismatches as fatal.
5447 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5448 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5449
John McCall86c05f32011-02-01 00:10:29 +00005450 // For GCC compatibility, other qualifier mismatches are treated
5451 // as still compatible in C.
5452 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5453 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005454
Mike Stumpeed9cac2009-02-19 03:04:26 +00005455 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5456 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005457 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005458 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005459 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005460 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005461
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005462 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005463 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005464 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005465 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005466
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005467 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005468 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005469 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005470
5471 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005472 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005473 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005474 }
John McCall86c05f32011-02-01 00:10:29 +00005475
Mike Stumpeed9cac2009-02-19 03:04:26 +00005476 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005477 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005478 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5479 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005480 // Check if the pointee types are compatible ignoring the sign.
5481 // We explicitly check for char so that we catch "char" vs
5482 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005483 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005484 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005485 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005486 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005487
Chris Lattner6a2b9262009-10-17 20:33:28 +00005488 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005489 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005490 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005491 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005492
John McCall86c05f32011-02-01 00:10:29 +00005493 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005494 // Types are compatible ignoring the sign. Qualifier incompatibility
5495 // takes priority over sign incompatibility because the sign
5496 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005497 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005498 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005499
John McCalle4be87e2011-01-31 23:13:11 +00005500 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005501 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005502
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005503 // If we are a multi-level pointer, it's possible that our issue is simply
5504 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5505 // the eventual target type is the same and the pointers have the same
5506 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005507 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005508 do {
John McCall86c05f32011-02-01 00:10:29 +00005509 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5510 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005511 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005512
John McCall86c05f32011-02-01 00:10:29 +00005513 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005514 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005515 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005516
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005517 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005518 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005519 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005520 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005521 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5522 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005523 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005524}
5525
John McCalle4be87e2011-01-31 23:13:11 +00005526/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005527/// block pointer types are compatible or whether a block and normal pointer
5528/// are compatible. It is more restrict than comparing two function pointer
5529// types.
John McCalle4be87e2011-01-31 23:13:11 +00005530static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005531checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5532 QualType RHSType) {
5533 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5534 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005535
Steve Naroff1c7d0672008-09-04 15:10:53 +00005536 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005537
Steve Naroff1c7d0672008-09-04 15:10:53 +00005538 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005539 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5540 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005541
John McCalle4be87e2011-01-31 23:13:11 +00005542 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005543 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005544 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005545
John McCalle4be87e2011-01-31 23:13:11 +00005546 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005547
Steve Naroff1c7d0672008-09-04 15:10:53 +00005548 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005549 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5550 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005551
Richard Trieu1da27a12011-09-06 20:21:22 +00005552 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005553 return Sema::IncompatibleBlockPointer;
5554
Steve Naroff1c7d0672008-09-04 15:10:53 +00005555 return ConvTy;
5556}
5557
John McCalle4be87e2011-01-31 23:13:11 +00005558/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005559/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005560static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005561checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5562 QualType RHSType) {
5563 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5564 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005565
Richard Trieu1da27a12011-09-06 20:21:22 +00005566 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005567 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005568 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5569 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005570 return Sema::IncompatiblePointer;
5571 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005572 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005573 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005574 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5575 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005576 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005577 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005578 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005579 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5580 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005581
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005582 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5583 // make an exception for id<P>
5584 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005585 return Sema::CompatiblePointerDiscardsQualifiers;
5586
Richard Trieu1da27a12011-09-06 20:21:22 +00005587 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005588 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005589 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005590 return Sema::IncompatibleObjCQualifiedId;
5591 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005592}
5593
John McCall1c23e912010-11-16 02:32:08 +00005594Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005595Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005596 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005597 // Fake up an opaque expression. We don't actually care about what
5598 // cast operations are required, so if CheckAssignmentConstraints
5599 // adds casts to this they'll be wasted, but fortunately that doesn't
5600 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005601 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5602 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005603 CastKind K = CK_Invalid;
5604
Richard Trieu1da27a12011-09-06 20:21:22 +00005605 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005606}
5607
Mike Stumpeed9cac2009-02-19 03:04:26 +00005608/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5609/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005610/// pointers. Here are some objectionable examples that GCC considers warnings:
5611///
5612/// int a, *pint;
5613/// short *pshort;
5614/// struct foo *pfoo;
5615///
5616/// pint = pshort; // warning: assignment from incompatible pointer type
5617/// a = pint; // warning: assignment makes integer from pointer without a cast
5618/// pint = a; // warning: assignment makes pointer from integer without a cast
5619/// pint = pfoo; // warning: assignment from incompatible pointer type
5620///
5621/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005622/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005623///
John McCalldaa8e4e2010-11-15 09:13:47 +00005624/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005625Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005626Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005627 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005628 QualType RHSType = RHS.get()->getType();
5629 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005630
Chris Lattnerfc144e22008-01-04 23:18:45 +00005631 // Get canonical types. We're not formatting these types, just comparing
5632 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005633 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5634 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005635
Eli Friedmanb001de72011-10-06 23:00:33 +00005636
John McCallb6cfa242011-01-31 22:28:28 +00005637 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005638 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005639 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005640 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005641 }
5642
Eli Friedman860a3192012-06-16 02:19:17 +00005643 // If we have an atomic type, try a non-atomic assignment, then just add an
5644 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005645 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005646 Sema::AssignConvertType result =
5647 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5648 if (result != Compatible)
5649 return result;
5650 if (Kind != CK_NoOp)
5651 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5652 Kind = CK_NonAtomicToAtomic;
5653 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005654 }
5655
Douglas Gregor9d293df2008-10-28 00:22:11 +00005656 // If the left-hand side is a reference type, then we are in a
5657 // (rare!) case where we've allowed the use of references in C,
5658 // e.g., as a parameter type in a built-in function. In this case,
5659 // just make sure that the type referenced is compatible with the
5660 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005661 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005662 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005663 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5664 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005665 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005666 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005667 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005668 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005669 }
John McCallb6cfa242011-01-31 22:28:28 +00005670
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005671 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5672 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005673 if (LHSType->isExtVectorType()) {
5674 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005675 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005676 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005677 // CK_VectorSplat does T -> vector T, so first cast to the
5678 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005679 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5680 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005681 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005682 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005683 }
5684 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005685 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005686 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005687 }
Mike Stump1eb44332009-09-09 15:08:12 +00005688
John McCallb6cfa242011-01-31 22:28:28 +00005689 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005690 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5691 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005692 // Allow assignments of an AltiVec vector type to an equivalent GCC
5693 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005694 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005695 Kind = CK_BitCast;
5696 return Compatible;
5697 }
5698
Douglas Gregor255210e2010-08-06 10:14:59 +00005699 // If we are allowing lax vector conversions, and LHS and RHS are both
5700 // vectors, the total size only needs to be the same. This is a bitcast;
5701 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005702 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005703 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005704 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005705 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005706 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005707 }
5708 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005709 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005710
John McCallb6cfa242011-01-31 22:28:28 +00005711 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005712 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005713 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005714 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005715 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005716 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005717
John McCallb6cfa242011-01-31 22:28:28 +00005718 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005719 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005720 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005721 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005722 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005723 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005724 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005725
John McCallb6cfa242011-01-31 22:28:28 +00005726 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005727 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005728 Kind = CK_IntegralToPointer; // FIXME: null?
5729 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005730 }
John McCallb6cfa242011-01-31 22:28:28 +00005731
5732 // C pointers are not compatible with ObjC object pointers,
5733 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005734 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005735 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005736 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005737 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005738 return Compatible;
5739 }
5740
5741 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 if (RHSType->isObjCClassType() &&
5743 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005744 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005745 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005746 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005747 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005748
John McCallb6cfa242011-01-31 22:28:28 +00005749 Kind = CK_BitCast;
5750 return IncompatiblePointer;
5751 }
5752
5753 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005754 if (RHSType->getAs<BlockPointerType>()) {
5755 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005756 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005757 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005758 }
Steve Naroffb4406862008-09-29 18:10:17 +00005759 }
John McCallb6cfa242011-01-31 22:28:28 +00005760
Steve Naroff1c7d0672008-09-04 15:10:53 +00005761 return Incompatible;
5762 }
5763
John McCallb6cfa242011-01-31 22:28:28 +00005764 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005765 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005766 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005767 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005768 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005769 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005770 }
5771
5772 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005773 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005774 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005775 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005776 }
5777
John McCallb6cfa242011-01-31 22:28:28 +00005778 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005779 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005780 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005781 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005782 }
Steve Naroffb4406862008-09-29 18:10:17 +00005783
John McCallb6cfa242011-01-31 22:28:28 +00005784 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005785 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005786 if (RHSPT->getPointeeType()->isVoidType()) {
5787 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005788 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005789 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005790
Chris Lattnerfc144e22008-01-04 23:18:45 +00005791 return Incompatible;
5792 }
5793
John McCallb6cfa242011-01-31 22:28:28 +00005794 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005795 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005796 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005797 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005798 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005799 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005800 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005801 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005802 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005803 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005804 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005805 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005806 }
5807
5808 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005809 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005810 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005811 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005812 }
5813
John McCallb6cfa242011-01-31 22:28:28 +00005814 // In general, C pointers are not compatible with ObjC object pointers,
5815 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005816 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005817 Kind = CK_CPointerToObjCPointerCast;
5818
John McCallb6cfa242011-01-31 22:28:28 +00005819 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005820 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005821 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005822 }
5823
5824 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005825 if (LHSType->isObjCClassType() &&
5826 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005827 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005828 return Compatible;
5829 }
5830
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005831 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005832 }
John McCallb6cfa242011-01-31 22:28:28 +00005833
5834 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005835 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005836 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005837 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005838 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005839 }
5840
Steve Naroff14108da2009-07-10 23:34:53 +00005841 return Incompatible;
5842 }
John McCallb6cfa242011-01-31 22:28:28 +00005843
5844 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005845 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005846 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005847 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005848 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005849 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005850 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005851
John McCallb6cfa242011-01-31 22:28:28 +00005852 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005853 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005854 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005855 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005857
Chris Lattnerfc144e22008-01-04 23:18:45 +00005858 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005859 }
John McCallb6cfa242011-01-31 22:28:28 +00005860
5861 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005862 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005863 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005864 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005865 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005866 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005867 }
Steve Naroff14108da2009-07-10 23:34:53 +00005868
John McCallb6cfa242011-01-31 22:28:28 +00005869 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005870 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005871 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005872 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005873 }
5874
Steve Naroff14108da2009-07-10 23:34:53 +00005875 return Incompatible;
5876 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005877
John McCallb6cfa242011-01-31 22:28:28 +00005878 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005879 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5880 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005881 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005882 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005883 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005884 }
John McCallb6cfa242011-01-31 22:28:28 +00005885
Reid Spencer5f016e22007-07-11 17:01:13 +00005886 return Incompatible;
5887}
5888
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005889/// \brief Constructs a transparent union from an expression that is
5890/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005891static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5892 ExprResult &EResult, QualType UnionType,
5893 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005894 // Build an initializer list that designates the appropriate member
5895 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005896 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005897 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005898 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005899 Initializer->setType(UnionType);
5900 Initializer->setInitializedFieldInUnion(Field);
5901
5902 // Build a compound literal constructing a value of the transparent
5903 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005904 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005905 EResult = S.Owned(
5906 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5907 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005908}
5909
5910Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005911Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005912 ExprResult &RHS) {
5913 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005914
Mike Stump1eb44332009-09-09 15:08:12 +00005915 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005916 // transparent_union GCC extension.
5917 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005918 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005919 return Incompatible;
5920
5921 // The field to initialize within the transparent union.
5922 RecordDecl *UD = UT->getDecl();
5923 FieldDecl *InitField = 0;
5924 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005925 for (RecordDecl::field_iterator it = UD->field_begin(),
5926 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005927 it != itend; ++it) {
5928 if (it->getType()->isPointerType()) {
5929 // If the transparent union contains a pointer type, we allow:
5930 // 1) void pointer
5931 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005932 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005933 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005934 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005935 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005936 break;
5937 }
Mike Stump1eb44332009-09-09 15:08:12 +00005938
Richard Trieuf7720da2011-09-06 20:40:12 +00005939 if (RHS.get()->isNullPointerConstant(Context,
5940 Expr::NPC_ValueDependentIsNull)) {
5941 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5942 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005943 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005944 break;
5945 }
5946 }
5947
John McCalldaa8e4e2010-11-15 09:13:47 +00005948 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005949 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005950 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005951 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005952 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005953 break;
5954 }
5955 }
5956
5957 if (!InitField)
5958 return Incompatible;
5959
Richard Trieuf7720da2011-09-06 20:40:12 +00005960 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005961 return Compatible;
5962}
5963
Chris Lattner5cf216b2008-01-04 18:04:52 +00005964Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005965Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5966 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005967 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005968 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005969 // C++ 5.17p3: If the left operand is not of class type, the
5970 // expression is implicitly converted (C++ 4) to the
5971 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005972 ExprResult Res;
5973 if (Diagnose) {
5974 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5975 AA_Assigning);
5976 } else {
5977 ImplicitConversionSequence ICS =
5978 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5979 /*SuppressUserConversions=*/false,
5980 /*AllowExplicit=*/false,
5981 /*InOverloadResolution=*/false,
5982 /*CStyle=*/false,
5983 /*AllowObjCWritebackConversion=*/false);
5984 if (ICS.isFailure())
5985 return Incompatible;
5986 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5987 ICS, AA_Assigning);
5988 }
John Wiegley429bb272011-04-08 18:41:53 +00005989 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005990 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005991 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005992 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005993 !CheckObjCARCUnavailableWeakConversion(LHSType,
5994 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005995 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005996 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005997 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005998 }
5999
6000 // FIXME: Currently, we fall through and treat C++ classes like C
6001 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00006002 // FIXME: We also fall through for atomics; not sure what should
6003 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00006004 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006005
Steve Naroff529a4ad2007-11-27 17:58:44 +00006006 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6007 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00006008 if ((LHSType->isPointerType() ||
6009 LHSType->isObjCObjectPointerType() ||
6010 LHSType->isBlockPointerType())
6011 && RHS.get()->isNullPointerConstant(Context,
6012 Expr::NPC_ValueDependentIsNull)) {
6013 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006014 return Compatible;
6015 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006016
Chris Lattner943140e2007-10-16 02:55:40 +00006017 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006018 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006019 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006020 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006021 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006022 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006023 if (!LHSType->isReferenceType()) {
6024 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6025 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006026 return Incompatible;
6027 }
Steve Narofff1120de2007-08-24 22:33:52 +00006028
John McCalldaa8e4e2010-11-15 09:13:47 +00006029 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006030 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006031 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006032
Steve Narofff1120de2007-08-24 22:33:52 +00006033 // C99 6.5.16.1p2: The value of the right operand is converted to the
6034 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006035 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6036 // so that we can use references in built-in functions even in C.
6037 // The getNonReferenceType() call makes sure that the resulting expression
6038 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006039 if (result != Incompatible && RHS.get()->getType() != LHSType)
6040 RHS = ImpCastExprToType(RHS.take(),
6041 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006042 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006043}
6044
Richard Trieuf7720da2011-09-06 20:40:12 +00006045QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6046 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006047 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006048 << LHS.get()->getType() << RHS.get()->getType()
6049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006050 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006051}
6052
Richard Trieu08062aa2011-09-06 21:01:04 +00006053QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006054 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006055 if (!IsCompAssign) {
6056 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6057 if (LHS.isInvalid())
6058 return QualType();
6059 }
6060 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6061 if (RHS.isInvalid())
6062 return QualType();
6063
Mike Stumpeed9cac2009-02-19 03:04:26 +00006064 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006065 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006066 QualType LHSType =
6067 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6068 QualType RHSType =
6069 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006070
Nate Begemanbe2341d2008-07-14 18:02:46 +00006071 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006072 if (LHSType == RHSType)
6073 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006074
Douglas Gregor255210e2010-08-06 10:14:59 +00006075 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006076 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6077 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6078 if (LHSType->isExtVectorType()) {
6079 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6080 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006081 }
6082
Richard Trieuccd891a2011-09-09 01:45:06 +00006083 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006084 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6085 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006086 }
6087
David Blaikie4e4d0842012-03-11 07:00:24 +00006088 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006089 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006090 // If we are allowing lax vector conversions, and LHS and RHS are both
6091 // vectors, the total size only needs to be the same. This is a
6092 // bitcast; no bits are changed but the result type is different.
6093 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006094 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6095 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006096 }
6097
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006098 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6099 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6100 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006101 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006102 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006103 std::swap(RHS, LHS);
6104 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006105 }
Mike Stump1eb44332009-09-09 15:08:12 +00006106
Nate Begemandde25982009-06-28 19:12:57 +00006107 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006108 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006109 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006110 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6111 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006112 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006113 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006114 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006115 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6116 if (swapped) std::swap(RHS, LHS);
6117 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006118 }
6119 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006120 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6121 RHSType->isRealFloatingType()) {
6122 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006123 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006124 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006125 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006126 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6127 if (swapped) std::swap(RHS, LHS);
6128 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006129 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006130 }
6131 }
Mike Stump1eb44332009-09-09 15:08:12 +00006132
Nate Begemandde25982009-06-28 19:12:57 +00006133 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006134 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006135 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006136 << LHS.get()->getType() << RHS.get()->getType()
6137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006138 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006139}
6140
Richard Trieu481037f2011-09-16 00:53:10 +00006141// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6142// expression. These are mainly cases where the null pointer is used as an
6143// integer instead of a pointer.
6144static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6145 SourceLocation Loc, bool IsCompare) {
6146 // The canonical way to check for a GNU null is with isNullPointerConstant,
6147 // but we use a bit of a hack here for speed; this is a relatively
6148 // hot path, and isNullPointerConstant is slow.
6149 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6150 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6151
6152 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6153
6154 // Avoid analyzing cases where the result will either be invalid (and
6155 // diagnosed as such) or entirely valid and not something to warn about.
6156 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6157 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6158 return;
6159
6160 // Comparison operations would not make sense with a null pointer no matter
6161 // what the other expression is.
6162 if (!IsCompare) {
6163 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6164 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6165 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6166 return;
6167 }
6168
6169 // The rest of the operations only make sense with a null pointer
6170 // if the other expression is a pointer.
6171 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6172 NonNullType->canDecayToPointerType())
6173 return;
6174
6175 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6176 << LHSNull /* LHS is NULL */ << NonNullType
6177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6178}
6179
Richard Trieu08062aa2011-09-06 21:01:04 +00006180QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006181 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006182 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006183 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6184
Richard Trieu08062aa2011-09-06 21:01:04 +00006185 if (LHS.get()->getType()->isVectorType() ||
6186 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006187 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006188
Richard Trieuccd891a2011-09-09 01:45:06 +00006189 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006190 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006191 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006192
David Chisnall7a7ee302012-01-16 17:27:18 +00006193
Eli Friedman860a3192012-06-16 02:19:17 +00006194 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006195 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006196
Chris Lattner7ef655a2010-01-12 21:23:57 +00006197 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006198 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006199 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006200 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006201 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6202 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006203
Chris Lattner7ef655a2010-01-12 21:23:57 +00006204 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006205}
6206
Chris Lattner7ef655a2010-01-12 21:23:57 +00006207QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006208 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006209 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6210
Richard Trieu08062aa2011-09-06 21:01:04 +00006211 if (LHS.get()->getType()->isVectorType() ||
6212 RHS.get()->getType()->isVectorType()) {
6213 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6214 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006215 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006216 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006217 }
Steve Naroff90045e82007-07-13 23:32:42 +00006218
Richard Trieuccd891a2011-09-09 01:45:06 +00006219 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006220 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006221 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006222
Eli Friedman860a3192012-06-16 02:19:17 +00006223 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006224 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006225
Chris Lattner7ef655a2010-01-12 21:23:57 +00006226 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006227 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006228 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006229 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6230 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006231
Chris Lattner7ef655a2010-01-12 21:23:57 +00006232 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006233}
6234
Chandler Carruth13b21be2011-06-27 08:02:19 +00006235/// \brief Diagnose invalid arithmetic on two void pointers.
6236static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006237 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006238 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006239 ? diag::err_typecheck_pointer_arith_void_type
6240 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006241 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6242 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006243}
6244
6245/// \brief Diagnose invalid arithmetic on a void pointer.
6246static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6247 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006248 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006249 ? diag::err_typecheck_pointer_arith_void_type
6250 : diag::ext_gnu_void_ptr)
6251 << 0 /* one pointer */ << Pointer->getSourceRange();
6252}
6253
6254/// \brief Diagnose invalid arithmetic on two function pointers.
6255static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6256 Expr *LHS, Expr *RHS) {
6257 assert(LHS->getType()->isAnyPointerType());
6258 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006259 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006260 ? diag::err_typecheck_pointer_arith_function_type
6261 : diag::ext_gnu_ptr_func_arith)
6262 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6263 // We only show the second type if it differs from the first.
6264 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6265 RHS->getType())
6266 << RHS->getType()->getPointeeType()
6267 << LHS->getSourceRange() << RHS->getSourceRange();
6268}
6269
6270/// \brief Diagnose invalid arithmetic on a function pointer.
6271static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6272 Expr *Pointer) {
6273 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006274 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006275 ? diag::err_typecheck_pointer_arith_function_type
6276 : diag::ext_gnu_ptr_func_arith)
6277 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6278 << 0 /* one pointer, so only one type */
6279 << Pointer->getSourceRange();
6280}
6281
Richard Trieud9f19342011-09-12 18:08:02 +00006282/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006283///
6284/// \returns True if pointer has incomplete type
6285static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6286 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006287 assert(Operand->getType()->isAnyPointerType() &&
6288 !Operand->getType()->isDependentType());
6289 QualType PointeeTy = Operand->getType()->getPointeeType();
6290 return S.RequireCompleteType(Loc, PointeeTy,
6291 diag::err_typecheck_arithmetic_incomplete_type,
6292 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006293}
6294
Chandler Carruth13b21be2011-06-27 08:02:19 +00006295/// \brief Check the validity of an arithmetic pointer operand.
6296///
6297/// If the operand has pointer type, this code will check for pointer types
6298/// which are invalid in arithmetic operations. These will be diagnosed
6299/// appropriately, including whether or not the use is supported as an
6300/// extension.
6301///
6302/// \returns True when the operand is valid to use (even if as an extension).
6303static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6304 Expr *Operand) {
6305 if (!Operand->getType()->isAnyPointerType()) return true;
6306
6307 QualType PointeeTy = Operand->getType()->getPointeeType();
6308 if (PointeeTy->isVoidType()) {
6309 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006310 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006311 }
6312 if (PointeeTy->isFunctionType()) {
6313 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006314 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006315 }
6316
Richard Trieu097ecd22011-09-02 02:15:37 +00006317 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006318
6319 return true;
6320}
6321
6322/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6323/// operands.
6324///
6325/// This routine will diagnose any invalid arithmetic on pointer operands much
6326/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6327/// for emitting a single diagnostic even for operations where both LHS and RHS
6328/// are (potentially problematic) pointers.
6329///
6330/// \returns True when the operand is valid to use (even if as an extension).
6331static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006332 Expr *LHSExpr, Expr *RHSExpr) {
6333 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6334 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006335 if (!isLHSPointer && !isRHSPointer) return true;
6336
6337 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006338 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6339 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006340
6341 // Check for arithmetic on pointers to incomplete types.
6342 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6343 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6344 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006345 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6346 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6347 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006348
David Blaikie4e4d0842012-03-11 07:00:24 +00006349 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006350 }
6351
6352 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6353 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6354 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006355 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6356 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6357 RHSExpr);
6358 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006359
David Blaikie4e4d0842012-03-11 07:00:24 +00006360 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006361 }
6362
John McCall1503f0d2012-07-31 05:14:30 +00006363 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6364 return false;
6365 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6366 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006367
Chandler Carruth13b21be2011-06-27 08:02:19 +00006368 return true;
6369}
6370
Nico Weber1cb2d742012-03-02 22:01:22 +00006371/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6372/// literal.
6373static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6374 Expr *LHSExpr, Expr *RHSExpr) {
6375 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6376 Expr* IndexExpr = RHSExpr;
6377 if (!StrExpr) {
6378 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6379 IndexExpr = LHSExpr;
6380 }
6381
6382 bool IsStringPlusInt = StrExpr &&
6383 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6384 if (!IsStringPlusInt)
6385 return;
6386
6387 llvm::APSInt index;
6388 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6389 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6390 if (index.isNonNegative() &&
6391 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6392 index.isUnsigned()))
6393 return;
6394 }
6395
6396 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6397 Self.Diag(OpLoc, diag::warn_string_plus_int)
6398 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6399
6400 // Only print a fixit for "str" + int, not for int + "str".
6401 if (IndexExpr == RHSExpr) {
6402 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6403 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6404 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6405 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6406 << FixItHint::CreateInsertion(EndLoc, "]");
6407 } else
6408 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6409}
6410
Richard Trieud9f19342011-09-12 18:08:02 +00006411/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006412static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006413 Expr *LHSExpr, Expr *RHSExpr) {
6414 assert(LHSExpr->getType()->isAnyPointerType());
6415 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006416 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006417 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6418 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006419}
6420
Chris Lattner7ef655a2010-01-12 21:23:57 +00006421QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006422 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6423 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006424 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6425
Richard Trieudef75842011-09-06 21:13:51 +00006426 if (LHS.get()->getType()->isVectorType() ||
6427 RHS.get()->getType()->isVectorType()) {
6428 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006429 if (CompLHSTy) *CompLHSTy = compType;
6430 return compType;
6431 }
Steve Naroff49b45262007-07-13 16:58:59 +00006432
Richard Trieudef75842011-09-06 21:13:51 +00006433 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6434 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006435 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006436
Nico Weber1cb2d742012-03-02 22:01:22 +00006437 // Diagnose "string literal" '+' int.
6438 if (Opc == BO_Add)
6439 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6440
Reid Spencer5f016e22007-07-11 17:01:13 +00006441 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006442 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006443 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006444 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006446
John McCall1503f0d2012-07-31 05:14:30 +00006447 // Type-checking. Ultimately the pointer's going to be in PExp;
6448 // note that we bias towards the LHS being the pointer.
6449 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006450
John McCall1503f0d2012-07-31 05:14:30 +00006451 bool isObjCPointer;
6452 if (PExp->getType()->isPointerType()) {
6453 isObjCPointer = false;
6454 } else if (PExp->getType()->isObjCObjectPointerType()) {
6455 isObjCPointer = true;
6456 } else {
6457 std::swap(PExp, IExp);
6458 if (PExp->getType()->isPointerType()) {
6459 isObjCPointer = false;
6460 } else if (PExp->getType()->isObjCObjectPointerType()) {
6461 isObjCPointer = true;
6462 } else {
6463 return InvalidOperands(Loc, LHS, RHS);
6464 }
6465 }
6466 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006467
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006468 if (!IExp->getType()->isIntegerType())
6469 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006470
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006471 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6472 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006473
John McCall1503f0d2012-07-31 05:14:30 +00006474 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006475 return QualType();
6476
6477 // Check array bounds for pointer arithemtic
6478 CheckArrayAccess(PExp, IExp);
6479
6480 if (CompLHSTy) {
6481 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6482 if (LHSTy.isNull()) {
6483 LHSTy = LHS.get()->getType();
6484 if (LHSTy->isPromotableIntegerType())
6485 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006486 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006487 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006488 }
6489
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006490 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006491}
6492
Chris Lattnereca7be62008-04-07 05:30:13 +00006493// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006494QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006495 SourceLocation Loc,
6496 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006497 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6498
Richard Trieudef75842011-09-06 21:13:51 +00006499 if (LHS.get()->getType()->isVectorType() ||
6500 RHS.get()->getType()->isVectorType()) {
6501 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006502 if (CompLHSTy) *CompLHSTy = compType;
6503 return compType;
6504 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006505
Richard Trieudef75842011-09-06 21:13:51 +00006506 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6507 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006508 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Chris Lattner6e4ab612007-12-09 21:53:25 +00006510 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006511
Chris Lattner6e4ab612007-12-09 21:53:25 +00006512 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006513 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006514 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006515 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006516 }
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Chris Lattner6e4ab612007-12-09 21:53:25 +00006518 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006519 if (LHS.get()->getType()->isAnyPointerType()) {
6520 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006521
Chris Lattnerb5f15622009-04-24 23:50:08 +00006522 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006523 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6524 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006525 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006526
Chris Lattner6e4ab612007-12-09 21:53:25 +00006527 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006528 if (RHS.get()->getType()->isIntegerType()) {
6529 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006530 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006531
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006532 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006533 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6534 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006535
Richard Trieudef75842011-09-06 21:13:51 +00006536 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6537 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006538 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006539
Chris Lattner6e4ab612007-12-09 21:53:25 +00006540 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006541 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006542 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006543 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006544
David Blaikie4e4d0842012-03-11 07:00:24 +00006545 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006546 // Pointee types must be the same: C++ [expr.add]
6547 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006548 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006549 }
6550 } else {
6551 // Pointee types must be compatible C99 6.5.6p3
6552 if (!Context.typesAreCompatible(
6553 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6554 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006555 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006556 return QualType();
6557 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006558 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006559
Chandler Carruth13b21be2011-06-27 08:02:19 +00006560 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006561 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006562 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006563
Richard Trieudef75842011-09-06 21:13:51 +00006564 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006565 return Context.getPointerDiffType();
6566 }
6567 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006568
Richard Trieudef75842011-09-06 21:13:51 +00006569 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006570}
6571
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006572static bool isScopedEnumerationType(QualType T) {
6573 if (const EnumType *ET = dyn_cast<EnumType>(T))
6574 return ET->getDecl()->isScoped();
6575 return false;
6576}
6577
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006578static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006579 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006580 QualType LHSType) {
David Tweed7a834212013-01-07 16:43:27 +00006581 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6582 // so skip remaining warnings as we don't want to modify values within Sema.
6583 if (S.getLangOpts().OpenCL)
6584 return;
6585
Chandler Carruth21206d52011-02-23 23:34:11 +00006586 llvm::APSInt Right;
6587 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006588 if (RHS.get()->isValueDependent() ||
6589 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006590 return;
6591
6592 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006593 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006594 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006595 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006596 return;
6597 }
6598 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006599 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006600 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006601 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006602 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006603 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006604 return;
6605 }
6606 if (Opc != BO_Shl)
6607 return;
6608
6609 // When left shifting an ICE which is signed, we can check for overflow which
6610 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6611 // integers have defined behavior modulo one more than the maximum value
6612 // representable in the result type, so never warn for those.
6613 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006614 if (LHS.get()->isValueDependent() ||
6615 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6616 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006617 return;
6618 llvm::APInt ResultBits =
6619 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6620 if (LeftBits.uge(ResultBits))
6621 return;
6622 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6623 Result = Result.shl(Right);
6624
Ted Kremenekfa821382011-06-15 00:54:52 +00006625 // Print the bit representation of the signed integer as an unsigned
6626 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006627 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006628 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6629
Chandler Carruth21206d52011-02-23 23:34:11 +00006630 // If we are only missing a sign bit, this is less likely to result in actual
6631 // bugs -- if the result is cast back to an unsigned type, it will have the
6632 // expected value. Thus we place this behind a different warning that can be
6633 // turned off separately if needed.
6634 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006635 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006636 << HexResult.str() << LHSType
6637 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006638 return;
6639 }
6640
6641 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006642 << HexResult.str() << Result.getMinSignedBits() << LHSType
6643 << Left.getBitWidth() << LHS.get()->getSourceRange()
6644 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006645}
6646
Chris Lattnereca7be62008-04-07 05:30:13 +00006647// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006648QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006649 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006650 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006651 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6652
Chris Lattnerca5eede2007-12-12 05:47:28 +00006653 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006654 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6655 !RHS.get()->getType()->hasIntegerRepresentation())
6656 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006657
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006658 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6659 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006660 if (isScopedEnumerationType(LHS.get()->getType()) ||
6661 isScopedEnumerationType(RHS.get()->getType())) {
6662 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006663 }
6664
Nate Begeman2207d792009-10-25 02:26:48 +00006665 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006666 if (LHS.get()->getType()->isVectorType() ||
6667 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006668 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006669
Chris Lattnerca5eede2007-12-12 05:47:28 +00006670 // Shifts don't perform usual arithmetic conversions, they just do integer
6671 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006672
John McCall1bc80af2010-12-16 19:28:59 +00006673 // For the LHS, do usual unary conversions, but then reset them away
6674 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006675 ExprResult OldLHS = LHS;
6676 LHS = UsualUnaryConversions(LHS.take());
6677 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006678 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006679 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006680 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006681
6682 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006683 RHS = UsualUnaryConversions(RHS.take());
6684 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006685 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686
Ryan Flynnd0439682009-08-07 16:20:20 +00006687 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006688 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006689
Chris Lattnerca5eede2007-12-12 05:47:28 +00006690 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006691 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006692}
6693
Chandler Carruth99919472010-07-10 12:30:03 +00006694static bool IsWithinTemplateSpecialization(Decl *D) {
6695 if (DeclContext *DC = D->getDeclContext()) {
6696 if (isa<ClassTemplateSpecializationDecl>(DC))
6697 return true;
6698 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6699 return FD->isFunctionTemplateSpecialization();
6700 }
6701 return false;
6702}
6703
Richard Trieue648ac32011-09-02 03:48:46 +00006704/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006705static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6706 ExprResult &RHS) {
6707 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6708 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006709
6710 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6711 if (!LHSEnumType)
6712 return;
6713 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6714 if (!RHSEnumType)
6715 return;
6716
6717 // Ignore anonymous enums.
6718 if (!LHSEnumType->getDecl()->getIdentifier())
6719 return;
6720 if (!RHSEnumType->getDecl()->getIdentifier())
6721 return;
6722
6723 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6724 return;
6725
6726 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6727 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006729}
6730
Richard Trieu7be1be02011-09-02 02:55:45 +00006731/// \brief Diagnose bad pointer comparisons.
6732static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006733 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006734 bool IsError) {
6735 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006736 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006737 << LHS.get()->getType() << RHS.get()->getType()
6738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006739}
6740
6741/// \brief Returns false if the pointers are converted to a composite type,
6742/// true otherwise.
6743static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006744 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006745 // C++ [expr.rel]p2:
6746 // [...] Pointer conversions (4.10) and qualification
6747 // conversions (4.4) are performed on pointer operands (or on
6748 // a pointer operand and a null pointer constant) to bring
6749 // them to their composite pointer type. [...]
6750 //
6751 // C++ [expr.eq]p1 uses the same notion for (in)equality
6752 // comparisons of pointers.
6753
6754 // C++ [expr.eq]p2:
6755 // In addition, pointers to members can be compared, or a pointer to
6756 // member and a null pointer constant. Pointer to member conversions
6757 // (4.11) and qualification conversions (4.4) are performed to bring
6758 // them to a common type. If one operand is a null pointer constant,
6759 // the common type is the type of the other operand. Otherwise, the
6760 // common type is a pointer to member type similar (4.4) to the type
6761 // of one of the operands, with a cv-qualification signature (4.4)
6762 // that is the union of the cv-qualification signatures of the operand
6763 // types.
6764
Richard Trieuba261492011-09-06 21:27:33 +00006765 QualType LHSType = LHS.get()->getType();
6766 QualType RHSType = RHS.get()->getType();
6767 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6768 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006769
6770 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006771 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006772 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006773 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006774 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006775 return true;
6776 }
6777
6778 if (NonStandardCompositeType)
6779 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006780 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6781 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006782
Richard Trieuba261492011-09-06 21:27:33 +00006783 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6784 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006785 return false;
6786}
6787
6788static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006789 ExprResult &LHS,
6790 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006791 bool IsError) {
6792 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6793 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006794 << LHS.get()->getType() << RHS.get()->getType()
6795 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006796}
6797
Jordan Rose9f63a452012-06-08 21:14:25 +00006798static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rose87da0b72012-11-09 23:55:21 +00006799 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rose9f63a452012-06-08 21:14:25 +00006800 case Stmt::ObjCArrayLiteralClass:
6801 case Stmt::ObjCDictionaryLiteralClass:
6802 case Stmt::ObjCStringLiteralClass:
6803 case Stmt::ObjCBoxedExprClass:
6804 return true;
6805 default:
6806 // Note that ObjCBoolLiteral is NOT an object literal!
6807 return false;
6808 }
6809}
6810
Jordan Rose8d872ca2012-07-17 17:46:40 +00006811static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6812 // Get the LHS object's interface type.
6813 QualType Type = LHS->getType();
6814 QualType InterfaceType;
6815 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6816 InterfaceType = PTy->getPointeeType();
6817 if (const ObjCObjectType *iQFaceTy =
6818 InterfaceType->getAsObjCQualifiedInterfaceType())
6819 InterfaceType = iQFaceTy->getBaseType();
6820 } else {
6821 // If this is not actually an Objective-C object, bail out.
6822 return false;
6823 }
6824
6825 // If the RHS isn't an Objective-C object, bail out.
6826 if (!RHS->getType()->isObjCObjectPointerType())
6827 return false;
6828
6829 // Try to find the -isEqual: method.
6830 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6831 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6832 InterfaceType,
6833 /*instance=*/true);
6834 if (!Method) {
6835 if (Type->isObjCIdType()) {
6836 // For 'id', just check the global pool.
6837 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6838 /*receiverId=*/true,
6839 /*warn=*/false);
6840 } else {
6841 // Check protocols.
6842 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6843 cast<ObjCObjectPointerType>(Type),
6844 /*instance=*/true);
6845 }
6846 }
6847
6848 if (!Method)
6849 return false;
6850
6851 QualType T = Method->param_begin()[0]->getType();
6852 if (!T->isObjCObjectPointerType())
6853 return false;
6854
6855 QualType R = Method->getResultType();
6856 if (!R->isScalarType())
6857 return false;
6858
6859 return true;
6860}
6861
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006862Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
6863 FromE = FromE->IgnoreParenImpCasts();
6864 switch (FromE->getStmtClass()) {
6865 default:
6866 break;
6867 case Stmt::ObjCStringLiteralClass:
6868 // "string literal"
6869 return LK_String;
6870 case Stmt::ObjCArrayLiteralClass:
6871 // "array literal"
6872 return LK_Array;
6873 case Stmt::ObjCDictionaryLiteralClass:
6874 // "dictionary literal"
6875 return LK_Dictionary;
Ted Kremenekd3292c82012-12-21 22:46:35 +00006876 case Stmt::BlockExprClass:
6877 return LK_Block;
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006878 case Stmt::ObjCBoxedExprClass: {
Ted Kremenekf530ff72012-12-21 21:59:39 +00006879 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006880 switch (Inner->getStmtClass()) {
6881 case Stmt::IntegerLiteralClass:
6882 case Stmt::FloatingLiteralClass:
6883 case Stmt::CharacterLiteralClass:
6884 case Stmt::ObjCBoolLiteralExprClass:
6885 case Stmt::CXXBoolLiteralExprClass:
6886 // "numeric literal"
6887 return LK_Numeric;
6888 case Stmt::ImplicitCastExprClass: {
6889 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6890 // Boolean literals can be represented by implicit casts.
6891 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
6892 return LK_Numeric;
6893 break;
6894 }
6895 default:
6896 break;
6897 }
6898 return LK_Boxed;
6899 }
6900 }
6901 return LK_None;
6902}
6903
Jordan Rose8d872ca2012-07-17 17:46:40 +00006904static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6905 ExprResult &LHS, ExprResult &RHS,
6906 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006907 Expr *Literal;
6908 Expr *Other;
6909 if (isObjCObjectLiteral(LHS)) {
6910 Literal = LHS.get();
6911 Other = RHS.get();
6912 } else {
6913 Literal = RHS.get();
6914 Other = LHS.get();
6915 }
6916
6917 // Don't warn on comparisons against nil.
6918 Other = Other->IgnoreParenCasts();
6919 if (Other->isNullPointerConstant(S.getASTContext(),
6920 Expr::NPC_ValueDependentIsNotNull))
6921 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006922
Jordan Roseeec207f2012-07-17 17:46:44 +00006923 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006924 // LK_String should always be after the other literals, since it has its own
6925 // warning flag.
6926 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenekd3292c82012-12-21 22:46:35 +00006927 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006928 if (LiteralKind == Sema::LK_None) {
Jordan Rose9f63a452012-06-08 21:14:25 +00006929 llvm_unreachable("Unknown Objective-C object literal kind");
6930 }
6931
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006932 if (LiteralKind == Sema::LK_String)
Jordan Roseeec207f2012-07-17 17:46:44 +00006933 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6934 << Literal->getSourceRange();
6935 else
6936 S.Diag(Loc, diag::warn_objc_literal_comparison)
6937 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006938
Jordan Rose8d872ca2012-07-17 17:46:40 +00006939 if (BinaryOperator::isEqualityOp(Opc) &&
6940 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6941 SourceLocation Start = LHS.get()->getLocStart();
6942 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6943 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006944
Jordan Rose8d872ca2012-07-17 17:46:40 +00006945 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6946 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6947 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6948 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006949 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006950}
6951
Douglas Gregor0c6db942009-05-04 06:07:12 +00006952// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006953QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006954 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006955 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006956 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6957
John McCall2de56d12010-08-25 11:45:40 +00006958 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006959
Chris Lattner02dd4b12009-12-05 05:40:13 +00006960 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006961 if (LHS.get()->getType()->isVectorType() ||
6962 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006963 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006964
Richard Trieuf1775fb2011-09-06 21:43:51 +00006965 QualType LHSType = LHS.get()->getType();
6966 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006967
Richard Trieuf1775fb2011-09-06 21:43:51 +00006968 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6969 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006970
Richard Trieuf1775fb2011-09-06 21:43:51 +00006971 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006972
Richard Trieuf1775fb2011-09-06 21:43:51 +00006973 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006974 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006975 !LHS.get()->getLocStart().isMacroID() &&
6976 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006977 // For non-floating point types, check for self-comparisons of the form
6978 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6979 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006980 //
6981 // NOTE: Don't warn about comparison expressions resulting from macro
6982 // expansion. Also don't warn about comparisons which are only self
6983 // comparisons within a template specialization. The warnings should catch
6984 // obvious cases in the definition of the template anyways. The idea is to
6985 // warn when the typed comparison operator will always evaluate to the same
6986 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006987 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006988 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006989 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006990 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006991 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006992 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006993 << (Opc == BO_EQ
6994 || Opc == BO_LE
6995 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006996 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006997 !DRL->getDecl()->getType()->isReferenceType() &&
6998 !DRR->getDecl()->getType()->isReferenceType()) {
6999 // what is it always going to eval to?
7000 char always_evals_to;
7001 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007002 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007003 always_evals_to = 0; // false
7004 break;
John McCall2de56d12010-08-25 11:45:40 +00007005 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007006 always_evals_to = 1; // true
7007 break;
7008 default:
7009 // best we can say is 'a constant'
7010 always_evals_to = 2; // e.g. array1 <= array2
7011 break;
7012 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007013 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007014 << 1 // array
7015 << always_evals_to);
7016 }
7017 }
Chandler Carruth99919472010-07-10 12:30:03 +00007018 }
Mike Stump1eb44332009-09-09 15:08:12 +00007019
Chris Lattner55660a72009-03-08 19:39:53 +00007020 if (isa<CastExpr>(LHSStripped))
7021 LHSStripped = LHSStripped->IgnoreParenCasts();
7022 if (isa<CastExpr>(RHSStripped))
7023 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007024
Chris Lattner55660a72009-03-08 19:39:53 +00007025 // Warn about comparisons against a string constant (unless the other
7026 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007027 Expr *literalString = 0;
7028 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007029 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007030 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007031 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007032 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007033 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007034 } else if ((isa<StringLiteral>(RHSStripped) ||
7035 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007036 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007037 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007038 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007039 literalStringStripped = RHSStripped;
7040 }
7041
7042 if (literalString) {
7043 std::string resultComparison;
7044 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007045 case BO_LT: resultComparison = ") < 0"; break;
7046 case BO_GT: resultComparison = ") > 0"; break;
7047 case BO_LE: resultComparison = ") <= 0"; break;
7048 case BO_GE: resultComparison = ") >= 0"; break;
7049 case BO_EQ: resultComparison = ") == 0"; break;
7050 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007051 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007052 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007053
Ted Kremenek351ba912011-02-23 01:52:04 +00007054 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007055 PDiag(diag::warn_stringcompare)
7056 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007057 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007058 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007059 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007060
Douglas Gregord64fdd02010-06-08 19:50:34 +00007061 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007062 if (LHS.get()->getType()->isArithmeticType() &&
7063 RHS.get()->getType()->isArithmeticType()) {
7064 UsualArithmeticConversions(LHS, RHS);
7065 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007066 return QualType();
7067 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007068 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 LHS = UsualUnaryConversions(LHS.take());
7070 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007071 return QualType();
7072
Richard Trieuf1775fb2011-09-06 21:43:51 +00007073 RHS = UsualUnaryConversions(RHS.take());
7074 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007075 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007076 }
7077
Richard Trieuf1775fb2011-09-06 21:43:51 +00007078 LHSType = LHS.get()->getType();
7079 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007080
Douglas Gregor447b69e2008-11-19 03:25:36 +00007081 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007082 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007083
Richard Trieuccd891a2011-09-09 01:45:06 +00007084 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007085 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007086 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007087 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007088 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007089 if (LHSType->hasFloatingRepresentation())
7090 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007091
Richard Trieuf1775fb2011-09-06 21:43:51 +00007092 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007093 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007094 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007095
Richard Trieuf1775fb2011-09-06 21:43:51 +00007096 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007097 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007098 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007099 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007100
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007101 // All of the following pointer-related warnings are GCC extensions, except
7102 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007103 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007104 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007105 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007106 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007107 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007108
David Blaikie4e4d0842012-03-11 07:00:24 +00007109 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007110 if (LCanPointeeTy == RCanPointeeTy)
7111 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007112 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007113 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7114 // Valid unless comparison between non-null pointer and function pointer
7115 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007116 // In a SFINAE context, we treat this as a hard error to maintain
7117 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007118 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7119 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007120 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007121 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007122
7123 if (isSFINAEContext())
7124 return QualType();
7125
Richard Trieuf1775fb2011-09-06 21:43:51 +00007126 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007127 return ResultTy;
7128 }
7129 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007130
Richard Trieuf1775fb2011-09-06 21:43:51 +00007131 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007132 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007133 else
7134 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007135 }
Eli Friedman3075e762009-08-23 00:27:47 +00007136 // C99 6.5.9p2 and C99 6.5.8p2
7137 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7138 RCanPointeeTy.getUnqualifiedType())) {
7139 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007140 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007141 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 << LHSType << RHSType << LHS.get()->getSourceRange()
7143 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007144 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007145 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007146 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7147 // Valid unless comparison between non-null pointer and function pointer
7148 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007149 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007150 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007151 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007152 } else {
7153 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007154 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007155 }
John McCall34d6f932011-03-11 04:25:25 +00007156 if (LCanPointeeTy != RCanPointeeTy) {
7157 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007158 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007159 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007160 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007161 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007162 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007163 }
Mike Stump1eb44332009-09-09 15:08:12 +00007164
David Blaikie4e4d0842012-03-11 07:00:24 +00007165 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007166 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007167 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007168 return ResultTy;
7169
Mike Stump1eb44332009-09-09 15:08:12 +00007170 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007171 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007172 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007173 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007174 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007175 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7176 RHS = ImpCastExprToType(RHS.take(), LHSType,
7177 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007178 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007179 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007180 return ResultTy;
7181 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007182 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007183 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007184 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007185 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7186 LHS = ImpCastExprToType(LHS.take(), RHSType,
7187 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007188 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007189 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007190 return ResultTy;
7191 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007192
7193 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007194 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007195 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7196 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007197 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007198 else
7199 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007200 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007201
7202 // Handle scoped enumeration types specifically, since they don't promote
7203 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007204 if (LHS.get()->getType()->isEnumeralType() &&
7205 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7206 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007207 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007208 }
Mike Stump1eb44332009-09-09 15:08:12 +00007209
Steve Naroff1c7d0672008-09-04 15:10:53 +00007210 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007211 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007212 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007213 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7214 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007215
Steve Naroff1c7d0672008-09-04 15:10:53 +00007216 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007217 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007218 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007219 << LHSType << RHSType << LHS.get()->getSourceRange()
7220 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007221 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007222 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007223 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007224 }
John Wiegley429bb272011-04-08 18:41:53 +00007225
Steve Naroff59f53942008-09-28 01:11:11 +00007226 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007227 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007228 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7229 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007230 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007231 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007232 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007233 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007234 ->getPointeeType()->isVoidType())))
7235 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007236 << LHSType << RHSType << LHS.get()->getSourceRange()
7237 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007238 }
John McCall34d6f932011-03-11 04:25:25 +00007239 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007240 LHS = ImpCastExprToType(LHS.take(), RHSType,
7241 RHSType->isPointerType() ? CK_BitCast
7242 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007243 else
John McCall1d9b3b22011-09-09 05:25:32 +00007244 RHS = ImpCastExprToType(RHS.take(), LHSType,
7245 LHSType->isPointerType() ? CK_BitCast
7246 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007247 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007248 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007249
Richard Trieuf1775fb2011-09-06 21:43:51 +00007250 if (LHSType->isObjCObjectPointerType() ||
7251 RHSType->isObjCObjectPointerType()) {
7252 const PointerType *LPT = LHSType->getAs<PointerType>();
7253 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007254 if (LPT || RPT) {
7255 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7256 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007257
Steve Naroffa8069f12008-11-17 19:49:16 +00007258 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007259 !Context.typesAreCompatible(LHSType, RHSType)) {
7260 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007261 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007262 }
John McCall34d6f932011-03-11 04:25:25 +00007263 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007264 LHS = ImpCastExprToType(LHS.take(), RHSType,
7265 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007266 else
John McCall1d9b3b22011-09-09 05:25:32 +00007267 RHS = ImpCastExprToType(RHS.take(), LHSType,
7268 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007269 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007270 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007271 if (LHSType->isObjCObjectPointerType() &&
7272 RHSType->isObjCObjectPointerType()) {
7273 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7274 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007275 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007276 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007277 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007278
John McCall34d6f932011-03-11 04:25:25 +00007279 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007280 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007281 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007282 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007283 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007284 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007285 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007286 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7287 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007288 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007289 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007290 if (LangOpts.DebuggerSupport) {
7291 // Under a debugger, allow the comparison of pointers to integers,
7292 // since users tend to want to compare addresses.
7293 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007294 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007295 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007296 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007297 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007298 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007299 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007300 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7301 isError = true;
7302 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007303 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007304
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007305 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007306 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007307 << LHSType << RHSType << LHS.get()->getSourceRange()
7308 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007309 if (isError)
7310 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007311 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007312
Richard Trieuf1775fb2011-09-06 21:43:51 +00007313 if (LHSType->isIntegerType())
7314 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007315 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007316 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007317 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007318 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007319 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007320 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007321
Steve Naroff39218df2008-09-04 16:56:14 +00007322 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007323 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007324 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7325 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007326 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007327 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007328 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007329 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7330 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007331 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007332 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007333
Richard Trieuf1775fb2011-09-06 21:43:51 +00007334 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007335}
7336
Tanya Lattner4f692c22012-01-16 21:02:28 +00007337
7338// Return a signed type that is of identical size and number of elements.
7339// For floating point vectors, return an integer type of identical size
7340// and number of elements.
7341QualType Sema::GetSignedVectorType(QualType V) {
7342 const VectorType *VTy = V->getAs<VectorType>();
7343 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7344 if (TypeSize == Context.getTypeSize(Context.CharTy))
7345 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7346 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7347 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7348 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7349 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7350 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7351 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7352 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7353 "Unhandled vector element size in vector compare");
7354 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7355}
7356
Nate Begemanbe2341d2008-07-14 18:02:46 +00007357/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007358/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007359/// like a scalar comparison, a vector comparison produces a vector of integer
7360/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007361QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007362 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007363 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007364 // Check to make sure we're operating on vectors of the same type and width,
7365 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007366 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007367 if (vType.isNull())
7368 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007369
Richard Trieu9f60dee2011-09-07 01:19:57 +00007370 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007371
Anton Yartsev7870b132011-03-27 15:36:07 +00007372 // If AltiVec, the comparison results in a numeric type, i.e.
7373 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007374 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007375 return Context.getLogicalOperationType();
7376
Nate Begemanbe2341d2008-07-14 18:02:46 +00007377 // For non-floating point types, check for self-comparisons of the form
7378 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7379 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007380 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007381 if (DeclRefExpr* DRL
7382 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7383 if (DeclRefExpr* DRR
7384 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007385 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007386 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007387 PDiag(diag::warn_comparison_always)
7388 << 0 // self-
7389 << 2 // "a constant"
7390 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007391 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007392
Nate Begemanbe2341d2008-07-14 18:02:46 +00007393 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007394 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007395 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007396 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007397 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007398
7399 // Return a signed type for the vector.
7400 return GetSignedVectorType(LHSType);
7401}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007402
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007403QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7404 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007405 // Ensure that either both operands are of the same vector type, or
7406 // one operand is of a vector type and the other is of its element type.
7407 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7408 if (vType.isNull() || vType->isFloatingType())
7409 return InvalidOperands(Loc, LHS, RHS);
7410
7411 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007412}
7413
Reid Spencer5f016e22007-07-11 17:01:13 +00007414inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007415 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007416 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7417
Richard Trieu9f60dee2011-09-07 01:19:57 +00007418 if (LHS.get()->getType()->isVectorType() ||
7419 RHS.get()->getType()->isVectorType()) {
7420 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7421 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007422 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007423
Richard Trieu9f60dee2011-09-07 01:19:57 +00007424 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007425 }
Steve Naroff90045e82007-07-13 23:32:42 +00007426
Richard Trieu9f60dee2011-09-07 01:19:57 +00007427 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7428 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007429 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007430 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007431 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007432 LHS = LHSResult.take();
7433 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007434
Eli Friedman860a3192012-06-16 02:19:17 +00007435 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007436 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007437 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007438}
7439
7440inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007441 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007442
Tanya Lattner4f692c22012-01-16 21:02:28 +00007443 // Check vector operands differently.
7444 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7445 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7446
Chris Lattner90a8f272010-07-13 19:41:32 +00007447 // Diagnose cases where the user write a logical and/or but probably meant a
7448 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7449 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007450 if (LHS.get()->getType()->isIntegerType() &&
7451 !LHS.get()->getType()->isBooleanType() &&
7452 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007453 // Don't warn in macros or template instantiations.
7454 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007455 // If the RHS can be constant folded, and if it constant folds to something
7456 // that isn't 0 or 1 (which indicate a potential logical operation that
7457 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007458 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007459 llvm::APSInt Result;
7460 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007461 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007462 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007463 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007464 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007465 << (Opc == BO_LAnd ? "&&" : "||");
7466 // Suggest replacing the logical operator with the bitwise version
7467 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7468 << (Opc == BO_LAnd ? "&" : "|")
7469 << FixItHint::CreateReplacement(SourceRange(
7470 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007471 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007472 Opc == BO_LAnd ? "&" : "|");
7473 if (Opc == BO_LAnd)
7474 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7475 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7476 << FixItHint::CreateRemoval(
7477 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007478 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007479 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007480 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007481 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007482 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007483 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007484
David Blaikie4e4d0842012-03-11 07:00:24 +00007485 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007486 LHS = UsualUnaryConversions(LHS.take());
7487 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007488 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007489
Richard Trieu9f60dee2011-09-07 01:19:57 +00007490 RHS = UsualUnaryConversions(RHS.take());
7491 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007492 return QualType();
7493
Richard Trieu9f60dee2011-09-07 01:19:57 +00007494 if (!LHS.get()->getType()->isScalarType() ||
7495 !RHS.get()->getType()->isScalarType())
7496 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007497
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007498 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007499 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007500
John McCall75f7c0f2010-06-04 00:29:51 +00007501 // The following is safe because we only use this method for
7502 // non-overloadable operands.
7503
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007504 // C++ [expr.log.and]p1
7505 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007506 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007507 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7508 if (LHSRes.isInvalid())
7509 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007510 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007511
Richard Trieu9f60dee2011-09-07 01:19:57 +00007512 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7513 if (RHSRes.isInvalid())
7514 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007515 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007516
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007517 // C++ [expr.log.and]p2
7518 // C++ [expr.log.or]p2
7519 // The result is a bool.
7520 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007521}
7522
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007523/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7524/// is a read-only property; return true if so. A readonly property expression
7525/// depends on various declarations and thus must be treated specially.
7526///
Mike Stump1eb44332009-09-09 15:08:12 +00007527static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007528 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7529 if (!PropExpr) return false;
7530 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007531
John McCall3c3b7f92011-10-25 17:37:35 +00007532 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7533 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007534 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007535 PropExpr->getBase()->getType();
7536
John McCall3c3b7f92011-10-25 17:37:35 +00007537 if (const ObjCObjectPointerType *OPT =
7538 BaseType->getAsObjCInterfacePointerType())
7539 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7540 if (S.isPropertyReadonly(PDecl, IFace))
7541 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007542 return false;
7543}
7544
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007545static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007546 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7547 if (!ME) return false;
7548 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7549 ObjCMessageExpr *Base =
7550 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7551 if (!Base) return false;
7552 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007553}
7554
John McCall78dae242012-03-13 00:37:01 +00007555/// Is the given expression (which must be 'const') a reference to a
7556/// variable which was originally non-const, but which has become
7557/// 'const' due to being captured within a block?
7558enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7559static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7560 assert(E->isLValue() && E->getType().isConstQualified());
7561 E = E->IgnoreParens();
7562
7563 // Must be a reference to a declaration from an enclosing scope.
7564 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7565 if (!DRE) return NCCK_None;
7566 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7567
7568 // The declaration must be a variable which is not declared 'const'.
7569 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7570 if (!var) return NCCK_None;
7571 if (var->getType().isConstQualified()) return NCCK_None;
7572 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7573
7574 // Decide whether the first capture was for a block or a lambda.
7575 DeclContext *DC = S.CurContext;
7576 while (DC->getParent() != var->getDeclContext())
7577 DC = DC->getParent();
7578 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7579}
7580
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007581/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7582/// emit an error and return true. If so, return false.
7583static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007584 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007585 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007586 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007587 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007588 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7589 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007590 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7591 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007592 if (IsLV == Expr::MLV_Valid)
7593 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007594
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007595 unsigned Diag = 0;
7596 bool NeedType = false;
7597 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007598 case Expr::MLV_ConstQualified:
7599 Diag = diag::err_typecheck_assign_const;
7600
John McCall78dae242012-03-13 00:37:01 +00007601 // Use a specialized diagnostic when we're assigning to an object
7602 // from an enclosing function or block.
7603 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7604 if (NCCK == NCCK_Block)
7605 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7606 else
7607 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7608 break;
7609 }
7610
John McCall7acddac2011-06-17 06:42:21 +00007611 // In ARC, use some specialized diagnostics for occasions where we
7612 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007613 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007614 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7615 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7616 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7617
John McCall7acddac2011-06-17 06:42:21 +00007618 // Use the normal diagnostic if it's pseudo-__strong but the
7619 // user actually wrote 'const'.
7620 if (var->isARCPseudoStrong() &&
7621 (!var->getTypeSourceInfo() ||
7622 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7623 // There are two pseudo-strong cases:
7624 // - self
John McCallf85e1932011-06-15 23:02:42 +00007625 ObjCMethodDecl *method = S.getCurMethodDecl();
7626 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007627 Diag = method->isClassMethod()
7628 ? diag::err_typecheck_arc_assign_self_class_method
7629 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007630
7631 // - fast enumeration variables
7632 else
John McCallf85e1932011-06-15 23:02:42 +00007633 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007634
John McCallf85e1932011-06-15 23:02:42 +00007635 SourceRange Assign;
7636 if (Loc != OrigLoc)
7637 Assign = SourceRange(OrigLoc, OrigLoc);
7638 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7639 // We need to preserve the AST regardless, so migration tool
7640 // can do its job.
7641 return false;
7642 }
7643 }
7644 }
7645
7646 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007647 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007648 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007649 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7650 NeedType = true;
7651 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007652 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007653 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7654 NeedType = true;
7655 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007656 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007657 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7658 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007659 case Expr::MLV_Valid:
7660 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007661 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007662 case Expr::MLV_MemberFunction:
7663 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007664 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7665 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007666 case Expr::MLV_IncompleteType:
7667 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007668 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007669 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007670 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007671 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7672 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007673 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007674 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007675 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007676 case Expr::MLV_InvalidMessageExpression:
7677 Diag = diag::error_readonly_message_assignment;
7678 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007679 case Expr::MLV_SubObjCPropertySetting:
7680 Diag = diag::error_no_subobject_property_setting;
7681 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007682 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007683
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007684 SourceRange Assign;
7685 if (Loc != OrigLoc)
7686 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007687 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007688 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007689 else
Mike Stump1eb44332009-09-09 15:08:12 +00007690 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007691 return true;
7692}
7693
Nico Weber7c81b432012-07-03 02:03:06 +00007694static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7695 SourceLocation Loc,
7696 Sema &Sema) {
7697 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007698 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7699 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7700 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7701 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007702 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007703 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007704
Nico Weber7c81b432012-07-03 02:03:06 +00007705 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007706 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7707 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7708 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7709 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7710 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7711 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007712 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007713 }
7714}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007715
7716// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007717QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007718 SourceLocation Loc,
7719 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007720 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7721
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007722 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007723 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007724 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007725
Richard Trieu268942b2011-09-07 01:33:52 +00007726 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007727 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7728 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007729 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007730 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007731 Expr *RHSCheck = RHS.get();
7732
Nico Weber7c81b432012-07-03 02:03:06 +00007733 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007734
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007735 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007736 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007737 if (RHS.isInvalid())
7738 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007739 // Special case of NSObject attributes on c-style pointer types.
7740 if (ConvTy == IncompatiblePointer &&
7741 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007742 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007743 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007744 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007745 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007746
John McCallf89e55a2010-11-18 06:31:45 +00007747 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007748 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007749 Diag(Loc, diag::err_objc_object_assignment)
7750 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007751
Chris Lattner2c156472008-08-21 18:04:13 +00007752 // If the RHS is a unary plus or minus, check to see if they = and + are
7753 // right next to each other. If so, the user may have typo'd "x =+ 4"
7754 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007755 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7756 RHSCheck = ICE->getSubExpr();
7757 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007758 if ((UO->getOpcode() == UO_Plus ||
7759 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007760 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007761 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007762 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007763 // And there is a space or other character before the subexpr of the
7764 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007765 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007766 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007767 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007768 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007769 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007770 }
Chris Lattner2c156472008-08-21 18:04:13 +00007771 }
John McCallf85e1932011-06-15 23:02:42 +00007772
7773 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007774 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7775 // Warn about retain cycles where a block captures the LHS, but
7776 // not if the LHS is a simple variable into which the block is
7777 // being stored...unless that variable can be captured by reference!
7778 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7779 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7780 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7781 checkRetainCycles(LHSExpr, RHS.get());
7782
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007783 // It is safe to assign a weak reference into a strong variable.
7784 // Although this code can still have problems:
7785 // id x = self.weakProp;
7786 // id y = self.weakProp;
7787 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7788 // paths through the function. This should be revisited if
7789 // -Wrepeated-use-of-weak is made flow-sensitive.
7790 DiagnosticsEngine::Level Level =
7791 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7792 RHS.get()->getLocStart());
7793 if (Level != DiagnosticsEngine::Ignored)
7794 getCurFunction()->markSafeWeakUse(RHS.get());
7795
Jordan Rosee10f4d32012-09-15 02:48:31 +00007796 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007797 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007798 }
John McCallf85e1932011-06-15 23:02:42 +00007799 }
Chris Lattner2c156472008-08-21 18:04:13 +00007800 } else {
7801 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007802 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007803 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007804
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007805 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007806 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007807 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007808
Richard Trieu268942b2011-09-07 01:33:52 +00007809 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007810
Reid Spencer5f016e22007-07-11 17:01:13 +00007811 // C99 6.5.16p3: The type of an assignment expression is the type of the
7812 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007813 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007814 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7815 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007816 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007817 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007818 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007819 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007820}
7821
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007822// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007823static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007824 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007825 LHS = S.CheckPlaceholderExpr(LHS.take());
7826 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007827 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007828 return QualType();
7829
John McCallcf2e5062010-10-12 07:14:40 +00007830 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7831 // operands, but not unary promotions.
7832 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007833
John McCallf6a16482010-12-04 03:47:34 +00007834 // So we treat the LHS as a ignored value, and in C++ we allow the
7835 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007836 LHS = S.IgnoredValueConversions(LHS.take());
7837 if (LHS.isInvalid())
7838 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007839
Eli Friedmana6115062012-05-24 00:47:05 +00007840 S.DiagnoseUnusedExprResult(LHS.get());
7841
David Blaikie4e4d0842012-03-11 07:00:24 +00007842 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007843 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7844 if (RHS.isInvalid())
7845 return QualType();
7846 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007847 S.RequireCompleteType(Loc, RHS.get()->getType(),
7848 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007849 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007850
John Wiegley429bb272011-04-08 18:41:53 +00007851 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007852}
7853
Steve Naroff49b45262007-07-13 16:58:59 +00007854/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7855/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007856static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7857 ExprValueKind &VK,
7858 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007859 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007860 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007861 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007862
Chris Lattner3528d352008-11-21 07:05:48 +00007863 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007864 // Atomic types can be used for increment / decrement where the non-atomic
7865 // versions can, so ignore the _Atomic() specifier for the purpose of
7866 // checking.
7867 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7868 ResType = ResAtomicType->getValueType();
7869
Chris Lattner3528d352008-11-21 07:05:48 +00007870 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007871
David Blaikie4e4d0842012-03-11 07:00:24 +00007872 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007873 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007874 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007875 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007876 return QualType();
7877 }
7878 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007879 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007880 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007881 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007882 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007883 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007884 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007885 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007886 } else if (ResType->isObjCObjectPointerType()) {
7887 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7888 // Otherwise, we just need a complete type.
7889 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7890 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7891 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007892 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007893 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007894 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007895 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007896 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007897 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007898 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007899 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007900 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007901 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007902 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007903 } else {
John McCall09431682010-11-18 19:01:18 +00007904 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007905 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007906 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007907 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007908 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007909 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007910 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007911 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007912 // In C++, a prefix increment is the same type as the operand. Otherwise
7913 // (in C or with postfix), the increment is the unqualified type of the
7914 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007915 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007916 VK = VK_LValue;
7917 return ResType;
7918 } else {
7919 VK = VK_RValue;
7920 return ResType.getUnqualifiedType();
7921 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007922}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007923
7924
Anders Carlsson369dee42008-02-01 07:15:58 +00007925/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007926/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007927/// where the declaration is needed for type checking. We only need to
7928/// handle cases when the expression references a function designator
7929/// or is an lvalue. Here are some examples:
7930/// - &(x) => x
7931/// - &*****f => f for f a function designator.
7932/// - &s.xx => s
7933/// - &s.zz[1].yy -> s, if zz is an array
7934/// - *(x + 1) -> x, if x is an array
7935/// - &"123"[2] -> 0
7936/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007937static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007938 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007939 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007940 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007941 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007942 // If this is an arrow operator, the address is an offset from
7943 // the base's value, so the object the base refers to is
7944 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007945 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007946 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007947 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007948 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007949 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007950 // FIXME: This code shouldn't be necessary! We should catch the implicit
7951 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007952 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7953 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7954 if (ICE->getSubExpr()->getType()->isArrayType())
7955 return getPrimaryDecl(ICE->getSubExpr());
7956 }
7957 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007958 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007959 case Stmt::UnaryOperatorClass: {
7960 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007961
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007962 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007963 case UO_Real:
7964 case UO_Imag:
7965 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007966 return getPrimaryDecl(UO->getSubExpr());
7967 default:
7968 return 0;
7969 }
7970 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007971 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007972 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007973 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007974 // If the result of an implicit cast is an l-value, we care about
7975 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007976 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007977 default:
7978 return 0;
7979 }
7980}
7981
Richard Trieu5520f232011-09-07 21:46:33 +00007982namespace {
7983 enum {
7984 AO_Bit_Field = 0,
7985 AO_Vector_Element = 1,
7986 AO_Property_Expansion = 2,
7987 AO_Register_Variable = 3,
7988 AO_No_Error = 4
7989 };
7990}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007991/// \brief Diagnose invalid operand for address of operations.
7992///
7993/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007994static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7995 Expr *E, unsigned Type) {
7996 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7997}
7998
Reid Spencer5f016e22007-07-11 17:01:13 +00007999/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008000/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008001/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008002/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008003/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008004/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008005/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00008006static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00008007 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00008008 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8009 if (PTy->getKind() == BuiltinType::Overload) {
8010 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8011 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8012 << OrigOp.get()->getSourceRange();
8013 return QualType();
8014 }
8015
8016 return S.Context.OverloadTy;
8017 }
8018
8019 if (PTy->getKind() == BuiltinType::UnknownAny)
8020 return S.Context.UnknownAnyTy;
8021
8022 if (PTy->getKind() == BuiltinType::BoundMember) {
8023 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8024 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008025 return QualType();
8026 }
John McCall3c3b7f92011-10-25 17:37:35 +00008027
8028 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8029 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008030 }
John McCall9c72c602010-08-27 09:08:28 +00008031
John McCall3c3b7f92011-10-25 17:37:35 +00008032 if (OrigOp.get()->isTypeDependent())
8033 return S.Context.DependentTy;
8034
8035 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008036
John McCall9c72c602010-08-27 09:08:28 +00008037 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008038 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008039
David Blaikie4e4d0842012-03-11 07:00:24 +00008040 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008041 // Implement C99-only parts of addressof rules.
8042 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008043 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008044 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8045 // (assuming the deref expression is valid).
8046 return uOp->getSubExpr()->getType();
8047 }
8048 // Technically, there should be a check for array subscript
8049 // expressions here, but the result of one is always an lvalue anyway.
8050 }
John McCall5808ce42011-02-03 08:15:49 +00008051 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008052 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008053 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008054
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008055 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008056 bool sfinae = S.isSFINAEContext();
8057 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8058 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008059 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008060 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008061 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008062 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008063 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008064 } else if (lval == Expr::LV_MemberFunction) {
8065 // If it's an instance method, make a member pointer.
8066 // The expression must have exactly the form &A::foo.
8067
8068 // If the underlying expression isn't a decl ref, give up.
8069 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008070 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008071 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008072 return QualType();
8073 }
8074 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8075 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8076
8077 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008078 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008079 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008080 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008081
8082 // The method was named without a qualifier.
8083 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008084 if (MD->getParent()->getName().empty())
8085 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8086 << op->getSourceRange();
8087 else {
8088 SmallString<32> Str;
8089 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8090 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8091 << op->getSourceRange()
8092 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8093 }
John McCall9c72c602010-08-27 09:08:28 +00008094 }
8095
John McCall09431682010-11-18 19:01:18 +00008096 return S.Context.getMemberPointerType(op->getType(),
8097 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008098 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008099 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008100 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008101 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008102 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008103 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008104 AddressOfError = AO_Property_Expansion;
8105 } else {
8106 // FIXME: emit more specific diag...
8107 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8108 << op->getSourceRange();
8109 return QualType();
8110 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008111 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008112 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008113 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008114 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008115 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008116 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008117 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008118 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008119 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008120 // with the register storage-class specifier.
8121 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008122 // in C++ it is not error to take address of a register
8123 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008124 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008125 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008126 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008127 }
John McCallba135432009-11-21 08:51:07 +00008128 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008129 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008130 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008131 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008132 // Could be a pointer to member, though, if there is an explicit
8133 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008134 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008135 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008136 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008137 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008138 S.Diag(OpLoc,
8139 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008140 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008141 return QualType();
8142 }
Mike Stump1eb44332009-09-09 15:08:12 +00008143
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008144 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8145 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008146 return S.Context.getMemberPointerType(op->getType(),
8147 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008148 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008149 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008150 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008151 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008152 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008153
Richard Trieu5520f232011-09-07 21:46:33 +00008154 if (AddressOfError != AO_No_Error) {
8155 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8156 return QualType();
8157 }
8158
Eli Friedman441cf102009-05-16 23:27:50 +00008159 if (lval == Expr::LV_IncompleteVoidType) {
8160 // Taking the address of a void variable is technically illegal, but we
8161 // allow it in cases which are otherwise valid.
8162 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008163 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008164 }
8165
Reid Spencer5f016e22007-07-11 17:01:13 +00008166 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008167 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008168 return S.Context.getObjCObjectPointerType(op->getType());
8169 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008170}
8171
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008172/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008173static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8174 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008175 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008176 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008177
John Wiegley429bb272011-04-08 18:41:53 +00008178 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8179 if (ConvResult.isInvalid())
8180 return QualType();
8181 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008182 QualType OpTy = Op->getType();
8183 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008184
8185 if (isa<CXXReinterpretCastExpr>(Op)) {
8186 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8187 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8188 Op->getSourceRange());
8189 }
8190
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008191 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8192 // is an incomplete type or void. It would be possible to warn about
8193 // dereferencing a void pointer, but it's completely well-defined, and such a
8194 // warning is unlikely to catch any mistakes.
8195 if (const PointerType *PT = OpTy->getAs<PointerType>())
8196 Result = PT->getPointeeType();
8197 else if (const ObjCObjectPointerType *OPT =
8198 OpTy->getAs<ObjCObjectPointerType>())
8199 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008200 else {
John McCallfb8721c2011-04-10 19:13:55 +00008201 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008202 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008203 if (PR.take() != Op)
8204 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008205 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008206
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008207 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008208 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008209 << OpTy << Op->getSourceRange();
8210 return QualType();
8211 }
John McCall09431682010-11-18 19:01:18 +00008212
8213 // Dereferences are usually l-values...
8214 VK = VK_LValue;
8215
8216 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008217 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008218 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008219
8220 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008221}
8222
John McCall2de56d12010-08-25 11:45:40 +00008223static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008224 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008225 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008226 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008227 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008228 case tok::periodstar: Opc = BO_PtrMemD; break;
8229 case tok::arrowstar: Opc = BO_PtrMemI; break;
8230 case tok::star: Opc = BO_Mul; break;
8231 case tok::slash: Opc = BO_Div; break;
8232 case tok::percent: Opc = BO_Rem; break;
8233 case tok::plus: Opc = BO_Add; break;
8234 case tok::minus: Opc = BO_Sub; break;
8235 case tok::lessless: Opc = BO_Shl; break;
8236 case tok::greatergreater: Opc = BO_Shr; break;
8237 case tok::lessequal: Opc = BO_LE; break;
8238 case tok::less: Opc = BO_LT; break;
8239 case tok::greaterequal: Opc = BO_GE; break;
8240 case tok::greater: Opc = BO_GT; break;
8241 case tok::exclaimequal: Opc = BO_NE; break;
8242 case tok::equalequal: Opc = BO_EQ; break;
8243 case tok::amp: Opc = BO_And; break;
8244 case tok::caret: Opc = BO_Xor; break;
8245 case tok::pipe: Opc = BO_Or; break;
8246 case tok::ampamp: Opc = BO_LAnd; break;
8247 case tok::pipepipe: Opc = BO_LOr; break;
8248 case tok::equal: Opc = BO_Assign; break;
8249 case tok::starequal: Opc = BO_MulAssign; break;
8250 case tok::slashequal: Opc = BO_DivAssign; break;
8251 case tok::percentequal: Opc = BO_RemAssign; break;
8252 case tok::plusequal: Opc = BO_AddAssign; break;
8253 case tok::minusequal: Opc = BO_SubAssign; break;
8254 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8255 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8256 case tok::ampequal: Opc = BO_AndAssign; break;
8257 case tok::caretequal: Opc = BO_XorAssign; break;
8258 case tok::pipeequal: Opc = BO_OrAssign; break;
8259 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008260 }
8261 return Opc;
8262}
8263
John McCall2de56d12010-08-25 11:45:40 +00008264static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008265 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008266 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008267 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008268 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008269 case tok::plusplus: Opc = UO_PreInc; break;
8270 case tok::minusminus: Opc = UO_PreDec; break;
8271 case tok::amp: Opc = UO_AddrOf; break;
8272 case tok::star: Opc = UO_Deref; break;
8273 case tok::plus: Opc = UO_Plus; break;
8274 case tok::minus: Opc = UO_Minus; break;
8275 case tok::tilde: Opc = UO_Not; break;
8276 case tok::exclaim: Opc = UO_LNot; break;
8277 case tok::kw___real: Opc = UO_Real; break;
8278 case tok::kw___imag: Opc = UO_Imag; break;
8279 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008280 }
8281 return Opc;
8282}
8283
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008284/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8285/// This warning is only emitted for builtin assignment operations. It is also
8286/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008287static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008288 SourceLocation OpLoc) {
8289 if (!S.ActiveTemplateInstantiations.empty())
8290 return;
8291 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8292 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008293 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8294 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8295 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8296 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8297 if (!LHSDeclRef || !RHSDeclRef ||
8298 LHSDeclRef->getLocation().isMacroID() ||
8299 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008300 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008301 const ValueDecl *LHSDecl =
8302 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8303 const ValueDecl *RHSDecl =
8304 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8305 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008306 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008307 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008308 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008309 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008310 if (RefTy->getPointeeType().isVolatileQualified())
8311 return;
8312
8313 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008314 << LHSDeclRef->getType()
8315 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008316}
8317
Douglas Gregoreaebc752008-11-06 23:29:22 +00008318/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8319/// operator @p Opc at location @c TokLoc. This routine only supports
8320/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008321ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008322 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008323 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008324 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008325 // The syntax only allows initializer lists on the RHS of assignment,
8326 // so we don't need to worry about accepting invalid code for
8327 // non-assignment operators.
8328 // C++11 5.17p9:
8329 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8330 // of x = {} is x = T().
8331 InitializationKind Kind =
8332 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8333 InitializedEntity Entity =
8334 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8335 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008336 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008337 if (Init.isInvalid())
8338 return Init;
8339 RHSExpr = Init.take();
8340 }
8341
Richard Trieu78ea78b2011-09-07 01:49:20 +00008342 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008343 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008344 // The following two variables are used for compound assignment operators
8345 QualType CompLHSTy; // Type of LHS after promotions for computation
8346 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008347 ExprValueKind VK = VK_RValue;
8348 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008349
8350 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008351 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008352 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008353 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008354 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8355 VK = LHS.get()->getValueKind();
8356 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008357 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008358 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008359 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008360 break;
John McCall2de56d12010-08-25 11:45:40 +00008361 case BO_PtrMemD:
8362 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008363 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008364 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008365 break;
John McCall2de56d12010-08-25 11:45:40 +00008366 case BO_Mul:
8367 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008368 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008369 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008370 break;
John McCall2de56d12010-08-25 11:45:40 +00008371 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008372 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008373 break;
John McCall2de56d12010-08-25 11:45:40 +00008374 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008375 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008376 break;
John McCall2de56d12010-08-25 11:45:40 +00008377 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008378 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008379 break;
John McCall2de56d12010-08-25 11:45:40 +00008380 case BO_Shl:
8381 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008382 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008383 break;
John McCall2de56d12010-08-25 11:45:40 +00008384 case BO_LE:
8385 case BO_LT:
8386 case BO_GE:
8387 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008388 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008389 break;
John McCall2de56d12010-08-25 11:45:40 +00008390 case BO_EQ:
8391 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008392 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008393 break;
John McCall2de56d12010-08-25 11:45:40 +00008394 case BO_And:
8395 case BO_Xor:
8396 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008397 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008398 break;
John McCall2de56d12010-08-25 11:45:40 +00008399 case BO_LAnd:
8400 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008401 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008402 break;
John McCall2de56d12010-08-25 11:45:40 +00008403 case BO_MulAssign:
8404 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008405 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008406 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008407 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008408 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8409 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008410 break;
John McCall2de56d12010-08-25 11:45:40 +00008411 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008412 CompResultTy = CheckRemainderOperands(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_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008418 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008421 break;
John McCall2de56d12010-08-25 11:45:40 +00008422 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008423 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8424 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8425 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008426 break;
John McCall2de56d12010-08-25 11:45:40 +00008427 case BO_ShlAssign:
8428 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008429 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008430 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008431 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8432 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008433 break;
John McCall2de56d12010-08-25 11:45:40 +00008434 case BO_AndAssign:
8435 case BO_XorAssign:
8436 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008437 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008438 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008439 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8440 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008441 break;
John McCall2de56d12010-08-25 11:45:40 +00008442 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008443 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008444 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008445 VK = RHS.get()->getValueKind();
8446 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008447 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008448 break;
8449 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008450 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008451 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008452
8453 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008454 CheckArrayAccess(LHS.get());
8455 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008456
Eli Friedmanab3a8522009-03-28 01:22:36 +00008457 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008458 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008459 ResultTy, VK, OK, OpLoc,
8460 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008461 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008462 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008463 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008464 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008465 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008466 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008467 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008468 CompResultTy, OpLoc,
8469 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008470}
8471
Sebastian Redlaee3c932009-10-27 12:10:02 +00008472/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8473/// operators are mixed in a way that suggests that the programmer forgot that
8474/// comparison operators have higher precedence. The most typical example of
8475/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008476static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008477 SourceLocation OpLoc, Expr *LHSExpr,
8478 Expr *RHSExpr) {
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008479 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8480 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008481
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008482 // Check that one of the sides is a comparison operator.
8483 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8484 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8485 if (!isLeftComp && !isRightComp)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008486 return;
8487
8488 // Bitwise operations are sometimes used as eager logical ops.
8489 // Don't diagnose this.
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008490 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8491 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8492 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008493 return;
8494
Richard Trieu78ea78b2011-09-07 01:49:20 +00008495 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8496 OpLoc)
8497 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008498 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu70979d42011-08-10 22:41:34 +00008499 SourceRange ParensRange = isLeftComp ?
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008500 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8501 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008502
8503 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008504 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu70979d42011-08-10 22:41:34 +00008505 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008506 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008507 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008508 SuggestParentheses(Self, OpLoc,
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008509 Self.PDiag(diag::note_precedence_bitwise_first)
8510 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu70979d42011-08-10 22:41:34 +00008511 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008512}
8513
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008514/// \brief It accepts a '&' expr that is inside a '|' one.
8515/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8516/// in parentheses.
8517static void
8518EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8519 BinaryOperator *Bop) {
8520 assert(Bop->getOpcode() == BO_And);
8521 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8522 << Bop->getSourceRange() << OpLoc;
8523 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008524 Self.PDiag(diag::note_precedence_silence)
8525 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008526 Bop->getSourceRange());
8527}
8528
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008529/// \brief It accepts a '&&' expr that is inside a '||' one.
8530/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8531/// in parentheses.
8532static void
8533EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008534 BinaryOperator *Bop) {
8535 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008536 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8537 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008538 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008539 Self.PDiag(diag::note_precedence_silence)
8540 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008541 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008542}
8543
8544/// \brief Returns true if the given expression can be evaluated as a constant
8545/// 'true'.
8546static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8547 bool Res;
8548 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8549}
8550
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008551/// \brief Returns true if the given expression can be evaluated as a constant
8552/// 'false'.
8553static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8554 bool Res;
8555 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8556}
8557
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008558/// \brief Look for '&&' in the left hand of a '||' expr.
8559static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008560 Expr *LHSExpr, Expr *RHSExpr) {
8561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008562 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008563 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008564 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008565 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008566 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8567 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8568 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8569 } else if (Bop->getOpcode() == BO_LOr) {
8570 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8571 // If it's "a || b && 1 || c" we didn't warn earlier for
8572 // "a || b && 1", but warn now.
8573 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8575 }
8576 }
8577 }
8578}
8579
8580/// \brief Look for '&&' in the right hand of a '||' expr.
8581static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008582 Expr *LHSExpr, Expr *RHSExpr) {
8583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008584 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008585 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008586 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008587 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008588 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8589 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8590 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008591 }
8592 }
8593}
8594
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008595/// \brief Look for '&' in the left or right hand of a '|' expr.
8596static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8597 Expr *OrArg) {
8598 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8599 if (Bop->getOpcode() == BO_And)
8600 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8601 }
8602}
8603
David Blaikieb3f55c52012-10-05 00:41:03 +00008604static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +00008605 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +00008606 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8607 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008608 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008609 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +00008610 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +00008611 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008612 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008613 Bop->getSourceRange());
8614 }
8615 }
8616}
8617
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008618/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008619/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008620static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008621 SourceLocation OpLoc, Expr *LHSExpr,
8622 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008623 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008624 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008625 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008626
8627 // Diagnose "arg1 & arg2 | arg3"
8628 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008629 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8630 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008631 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008632
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008633 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8634 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008635 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008636 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8637 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008638 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008639
8640 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8641 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +00008642 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8643 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8644 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +00008645 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008646}
8647
Reid Spencer5f016e22007-07-11 17:01:13 +00008648// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008649ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008650 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008651 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008652 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008653 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8654 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008655
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008656 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008657 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008658
Richard Trieubefece12011-09-07 02:02:10 +00008659 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008660}
8661
John McCall3c3b7f92011-10-25 17:37:35 +00008662/// Build an overloaded binary operator expression in the given scope.
8663static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8664 BinaryOperatorKind Opc,
8665 Expr *LHS, Expr *RHS) {
8666 // Find all of the overloaded operators visible from this
8667 // point. We perform both an operator-name lookup from the local
8668 // scope and an argument-dependent lookup based on the types of
8669 // the arguments.
8670 UnresolvedSet<16> Functions;
8671 OverloadedOperatorKind OverOp
8672 = BinaryOperator::getOverloadedOperator(Opc);
8673 if (Sc && OverOp != OO_None)
8674 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8675 RHS->getType(), Functions);
8676
8677 // Build the (potentially-overloaded, potentially-dependent)
8678 // binary operation.
8679 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8680}
8681
John McCall60d7b3a2010-08-24 06:29:42 +00008682ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008683 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008684 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008685 // We want to end up calling one of checkPseudoObjectAssignment
8686 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8687 // both expressions are overloadable or either is type-dependent),
8688 // or CreateBuiltinBinOp (in any other case). We also want to get
8689 // any placeholder types out of the way.
8690
John McCall3c3b7f92011-10-25 17:37:35 +00008691 // Handle pseudo-objects in the LHS.
8692 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8693 // Assignments with a pseudo-object l-value need special analysis.
8694 if (pty->getKind() == BuiltinType::PseudoObject &&
8695 BinaryOperator::isAssignmentOp(Opc))
8696 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8697
8698 // Don't resolve overloads if the other type is overloadable.
8699 if (pty->getKind() == BuiltinType::Overload) {
8700 // We can't actually test that if we still have a placeholder,
8701 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008702 // code below are valid when the LHS is an overload set. Note
8703 // that an overload set can be dependently-typed, but it never
8704 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008705 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8706 if (resolvedRHS.isInvalid()) return ExprError();
8707 RHSExpr = resolvedRHS.take();
8708
John McCallac516502011-10-28 01:04:34 +00008709 if (RHSExpr->isTypeDependent() ||
8710 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008711 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8712 }
8713
8714 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8715 if (LHS.isInvalid()) return ExprError();
8716 LHSExpr = LHS.take();
8717 }
8718
8719 // Handle pseudo-objects in the RHS.
8720 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8721 // An overload in the RHS can potentially be resolved by the type
8722 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008723 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8724 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8725 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8726
Eli Friedman87884912012-01-17 21:27:43 +00008727 if (LHSExpr->getType()->isOverloadableType())
8728 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8729
John McCall3c3b7f92011-10-25 17:37:35 +00008730 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008731 }
John McCall3c3b7f92011-10-25 17:37:35 +00008732
8733 // Don't resolve overloads if the other type is overloadable.
8734 if (pty->getKind() == BuiltinType::Overload &&
8735 LHSExpr->getType()->isOverloadableType())
8736 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8737
8738 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8739 if (!resolvedRHS.isUsable()) return ExprError();
8740 RHSExpr = resolvedRHS.take();
8741 }
8742
David Blaikie4e4d0842012-03-11 07:00:24 +00008743 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008744 // If either expression is type-dependent, always build an
8745 // overloaded op.
8746 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008748
John McCallac516502011-10-28 01:04:34 +00008749 // Otherwise, build an overloaded op if either expression has an
8750 // overloadable type.
8751 if (LHSExpr->getType()->isOverloadableType() ||
8752 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008753 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008754 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008755
Douglas Gregoreaebc752008-11-06 23:29:22 +00008756 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008757 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008758}
8759
John McCall60d7b3a2010-08-24 06:29:42 +00008760ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008761 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008762 Expr *InputExpr) {
8763 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008764 ExprValueKind VK = VK_RValue;
8765 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008766 QualType resultType;
8767 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008768 case UO_PreInc:
8769 case UO_PreDec:
8770 case UO_PostInc:
8771 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008772 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008773 Opc == UO_PreInc ||
8774 Opc == UO_PostInc,
8775 Opc == UO_PreInc ||
8776 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008777 break;
John McCall2de56d12010-08-25 11:45:40 +00008778 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008779 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008780 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008781 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008782 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008783 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008784 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008785 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008786 }
John McCall2de56d12010-08-25 11:45:40 +00008787 case UO_Plus:
8788 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008789 Input = UsualUnaryConversions(Input.take());
8790 if (Input.isInvalid()) return ExprError();
8791 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008792 if (resultType->isDependentType())
8793 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008794 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8795 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008796 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008797 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008798 resultType->isEnumeralType())
8799 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008800 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008801 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008802 resultType->isPointerType())
8803 break;
8804
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());
8807
John McCall2de56d12010-08-25 11:45:40 +00008808 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008809 Input = UsualUnaryConversions(Input.take());
8810 if (Input.isInvalid()) return ExprError();
8811 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008812 if (resultType->isDependentType())
8813 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008814 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8815 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8816 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008817 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008818 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008819 else if (resultType->hasIntegerRepresentation())
8820 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008821 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008823 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008824 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008825 break;
John Wiegley429bb272011-04-08 18:41:53 +00008826
John McCall2de56d12010-08-25 11:45:40 +00008827 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008828 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008829 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8830 if (Input.isInvalid()) return ExprError();
8831 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008832
8833 // Though we still have to promote half FP to float...
8834 if (resultType->isHalfType()) {
8835 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8836 resultType = Context.FloatTy;
8837 }
8838
Sebastian Redl28507842009-02-26 14:39:58 +00008839 if (resultType->isDependentType())
8840 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008841 if (resultType->isScalarType()) {
8842 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008843 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008844 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8845 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008846 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8847 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008848 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008849 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008850 // Vector logical not returns the signed variant of the operand type.
8851 resultType = GetSignedVectorType(resultType);
8852 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008853 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008854 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008855 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008856 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008857
Reid Spencer5f016e22007-07-11 17:01:13 +00008858 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008859 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008860 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008861 break;
John McCall2de56d12010-08-25 11:45:40 +00008862 case UO_Real:
8863 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008864 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008865 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8866 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008867 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008868 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8869 if (Input.get()->getValueKind() != VK_RValue &&
8870 Input.get()->getObjectKind() == OK_Ordinary)
8871 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008872 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008873 // In C, a volatile scalar is read by __imag. In C++, it is not.
8874 Input = DefaultLvalueConversion(Input.take());
8875 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008876 break;
John McCall2de56d12010-08-25 11:45:40 +00008877 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008878 resultType = Input.get()->getType();
8879 VK = Input.get()->getValueKind();
8880 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008881 break;
8882 }
John Wiegley429bb272011-04-08 18:41:53 +00008883 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008884 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008885
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008886 // Check for array bounds violations in the operand of the UnaryOperator,
8887 // except for the '*' and '&' operators that have to be handled specially
8888 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8889 // that are explicitly defined as valid by the standard).
8890 if (Opc != UO_AddrOf && Opc != UO_Deref)
8891 CheckArrayAccess(Input.get());
8892
John Wiegley429bb272011-04-08 18:41:53 +00008893 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008894 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008895}
8896
Douglas Gregord3d08532011-12-14 21:23:13 +00008897/// \brief Determine whether the given expression is a qualified member
8898/// access expression, of a form that could be turned into a pointer to member
8899/// with the address-of operator.
8900static bool isQualifiedMemberAccess(Expr *E) {
8901 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8902 if (!DRE->getQualifier())
8903 return false;
8904
8905 ValueDecl *VD = DRE->getDecl();
8906 if (!VD->isCXXClassMember())
8907 return false;
8908
8909 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8910 return true;
8911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8912 return Method->isInstance();
8913
8914 return false;
8915 }
8916
8917 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8918 if (!ULE->getQualifier())
8919 return false;
8920
8921 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8922 DEnd = ULE->decls_end();
8923 D != DEnd; ++D) {
8924 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8925 if (Method->isInstance())
8926 return true;
8927 } else {
8928 // Overload set does not contain methods.
8929 break;
8930 }
8931 }
8932
8933 return false;
8934 }
8935
8936 return false;
8937}
8938
John McCall60d7b3a2010-08-24 06:29:42 +00008939ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008940 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008941 // First things first: handle placeholders so that the
8942 // overloaded-operator check considers the right type.
8943 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8944 // Increment and decrement of pseudo-object references.
8945 if (pty->getKind() == BuiltinType::PseudoObject &&
8946 UnaryOperator::isIncrementDecrementOp(Opc))
8947 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8948
8949 // extension is always a builtin operator.
8950 if (Opc == UO_Extension)
8951 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8952
8953 // & gets special logic for several kinds of placeholder.
8954 // The builtin code knows what to do.
8955 if (Opc == UO_AddrOf &&
8956 (pty->getKind() == BuiltinType::Overload ||
8957 pty->getKind() == BuiltinType::UnknownAny ||
8958 pty->getKind() == BuiltinType::BoundMember))
8959 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8960
8961 // Anything else needs to be handled now.
8962 ExprResult Result = CheckPlaceholderExpr(Input);
8963 if (Result.isInvalid()) return ExprError();
8964 Input = Result.take();
8965 }
8966
David Blaikie4e4d0842012-03-11 07:00:24 +00008967 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008968 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8969 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008970 // Find all of the overloaded operators visible from this
8971 // point. We perform both an operator-name lookup from the local
8972 // scope and an argument-dependent lookup based on the types of
8973 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008974 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008975 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008976 if (S && OverOp != OO_None)
8977 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8978 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008979
John McCall9ae2f072010-08-23 23:25:46 +00008980 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008981 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008982
John McCall9ae2f072010-08-23 23:25:46 +00008983 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008984}
8985
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008986// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008987ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008988 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008989 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008990}
8991
Steve Naroff1b273c42007-09-16 14:56:35 +00008992/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008993ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008994 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008995 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008996 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008997 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008998 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008999}
9000
John McCallf85e1932011-06-15 23:02:42 +00009001/// Given the last statement in a statement-expression, check whether
9002/// the result is a producing expression (like a call to an
9003/// ns_returns_retained function) and, if so, rebuild it to hoist the
9004/// release out of the full-expression. Otherwise, return null.
9005/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00009006static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00009007 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00009008 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00009009 if (!cleanups) return 0;
9010
9011 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00009012 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00009013 return 0;
9014
9015 // Splice out the cast. This shouldn't modify any interesting
9016 // features of the statement.
9017 Expr *producer = cast->getSubExpr();
9018 assert(producer->getType() == cast->getType());
9019 assert(producer->getValueKind() == cast->getValueKind());
9020 cleanups->setSubExpr(producer);
9021 return cleanups;
9022}
9023
John McCall73f428c2012-04-04 01:27:53 +00009024void Sema::ActOnStartStmtExpr() {
9025 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9026}
9027
9028void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009029 // Note that function is also called by TreeTransform when leaving a
9030 // StmtExpr scope without rebuilding anything.
9031
John McCall73f428c2012-04-04 01:27:53 +00009032 DiscardCleanupsInEvaluationContext();
9033 PopExpressionEvaluationContext();
9034}
9035
John McCall60d7b3a2010-08-24 06:29:42 +00009036ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009037Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009038 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009039 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9040 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9041
John McCall73f428c2012-04-04 01:27:53 +00009042 if (hasAnyUnrecoverableErrorsInThisFunction())
9043 DiscardCleanupsInEvaluationContext();
9044 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9045 PopExpressionEvaluationContext();
9046
Douglas Gregordd8f5692010-03-10 04:54:39 +00009047 bool isFileScope
9048 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009049 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009050 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009051
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009052 // FIXME: there are a variety of strange constraints to enforce here, for
9053 // example, it is not possible to goto into a stmt expression apparently.
9054 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009055
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009056 // If there are sub stmts in the compound stmt, take the type of the last one
9057 // as the type of the stmtexpr.
9058 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009059 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009060 if (!Compound->body_empty()) {
9061 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009062 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009063 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009064 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9065 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009066 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009067 }
John McCallf85e1932011-06-15 23:02:42 +00009068
John Wiegley429bb272011-04-08 18:41:53 +00009069 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009070 // Do function/array conversion on the last expression, but not
9071 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009072 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9073 if (LastExpr.isInvalid())
9074 return ExprError();
9075 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009076
John Wiegley429bb272011-04-08 18:41:53 +00009077 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009078 // In ARC, if the final expression ends in a consume, splice
9079 // the consume out and bind it later. In the alternate case
9080 // (when dealing with a retainable type), the result
9081 // initialization will create a produce. In both cases the
9082 // result will be +1, and we'll need to balance that out with
9083 // a bind.
9084 if (Expr *rebuiltLastStmt
9085 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9086 LastExpr = rebuiltLastStmt;
9087 } else {
9088 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009089 InitializedEntity::InitializeResult(LPLoc,
9090 Ty,
9091 false),
9092 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009093 LastExpr);
9094 }
9095
John Wiegley429bb272011-04-08 18:41:53 +00009096 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009097 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009098 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009099 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009100 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009101 else
John Wiegley429bb272011-04-08 18:41:53 +00009102 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009103 StmtExprMayBindToTemp = true;
9104 }
9105 }
9106 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009108
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009109 // FIXME: Check that expression type is complete/non-abstract; statement
9110 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009111 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9112 if (StmtExprMayBindToTemp)
9113 return MaybeBindToTemporary(ResStmtExpr);
9114 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009115}
Steve Naroffd34e9152007-08-01 22:05:33 +00009116
John McCall60d7b3a2010-08-24 06:29:42 +00009117ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009118 TypeSourceInfo *TInfo,
9119 OffsetOfComponent *CompPtr,
9120 unsigned NumComponents,
9121 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009122 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009123 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009124 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009125
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009126 // We must have at least one component that refers to the type, and the first
9127 // one is known to be a field designator. Verify that the ArgTy represents
9128 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009129 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009130 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9131 << ArgTy << TypeRange);
9132
9133 // Type must be complete per C99 7.17p3 because a declaring a variable
9134 // with an incomplete type would be ill-formed.
9135 if (!Dependent
9136 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009137 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009138 return ExprError();
9139
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009140 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9141 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009142 // FIXME: This diagnostic isn't actually visible because the location is in
9143 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009144 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009145 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9146 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009147
9148 bool DidWarnAboutNonPOD = false;
9149 QualType CurrentType = ArgTy;
9150 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009151 SmallVector<OffsetOfNode, 4> Comps;
9152 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009153 for (unsigned i = 0; i != NumComponents; ++i) {
9154 const OffsetOfComponent &OC = CompPtr[i];
9155 if (OC.isBrackets) {
9156 // Offset of an array sub-field. TODO: Should we allow vector elements?
9157 if (!CurrentType->isDependentType()) {
9158 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9159 if(!AT)
9160 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9161 << CurrentType);
9162 CurrentType = AT->getElementType();
9163 } else
9164 CurrentType = Context.DependentTy;
9165
Richard Smithea011432011-10-17 23:29:39 +00009166 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9167 if (IdxRval.isInvalid())
9168 return ExprError();
9169 Expr *Idx = IdxRval.take();
9170
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009171 // The expression must be an integral expression.
9172 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009173 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9174 !Idx->getType()->isIntegerType())
9175 return ExprError(Diag(Idx->getLocStart(),
9176 diag::err_typecheck_subscript_not_integer)
9177 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009178
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009179 // Record this array index.
9180 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009181 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009182 continue;
9183 }
9184
9185 // Offset of a field.
9186 if (CurrentType->isDependentType()) {
9187 // We have the offset of a field, but we can't look into the dependent
9188 // type. Just record the identifier of the field.
9189 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9190 CurrentType = Context.DependentTy;
9191 continue;
9192 }
9193
9194 // We need to have a complete type to look into.
9195 if (RequireCompleteType(OC.LocStart, CurrentType,
9196 diag::err_offsetof_incomplete_type))
9197 return ExprError();
9198
9199 // Look for the designated field.
9200 const RecordType *RC = CurrentType->getAs<RecordType>();
9201 if (!RC)
9202 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9203 << CurrentType);
9204 RecordDecl *RD = RC->getDecl();
9205
9206 // C++ [lib.support.types]p5:
9207 // The macro offsetof accepts a restricted set of type arguments in this
9208 // International Standard. type shall be a POD structure or a POD union
9209 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009210 // C++11 [support.types]p4:
9211 // If type is not a standard-layout class (Clause 9), the results are
9212 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009213 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009214 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009215 unsigned DiagID =
Richard Smith80ad52f2013-01-02 11:42:31 +00009216 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009217 : diag::warn_offsetof_non_pod_type;
9218
9219 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009220 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009221 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009222 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9223 << CurrentType))
9224 DidWarnAboutNonPOD = true;
9225 }
9226
9227 // Look for the field.
9228 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9229 LookupQualifiedName(R, RD);
9230 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009231 IndirectFieldDecl *IndirectMemberDecl = 0;
9232 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009233 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009234 MemberDecl = IndirectMemberDecl->getAnonField();
9235 }
9236
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009237 if (!MemberDecl)
9238 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9239 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9240 OC.LocEnd));
9241
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009242 // C99 7.17p3:
9243 // (If the specified member is a bit-field, the behavior is undefined.)
9244 //
9245 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009246 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009247 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9248 << MemberDecl->getDeclName()
9249 << SourceRange(BuiltinLoc, RParenLoc);
9250 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9251 return ExprError();
9252 }
Eli Friedman19410a72010-08-05 10:11:36 +00009253
9254 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009255 if (IndirectMemberDecl)
9256 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009257
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009258 // If the member was found in a base class, introduce OffsetOfNodes for
9259 // the base class indirections.
9260 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9261 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009262 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009263 CXXBasePath &Path = Paths.front();
9264 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9265 B != BEnd; ++B)
9266 Comps.push_back(OffsetOfNode(B->Base));
9267 }
Eli Friedman19410a72010-08-05 10:11:36 +00009268
Francois Pichet87c2e122010-11-21 06:08:52 +00009269 if (IndirectMemberDecl) {
9270 for (IndirectFieldDecl::chain_iterator FI =
9271 IndirectMemberDecl->chain_begin(),
9272 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9273 assert(isa<FieldDecl>(*FI));
9274 Comps.push_back(OffsetOfNode(OC.LocStart,
9275 cast<FieldDecl>(*FI), OC.LocEnd));
9276 }
9277 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009278 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009279
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009280 CurrentType = MemberDecl->getType().getNonReferenceType();
9281 }
9282
9283 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009284 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009285}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009286
John McCall60d7b3a2010-08-24 06:29:42 +00009287ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009288 SourceLocation BuiltinLoc,
9289 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009290 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009291 OffsetOfComponent *CompPtr,
9292 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009293 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009294
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009295 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009296 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009297 if (ArgTy.isNull())
9298 return ExprError();
9299
Eli Friedman5a15dc12010-08-05 10:15:45 +00009300 if (!ArgTInfo)
9301 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9302
9303 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009304 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009305}
9306
9307
John McCall60d7b3a2010-08-24 06:29:42 +00009308ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009309 Expr *CondExpr,
9310 Expr *LHSExpr, Expr *RHSExpr,
9311 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009312 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9313
John McCallf89e55a2010-11-18 06:31:45 +00009314 ExprValueKind VK = VK_RValue;
9315 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009316 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009317 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009318 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009319 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009320 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009321 } else {
9322 // The conditional expression is required to be a constant expression.
9323 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009324 ExprResult CondICE
9325 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9326 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009327 if (CondICE.isInvalid())
9328 return ExprError();
9329 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009330
Sebastian Redl28507842009-02-26 14:39:58 +00009331 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009332 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9333
9334 resType = ActiveExpr->getType();
9335 ValueDependent = ActiveExpr->isValueDependent();
9336 VK = ActiveExpr->getValueKind();
9337 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009338 }
9339
Sebastian Redlf53597f2009-03-15 17:47:39 +00009340 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009341 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009342 resType->isDependentType(),
9343 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009344}
9345
Steve Naroff4eb206b2008-09-03 18:15:37 +00009346//===----------------------------------------------------------------------===//
9347// Clang Extensions.
9348//===----------------------------------------------------------------------===//
9349
9350/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009351void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009352 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009353 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009354 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009355 if (CurScope)
9356 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009357 else
9358 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009359
Eli Friedman84b007f2012-01-26 03:00:14 +00009360 getCurBlock()->HasImplicitReturnType = true;
9361
John McCall538773c2011-11-11 03:19:12 +00009362 // Enter a new evaluation context to insulate the block from any
9363 // cleanups from the enclosing full-expression.
9364 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009365}
9366
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009367void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9368 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009369 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009370 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009371 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009372
John McCallbf1a0282010-06-04 23:28:52 +00009373 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009374 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009375
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009376 // FIXME: We should allow unexpanded parameter packs here, but that would,
9377 // in turn, make the block expression contain unexpanded parameter packs.
9378 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9379 // Drop the parameters.
9380 FunctionProtoType::ExtProtoInfo EPI;
9381 EPI.HasTrailingReturn = false;
9382 EPI.TypeQuals |= DeclSpec::TQ_const;
9383 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9384 EPI);
9385 Sig = Context.getTrivialTypeSourceInfo(T);
9386 }
9387
John McCall711c52b2011-01-05 12:14:39 +00009388 // GetTypeForDeclarator always produces a function type for a block
9389 // literal signature. Furthermore, it is always a FunctionProtoType
9390 // unless the function was written with a typedef.
9391 assert(T->isFunctionType() &&
9392 "GetTypeForDeclarator made a non-function block signature");
9393
9394 // Look for an explicit signature in that function type.
9395 FunctionProtoTypeLoc ExplicitSignature;
9396
9397 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9398 if (isa<FunctionProtoTypeLoc>(tmp)) {
9399 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9400
9401 // Check whether that explicit signature was synthesized by
9402 // GetTypeForDeclarator. If so, don't save that as part of the
9403 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009404 if (ExplicitSignature.getLocalRangeBegin() ==
9405 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009406 // This would be much cheaper if we stored TypeLocs instead of
9407 // TypeSourceInfos.
9408 TypeLoc Result = ExplicitSignature.getResultLoc();
9409 unsigned Size = Result.getFullDataSize();
9410 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9411 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9412
9413 ExplicitSignature = FunctionProtoTypeLoc();
9414 }
John McCall82dc0092010-06-04 11:21:44 +00009415 }
Mike Stump1eb44332009-09-09 15:08:12 +00009416
John McCall711c52b2011-01-05 12:14:39 +00009417 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9418 CurBlock->FunctionType = T;
9419
9420 const FunctionType *Fn = T->getAs<FunctionType>();
9421 QualType RetTy = Fn->getResultType();
9422 bool isVariadic =
9423 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9424
John McCallc71a4912010-06-04 19:02:56 +00009425 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009426
John McCall82dc0092010-06-04 11:21:44 +00009427 // Don't allow returning a objc interface by value.
9428 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009429 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009430 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9431 return;
9432 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009433
John McCall82dc0092010-06-04 11:21:44 +00009434 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009435 // return type. TODO: what should we do with declarators like:
9436 // ^ * { ... }
9437 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009438 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009439 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009440 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009441 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009442 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009443
John McCall82dc0092010-06-04 11:21:44 +00009444 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009445 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009446 if (ExplicitSignature) {
9447 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9448 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009449 if (Param->getIdentifier() == 0 &&
9450 !Param->isImplicit() &&
9451 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009452 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009453 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009454 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009455 }
John McCall82dc0092010-06-04 11:21:44 +00009456
9457 // Fake up parameter variables if we have a typedef, like
9458 // ^ fntype { ... }
9459 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9460 for (FunctionProtoType::arg_type_iterator
9461 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9462 ParmVarDecl *Param =
9463 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009464 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009465 *I);
John McCallc71a4912010-06-04 19:02:56 +00009466 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009467 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009468 }
John McCall82dc0092010-06-04 11:21:44 +00009469
John McCallc71a4912010-06-04 19:02:56 +00009470 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009471 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009472 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009473 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9474 CurBlock->TheDecl->param_end(),
9475 /*CheckParameterNames=*/false);
9476 }
9477
John McCall82dc0092010-06-04 11:21:44 +00009478 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009479 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009480
John McCall82dc0092010-06-04 11:21:44 +00009481 // Put the parameter variables in scope. We can bail out immediately
9482 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009483 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009484 return;
9485
Steve Naroff090276f2008-10-10 01:28:17 +00009486 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009487 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9488 (*AI)->setOwningFunction(CurBlock->TheDecl);
9489
Steve Naroff090276f2008-10-10 01:28:17 +00009490 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009491 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009492 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009493
Steve Naroff090276f2008-10-10 01:28:17 +00009494 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009495 }
John McCall7a9813c2010-01-22 00:28:27 +00009496 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009497}
9498
9499/// ActOnBlockError - If there is an error parsing a block, this callback
9500/// is invoked to pop the information about the block from the action impl.
9501void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009502 // Leave the expression-evaluation context.
9503 DiscardCleanupsInEvaluationContext();
9504 PopExpressionEvaluationContext();
9505
Steve Naroff4eb206b2008-09-03 18:15:37 +00009506 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009507 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009508 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009509}
9510
9511/// ActOnBlockStmtExpr - This is called when the body of a block statement
9512/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009513ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009514 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009515 // If blocks are disabled, emit an error.
9516 if (!LangOpts.Blocks)
9517 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009518
John McCall538773c2011-11-11 03:19:12 +00009519 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009520 if (hasAnyUnrecoverableErrorsInThisFunction())
9521 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009522 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9523 PopExpressionEvaluationContext();
9524
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009525 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009526
9527 if (BSI->HasImplicitReturnType)
9528 deduceClosureReturnType(*BSI);
9529
Steve Naroff090276f2008-10-10 01:28:17 +00009530 PopDeclContext();
9531
Steve Naroff4eb206b2008-09-03 18:15:37 +00009532 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009533 if (!BSI->ReturnType.isNull())
9534 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009535
Mike Stump56925862009-07-28 22:04:01 +00009536 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009537 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009538
John McCall469a1eb2011-02-02 13:00:07 +00009539 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009540 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9541 SmallVector<BlockDecl::Capture, 4> Captures;
9542 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9543 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9544 if (Cap.isThisCapture())
9545 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009546 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009547 Cap.isNested(), Cap.getCopyExpr());
9548 Captures.push_back(NewCap);
9549 }
9550 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9551 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009552
John McCallc71a4912010-06-04 19:02:56 +00009553 // If the user wrote a function type in some form, try to use that.
9554 if (!BSI->FunctionType.isNull()) {
9555 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9556
9557 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9558 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9559
9560 // Turn protoless block types into nullary block types.
9561 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009562 FunctionProtoType::ExtProtoInfo EPI;
9563 EPI.ExtInfo = Ext;
9564 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009565
9566 // Otherwise, if we don't need to change anything about the function type,
9567 // preserve its sugar structure.
9568 } else if (FTy->getResultType() == RetTy &&
9569 (!NoReturn || FTy->getNoReturnAttr())) {
9570 BlockTy = BSI->FunctionType;
9571
9572 // Otherwise, make the minimal modifications to the function type.
9573 } else {
9574 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009575 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9576 EPI.TypeQuals = 0; // FIXME: silently?
9577 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009578 BlockTy = Context.getFunctionType(RetTy,
9579 FPT->arg_type_begin(),
9580 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009581 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009582 }
9583
9584 // If we don't have a function type, just build one from nothing.
9585 } else {
John McCalle23cf432010-12-14 08:05:40 +00009586 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009587 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009588 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009589 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009590
John McCallc71a4912010-06-04 19:02:56 +00009591 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9592 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009593 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009594
Chris Lattner17a78302009-04-19 05:28:12 +00009595 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009596 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009597 !hasAnyUnrecoverableErrorsInThisFunction() &&
9598 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009599 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009600
Chris Lattnere476bdc2011-02-17 23:58:47 +00009601 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009602
Jordan Rose7dd900e2012-07-02 21:19:23 +00009603 // Try to apply the named return value optimization. We have to check again
9604 // if we can do this, though, because blocks keep return statements around
9605 // to deduce an implicit return type.
9606 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9607 !BSI->TheDecl->isDependentContext())
9608 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009609
Benjamin Kramerd2486192011-07-12 14:11:05 +00009610 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9611 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009612 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009613
John McCall80ee6e82011-11-10 05:35:25 +00009614 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009615 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009616 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009617 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009618 ExprCleanupObjects.push_back(Result->getBlockDecl());
9619 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009620
9621 // It also gets a branch-protected scope if any of the captured
9622 // variables needs destruction.
9623 for (BlockDecl::capture_const_iterator
9624 ci = Result->getBlockDecl()->capture_begin(),
9625 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9626 const VarDecl *var = ci->getVariable();
9627 if (var->getType().isDestructedType() != QualType::DK_none) {
9628 getCurFunction()->setHasBranchProtectedScope();
9629 break;
9630 }
9631 }
John McCall80ee6e82011-11-10 05:35:25 +00009632 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009633
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009634 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009635}
9636
John McCall60d7b3a2010-08-24 06:29:42 +00009637ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009638 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009639 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009640 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009641 GetTypeFromParser(Ty, &TInfo);
9642 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009643}
9644
John McCall60d7b3a2010-08-24 06:29:42 +00009645ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009646 Expr *E, TypeSourceInfo *TInfo,
9647 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009648 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009649
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009650 // Get the va_list type
9651 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009652 if (VaListType->isArrayType()) {
9653 // Deal with implicit array decay; for example, on x86-64,
9654 // va_list is an array, but it's supposed to decay to
9655 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009656 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009657 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009658 ExprResult Result = UsualUnaryConversions(E);
9659 if (Result.isInvalid())
9660 return ExprError();
9661 E = Result.take();
Logan Chienb687f3b2012-10-20 06:11:33 +00009662 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9663 // If va_list is a record type and we are compiling in C++ mode,
9664 // check the argument using reference binding.
9665 InitializedEntity Entity
9666 = InitializedEntity::InitializeParameter(Context,
9667 Context.getLValueReferenceType(VaListType), false);
9668 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9669 if (Init.isInvalid())
9670 return ExprError();
9671 E = Init.takeAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009672 } else {
9673 // Otherwise, the va_list argument must be an l-value because
9674 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009675 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009676 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009677 return ExprError();
9678 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009679
Douglas Gregordd027302009-05-19 23:10:31 +00009680 if (!E->isTypeDependent() &&
9681 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009682 return ExprError(Diag(E->getLocStart(),
9683 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009684 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009685 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009686
David Majnemer0adde122011-06-14 05:17:32 +00009687 if (!TInfo->getType()->isDependentType()) {
9688 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009689 diag::err_second_parameter_to_va_arg_incomplete,
9690 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009691 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009692
David Majnemer0adde122011-06-14 05:17:32 +00009693 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009694 TInfo->getType(),
9695 diag::err_second_parameter_to_va_arg_abstract,
9696 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009697 return ExprError();
9698
Douglas Gregor4eb75222011-07-30 06:45:27 +00009699 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009700 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009701 TInfo->getType()->isObjCLifetimeType()
9702 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9703 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009704 << TInfo->getType()
9705 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009706 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009707
9708 // Check for va_arg where arguments of the given type will be promoted
9709 // (i.e. this va_arg is guaranteed to have undefined behavior).
9710 QualType PromoteType;
9711 if (TInfo->getType()->isPromotableIntegerType()) {
9712 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9713 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9714 PromoteType = QualType();
9715 }
9716 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9717 PromoteType = Context.DoubleTy;
9718 if (!PromoteType.isNull())
Ted Kremenekcbb99ef2013-01-08 01:50:40 +00009719 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9720 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9721 << TInfo->getType()
9722 << PromoteType
9723 << TInfo->getTypeLoc().getSourceRange());
David Majnemer0adde122011-06-14 05:17:32 +00009724 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009725
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009726 QualType T = TInfo->getType().getNonLValueExprType(Context);
9727 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009728}
9729
John McCall60d7b3a2010-08-24 06:29:42 +00009730ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009731 // The type of __null will be int or long, depending on the size of
9732 // pointers on the target.
9733 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009734 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9735 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009736 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009737 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009738 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009739 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009740 Ty = Context.LongLongTy;
9741 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009742 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009743 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009744
Sebastian Redlf53597f2009-03-15 17:47:39 +00009745 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009746}
9747
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009748static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009749 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009750 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009751 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009752
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009753 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9754 if (!PT)
9755 return;
9756
9757 // Check if the destination is of type 'id'.
9758 if (!PT->isObjCIdType()) {
9759 // Check if the destination is the 'NSString' interface.
9760 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9761 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9762 return;
9763 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009764
John McCall4b9c2d22011-11-06 09:01:30 +00009765 // Ignore any parens, implicit casts (should only be
9766 // array-to-pointer decays), and not-so-opaque values. The last is
9767 // important for making this trigger for property assignments.
9768 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9769 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9770 if (OV->getSourceExpr())
9771 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9772
9773 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009774 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009775 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009776
Douglas Gregor849b2432010-03-31 17:46:05 +00009777 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009778}
9779
Chris Lattner5cf216b2008-01-04 18:04:52 +00009780bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9781 SourceLocation Loc,
9782 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009783 Expr *SrcExpr, AssignmentAction Action,
9784 bool *Complained) {
9785 if (Complained)
9786 *Complained = false;
9787
Chris Lattner5cf216b2008-01-04 18:04:52 +00009788 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009789 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009790 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009791 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009792 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009793 ConversionFixItGenerator ConvHints;
9794 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009795 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009796
Chris Lattner5cf216b2008-01-04 18:04:52 +00009797 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009798 case Compatible:
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00009799 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9800 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009801
Chris Lattnerb7b61152008-01-04 18:22:42 +00009802 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009803 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009804 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9805 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009806 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009807 case IntToPointer:
9808 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009809 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9810 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009811 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009812 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009813 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009814 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009815 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9816 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009817 if (Hint.isNull() && !CheckInferredResultType) {
9818 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9819 }
9820 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009821 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009822 case IncompatiblePointerSign:
9823 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9824 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009825 case FunctionVoidPointer:
9826 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9827 break;
John McCall86c05f32011-02-01 00:10:29 +00009828 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009829 // Perform array-to-pointer decay if necessary.
9830 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9831
John McCall86c05f32011-02-01 00:10:29 +00009832 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9833 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9834 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9835 DiagKind = diag::err_typecheck_incompatible_address_space;
9836 break;
John McCallf85e1932011-06-15 23:02:42 +00009837
9838
9839 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009840 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009841 break;
John McCall86c05f32011-02-01 00:10:29 +00009842 }
9843
9844 llvm_unreachable("unknown error case for discarding qualifiers!");
9845 // fallthrough
9846 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009847 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009848 // If the qualifiers lost were because we were applying the
9849 // (deprecated) C++ conversion from a string literal to a char*
9850 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9851 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009852 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009853 // bit of refactoring (so that the second argument is an
9854 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009855 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009856 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009857 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009858 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9859 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009860 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9861 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009862 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009863 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009864 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009865 case IntToBlockPointer:
9866 DiagKind = diag::err_int_to_block_pointer;
9867 break;
9868 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009869 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009870 break;
Steve Naroff39579072008-10-14 22:18:38 +00009871 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009872 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009873 // it can give a more specific diagnostic.
9874 DiagKind = diag::warn_incompatible_qualified_id;
9875 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009876 case IncompatibleVectors:
9877 DiagKind = diag::warn_incompatible_vectors;
9878 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009879 case IncompatibleObjCWeakRef:
9880 DiagKind = diag::err_arc_weak_unavailable_assign;
9881 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009882 case Incompatible:
9883 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009884 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9885 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009886 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009887 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009888 break;
9889 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009890
Douglas Gregord4eea832010-04-09 00:35:39 +00009891 QualType FirstType, SecondType;
9892 switch (Action) {
9893 case AA_Assigning:
9894 case AA_Initializing:
9895 // The destination type comes first.
9896 FirstType = DstType;
9897 SecondType = SrcType;
9898 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009899
Douglas Gregord4eea832010-04-09 00:35:39 +00009900 case AA_Returning:
9901 case AA_Passing:
9902 case AA_Converting:
9903 case AA_Sending:
9904 case AA_Casting:
9905 // The source type comes first.
9906 FirstType = SrcType;
9907 SecondType = DstType;
9908 break;
9909 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009910
Anna Zaks67221552011-07-28 19:51:27 +00009911 PartialDiagnostic FDiag = PDiag(DiagKind);
9912 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9913
9914 // If we can fix the conversion, suggest the FixIts.
9915 assert(ConvHints.isNull() || Hint.isNull());
9916 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009917 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9918 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009919 FDiag << *HI;
9920 } else {
9921 FDiag << Hint;
9922 }
9923 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9924
Richard Trieu6efd4c52011-11-23 22:32:32 +00009925 if (MayHaveFunctionDiff)
9926 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9927
Anna Zaks67221552011-07-28 19:51:27 +00009928 Diag(Loc, FDiag);
9929
Richard Trieu6efd4c52011-11-23 22:32:32 +00009930 if (SecondType == Context.OverloadTy)
9931 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9932 FirstType);
9933
Douglas Gregor926df6c2011-06-11 01:09:30 +00009934 if (CheckInferredResultType)
9935 EmitRelatedResultTypeNote(SrcExpr);
9936
Douglas Gregora41a8c52010-04-22 00:20:18 +00009937 if (Complained)
9938 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009939 return isInvalid;
9940}
Anders Carlssone21555e2008-11-30 19:50:32 +00009941
Richard Smith282e7e62012-02-04 09:53:13 +00009942ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9943 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009944 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9945 public:
9946 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9947 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9948 }
9949 } Diagnoser;
9950
9951 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9952}
9953
9954ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9955 llvm::APSInt *Result,
9956 unsigned DiagID,
9957 bool AllowFold) {
9958 class IDDiagnoser : public VerifyICEDiagnoser {
9959 unsigned DiagID;
9960
9961 public:
9962 IDDiagnoser(unsigned DiagID)
9963 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9964
9965 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9966 S.Diag(Loc, DiagID) << SR;
9967 }
9968 } Diagnoser(DiagID);
9969
9970 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9971}
9972
9973void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9974 SourceRange SR) {
9975 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009976}
9977
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009978ExprResult
9979Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009980 VerifyICEDiagnoser &Diagnoser,
9981 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009982 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009983
Richard Smith80ad52f2013-01-02 11:42:31 +00009984 if (getLangOpts().CPlusPlus11) {
Richard Smith282e7e62012-02-04 09:53:13 +00009985 // C++11 [expr.const]p5:
9986 // If an expression of literal class type is used in a context where an
9987 // integral constant expression is required, then that class type shall
9988 // have a single non-explicit conversion function to an integral or
9989 // unscoped enumeration type
9990 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009991 if (!Diagnoser.Suppress) {
9992 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9993 public:
9994 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9995
9996 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9997 QualType T) {
9998 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9999 }
10000
10001 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10002 SourceLocation Loc,
10003 QualType T) {
10004 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10005 }
10006
10007 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10008 SourceLocation Loc,
10009 QualType T,
10010 QualType ConvTy) {
10011 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10012 }
10013
10014 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10015 CXXConversionDecl *Conv,
10016 QualType ConvTy) {
10017 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10018 << ConvTy->isEnumeralType() << ConvTy;
10019 }
10020
10021 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10022 QualType T) {
10023 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10024 }
10025
10026 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10027 CXXConversionDecl *Conv,
10028 QualType ConvTy) {
10029 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10030 << ConvTy->isEnumeralType() << ConvTy;
10031 }
10032
10033 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10034 SourceLocation Loc,
10035 QualType T,
10036 QualType ConvTy) {
10037 return DiagnosticBuilder::getEmpty();
10038 }
10039 } ConvertDiagnoser;
10040
10041 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10042 ConvertDiagnoser,
10043 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010044 } else {
10045 // The caller wants to silently enquire whether this is an ICE. Don't
10046 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010047 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10048 public:
10049 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10050
10051 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10052 QualType T) {
10053 return DiagnosticBuilder::getEmpty();
10054 }
10055
10056 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10057 SourceLocation Loc,
10058 QualType T) {
10059 return DiagnosticBuilder::getEmpty();
10060 }
10061
10062 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10063 SourceLocation Loc,
10064 QualType T,
10065 QualType ConvTy) {
10066 return DiagnosticBuilder::getEmpty();
10067 }
10068
10069 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10070 CXXConversionDecl *Conv,
10071 QualType ConvTy) {
10072 return DiagnosticBuilder::getEmpty();
10073 }
10074
10075 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10076 QualType T) {
10077 return DiagnosticBuilder::getEmpty();
10078 }
10079
10080 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10081 CXXConversionDecl *Conv,
10082 QualType ConvTy) {
10083 return DiagnosticBuilder::getEmpty();
10084 }
10085
10086 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10087 SourceLocation Loc,
10088 QualType T,
10089 QualType ConvTy) {
10090 return DiagnosticBuilder::getEmpty();
10091 }
10092 } ConvertDiagnoser;
10093
10094 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10095 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010096 }
10097 if (Converted.isInvalid())
10098 return Converted;
10099 E = Converted.take();
10100 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10101 return ExprError();
10102 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10103 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010104 if (!Diagnoser.Suppress)
10105 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010106 return ExprError();
10107 }
10108
Richard Smithdaaefc52011-12-14 23:32:26 +000010109 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10110 // in the non-ICE case.
Richard Smith80ad52f2013-01-02 11:42:31 +000010111 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010112 if (Result)
10113 *Result = E->EvaluateKnownConstInt(Context);
10114 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010115 }
10116
Anders Carlssone21555e2008-11-30 19:50:32 +000010117 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010118 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10119 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010120
Richard Smithdaaefc52011-12-14 23:32:26 +000010121 // Try to evaluate the expression, and produce diagnostics explaining why it's
10122 // not a constant expression as a side-effect.
10123 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10124 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10125
10126 // In C++11, we can rely on diagnostics being produced for any expression
10127 // which is not a constant expression. If no diagnostics were produced, then
10128 // this is a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +000010129 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010130 if (Result)
10131 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010132 return Owned(E);
10133 }
10134
10135 // If our only note is the usual "invalid subexpression" note, just point
10136 // the caret at its location rather than producing an essentially
10137 // redundant note.
10138 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10139 diag::note_invalid_subexpr_in_const_expr) {
10140 DiagLoc = Notes[0].first;
10141 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010142 }
10143
10144 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010145 if (!Diagnoser.Suppress) {
10146 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010147 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10148 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010149 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010150
Richard Smith282e7e62012-02-04 09:53:13 +000010151 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010152 }
10153
Douglas Gregorab41fe92012-05-04 22:38:52 +000010154 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010155 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10156 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010157
Anders Carlssone21555e2008-11-30 19:50:32 +000010158 if (Result)
10159 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010160 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010161}
Douglas Gregore0762c92009-06-19 23:52:42 +000010162
Eli Friedmanef331b72012-01-20 01:26:23 +000010163namespace {
10164 // Handle the case where we conclude a expression which we speculatively
10165 // considered to be unevaluated is actually evaluated.
10166 class TransformToPE : public TreeTransform<TransformToPE> {
10167 typedef TreeTransform<TransformToPE> BaseTransform;
10168
10169 public:
10170 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10171
10172 // Make sure we redo semantic analysis
10173 bool AlwaysRebuild() { return true; }
10174
Eli Friedman56ff2832012-02-06 23:29:57 +000010175 // Make sure we handle LabelStmts correctly.
10176 // FIXME: This does the right thing, but maybe we need a more general
10177 // fix to TreeTransform?
10178 StmtResult TransformLabelStmt(LabelStmt *S) {
10179 S->getDecl()->setStmt(0);
10180 return BaseTransform::TransformLabelStmt(S);
10181 }
10182
Eli Friedmanef331b72012-01-20 01:26:23 +000010183 // We need to special-case DeclRefExprs referring to FieldDecls which
10184 // are not part of a member pointer formation; normal TreeTransforming
10185 // doesn't catch this case because of the way we represent them in the AST.
10186 // FIXME: This is a bit ugly; is it really the best way to handle this
10187 // case?
10188 //
10189 // Error on DeclRefExprs referring to FieldDecls.
10190 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10191 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010192 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010193 return SemaRef.Diag(E->getLocation(),
10194 diag::err_invalid_non_static_member_use)
10195 << E->getDecl() << E->getSourceRange();
10196
10197 return BaseTransform::TransformDeclRefExpr(E);
10198 }
10199
10200 // Exception: filter out member pointer formation
10201 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10202 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10203 return E;
10204
10205 return BaseTransform::TransformUnaryOperator(E);
10206 }
10207
Douglas Gregore2c59132012-02-09 08:14:43 +000010208 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10209 // Lambdas never need to be transformed.
10210 return E;
10211 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010212 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010213}
10214
Benjamin Krameraccaf192012-11-14 15:08:31 +000010215ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010216 assert(ExprEvalContexts.back().Context == Unevaluated &&
10217 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010218 ExprEvalContexts.back().Context =
10219 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10220 if (ExprEvalContexts.back().Context == Unevaluated)
10221 return E;
10222 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010223}
10224
Douglas Gregor2afce722009-11-26 00:44:06 +000010225void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010226Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010227 Decl *LambdaContextDecl,
10228 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010229 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010230 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010231 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010232 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010233 LambdaContextDecl,
10234 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010235 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010236 if (!MaybeODRUseExprs.empty())
10237 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010238}
10239
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010240void
10241Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10242 ReuseLambdaContextDecl_t,
10243 bool IsDecltype) {
10244 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10245 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10246}
10247
Richard Trieu67e29332011-08-02 04:35:43 +000010248void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010249 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010250
Douglas Gregore2c59132012-02-09 08:14:43 +000010251 if (!Rec.Lambdas.empty()) {
10252 if (Rec.Context == Unevaluated) {
10253 // C++11 [expr.prim.lambda]p2:
10254 // A lambda-expression shall not appear in an unevaluated operand
10255 // (Clause 5).
10256 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10257 Diag(Rec.Lambdas[I]->getLocStart(),
10258 diag::err_lambda_unevaluated_operand);
10259 } else {
10260 // Mark the capture expressions odr-used. This was deferred
10261 // during lambda expression creation.
10262 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10263 LambdaExpr *Lambda = Rec.Lambdas[I];
10264 for (LambdaExpr::capture_init_iterator
10265 C = Lambda->capture_init_begin(),
10266 CEnd = Lambda->capture_init_end();
10267 C != CEnd; ++C) {
10268 MarkDeclarationsReferencedInExpr(*C);
10269 }
10270 }
10271 }
10272 }
10273
Douglas Gregor2afce722009-11-26 00:44:06 +000010274 // When are coming out of an unevaluated context, clear out any
10275 // temporaries that we may have created as part of the evaluation of
10276 // the expression in that context: they aren't relevant because they
10277 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010278 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010279 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10280 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010281 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010282 CleanupVarDeclMarking();
10283 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010284 // Otherwise, merge the contexts together.
10285 } else {
10286 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010287 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10288 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010289 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010290
10291 // Pop the current expression evaluation context off the stack.
10292 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010293}
Douglas Gregore0762c92009-06-19 23:52:42 +000010294
John McCallf85e1932011-06-15 23:02:42 +000010295void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010296 ExprCleanupObjects.erase(
10297 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10298 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010299 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010300 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010301}
10302
Eli Friedman71b8fb52012-01-21 01:01:51 +000010303ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10304 if (!E->getType()->isVariablyModifiedType())
10305 return E;
Benjamin Krameraccaf192012-11-14 15:08:31 +000010306 return TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +000010307}
10308
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010309static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010310 // Do not mark anything as "used" within a dependent context; wait for
10311 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010312 if (SemaRef.CurContext->isDependentContext())
10313 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010314
Eli Friedman5f2987c2012-02-02 03:46:19 +000010315 switch (SemaRef.ExprEvalContexts.back().Context) {
10316 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010317 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010318 // (Depending on how you read the standard, we actually do need to do
10319 // something here for null pointer constants, but the standard's
10320 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010321 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010322
Eli Friedman5f2987c2012-02-02 03:46:19 +000010323 case Sema::ConstantEvaluated:
10324 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010325 // We are in a potentially evaluated expression (or a constant-expression
10326 // in C++03); we need to do implicit template instantiation, implicitly
10327 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010328 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010329
Eli Friedman5f2987c2012-02-02 03:46:19 +000010330 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010331 // Referenced declarations will only be used if the construct in the
10332 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010333 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010334 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010335 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010336}
10337
10338/// \brief Mark a function referenced, and check whether it is odr-used
10339/// (C++ [basic.def.odr]p2, C99 6.9p3)
10340void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10341 assert(Func && "No function?");
10342
10343 Func->setReferenced();
10344
Richard Smithce2661f2012-11-07 01:14:25 +000010345 // C++11 [basic.def.odr]p3:
10346 // A function whose name appears as a potentially-evaluated expression is
10347 // odr-used if it is the unique lookup result or the selected member of a
10348 // set of overloaded functions [...].
10349 //
10350 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10351 // can just check that here. Skip the rest of this function if we've already
10352 // marked the function as used.
10353 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10354 // C++11 [temp.inst]p3:
10355 // Unless a function template specialization has been explicitly
10356 // instantiated or explicitly specialized, the function template
10357 // specialization is implicitly instantiated when the specialization is
10358 // referenced in a context that requires a function definition to exist.
10359 //
10360 // We consider constexpr function templates to be referenced in a context
10361 // that requires a definition to exist whenever they are referenced.
10362 //
10363 // FIXME: This instantiates constexpr functions too frequently. If this is
10364 // really an unevaluated context (and we're not just in the definition of a
10365 // function template or overload resolution or other cases which we
10366 // incorrectly consider to be unevaluated contexts), and we're not in a
10367 // subexpression which we actually need to evaluate (for instance, a
10368 // template argument, array bound or an expression in a braced-init-list),
10369 // we are not permitted to instantiate this constexpr function definition.
10370 //
10371 // FIXME: This also implicitly defines special members too frequently. They
10372 // are only supposed to be implicitly defined if they are odr-used, but they
10373 // are not odr-used from constant expressions in unevaluated contexts.
10374 // However, they cannot be referenced if they are deleted, and they are
10375 // deleted whenever the implicit definition of the special member would
10376 // fail.
10377 if (!Func->isConstexpr() || Func->getBody())
10378 return;
10379 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10380 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10381 return;
10382 }
Mike Stump1eb44332009-09-09 15:08:12 +000010383
Douglas Gregore0762c92009-06-19 23:52:42 +000010384 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010385 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010386 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010387 if (Constructor->isDefaultConstructor()) {
10388 if (Constructor->isTrivial())
10389 return;
10390 if (!Constructor->isUsed(false))
10391 DefineImplicitDefaultConstructor(Loc, Constructor);
10392 } else if (Constructor->isCopyConstructor()) {
10393 if (!Constructor->isUsed(false))
10394 DefineImplicitCopyConstructor(Loc, Constructor);
10395 } else if (Constructor->isMoveConstructor()) {
10396 if (!Constructor->isUsed(false))
10397 DefineImplicitMoveConstructor(Loc, Constructor);
10398 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010399 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010400
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010401 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010402 } else if (CXXDestructorDecl *Destructor =
10403 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010404 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10405 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010406 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010407 if (Destructor->isVirtual())
10408 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010409 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010410 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10411 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010412 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010413 if (!MethodDecl->isUsed(false)) {
10414 if (MethodDecl->isCopyAssignmentOperator())
10415 DefineImplicitCopyAssignment(Loc, MethodDecl);
10416 else
10417 DefineImplicitMoveAssignment(Loc, MethodDecl);
10418 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010419 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10420 MethodDecl->getParent()->isLambda()) {
10421 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10422 if (Conversion->isLambdaToBlockPointerConversion())
10423 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10424 else
10425 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010426 } else if (MethodDecl->isVirtual())
10427 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010428 }
John McCall15e310a2011-02-19 02:53:41 +000010429
Eli Friedman5f2987c2012-02-02 03:46:19 +000010430 // Recursive functions should be marked when used from another function.
10431 // FIXME: Is this really right?
10432 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010433
Richard Smithb9d0b762012-07-27 04:22:15 +000010434 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010435 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010436 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010437 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10438 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010439
Eli Friedman5f2987c2012-02-02 03:46:19 +000010440 // Implicit instantiation of function templates and member functions of
10441 // class templates.
10442 if (Func->isImplicitlyInstantiable()) {
10443 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010444 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010445 if (FunctionTemplateSpecializationInfo *SpecInfo
10446 = Func->getTemplateSpecializationInfo()) {
10447 if (SpecInfo->getPointOfInstantiation().isInvalid())
10448 SpecInfo->setPointOfInstantiation(Loc);
10449 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010450 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010451 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010452 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10453 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010454 } else if (MemberSpecializationInfo *MSInfo
10455 = Func->getMemberSpecializationInfo()) {
10456 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010457 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010458 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010459 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010460 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010461 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10462 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010463 }
Mike Stump1eb44332009-09-09 15:08:12 +000010464
Richard Smith57b9c4e2012-02-14 22:25:15 +000010465 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010466 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10467 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010468 PendingLocalImplicitInstantiations.push_back(
10469 std::make_pair(Func, PointOfInstantiation));
10470 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010471 // Do not defer instantiations of constexpr functions, to avoid the
10472 // expression evaluator needing to call back into Sema if it sees a
10473 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010474 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010475 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010476 PendingInstantiations.push_back(std::make_pair(Func,
10477 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010478 // Notify the consumer that a function was implicitly instantiated.
10479 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10480 }
John McCall15e310a2011-02-19 02:53:41 +000010481 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010482 } else {
10483 // Walk redefinitions, as some of them may be instantiable.
10484 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10485 e(Func->redecls_end()); i != e; ++i) {
10486 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10487 MarkFunctionReferenced(Loc, *i);
10488 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010489 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010490
10491 // Keep track of used but undefined functions.
10492 if (!Func->isPure() && !Func->hasBody() &&
10493 Func->getLinkage() != ExternalLinkage) {
10494 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10495 if (old.isInvalid()) old = Loc;
10496 }
10497
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010498 // Normally the must current decl is marked used while processing the use and
10499 // any subsequent decls are marked used by decl merging. This fails with
10500 // template instantiation since marking can happen at the end of the file
10501 // and, because of the two phase lookup, this function is called with at
10502 // decl in the middle of a decl chain. We loop to maintain the invariant
10503 // that once a decl is used, all decls after it are also used.
Rafael Espindolaa6d20202013-01-08 19:58:34 +000010504 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010505 F->setUsed(true);
10506 if (F == Func)
10507 break;
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010508 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010509}
10510
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010511static void
10512diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10513 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010514 DeclContext *VarDC = var->getDeclContext();
10515
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010516 // If the parameter still belongs to the translation unit, then
10517 // we're actually just using one parameter in the declaration of
10518 // the next.
10519 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010520 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010521 return;
10522
Eli Friedman0a294222012-02-07 00:15:00 +000010523 // For C code, don't diagnose about capture if we're not actually in code
10524 // right now; it's impossible to write a non-constant expression outside of
10525 // function context, so we'll get other (more useful) diagnostics later.
10526 //
10527 // For C++, things get a bit more nasty... it would be nice to suppress this
10528 // diagnostic for certain cases like using a local variable in an array bound
10529 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010530 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010531 return;
10532
Eli Friedman0a294222012-02-07 00:15:00 +000010533 if (isa<CXXMethodDecl>(VarDC) &&
10534 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10535 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10536 << var->getIdentifier();
10537 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10538 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10539 << var->getIdentifier() << fn->getDeclName();
10540 } else if (isa<BlockDecl>(VarDC)) {
10541 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10542 << var->getIdentifier();
10543 } else {
10544 // FIXME: Is there any other context where a local variable can be
10545 // declared?
10546 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10547 << var->getIdentifier();
10548 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010549
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010550 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10551 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010552
10553 // FIXME: Add additional diagnostic info about class etc. which prevents
10554 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010555}
10556
Douglas Gregorf8af9822012-02-12 18:42:33 +000010557/// \brief Capture the given variable in the given lambda expression.
10558static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010559 VarDecl *Var, QualType FieldType,
10560 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010561 SourceLocation Loc,
10562 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010563 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010564
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010565 // Build the non-static data member.
10566 FieldDecl *Field
10567 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10568 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010569 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010570 Field->setImplicit(true);
10571 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010572 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010573
10574 // C++11 [expr.prim.lambda]p21:
10575 // When the lambda-expression is evaluated, the entities that
10576 // are captured by copy are used to direct-initialize each
10577 // corresponding non-static data member of the resulting closure
10578 // object. (For array members, the array elements are
10579 // direct-initialized in increasing subscript order.) These
10580 // initializations are performed in the (unspecified) order in
10581 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010582
Douglas Gregore2c59132012-02-09 08:14:43 +000010583 // Introduce a new evaluation context for the initialization, so
10584 // that temporaries introduced as part of the capture are retained
10585 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010586 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10587
Douglas Gregor73d90922012-02-10 09:26:04 +000010588 // C++ [expr.prim.labda]p12:
10589 // An entity captured by a lambda-expression is odr-used (3.2) in
10590 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010591 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10592 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010593 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010594 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010595
10596 // When the field has array type, create index variables for each
10597 // dimension of the array. We use these index variables to subscript
10598 // the source array, and other clients (e.g., CodeGen) will perform
10599 // the necessary iteration with these index variables.
10600 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010601 QualType BaseType = FieldType;
10602 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010603 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010604 while (const ConstantArrayType *Array
10605 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010606 // Create the iteration variable for this array index.
10607 IdentifierInfo *IterationVarName = 0;
10608 {
10609 SmallString<8> Str;
10610 llvm::raw_svector_ostream OS(Str);
10611 OS << "__i" << IndexVariables.size();
10612 IterationVarName = &S.Context.Idents.get(OS.str());
10613 }
10614 VarDecl *IterationVar
10615 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10616 IterationVarName, SizeType,
10617 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10618 SC_None, SC_None);
10619 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010620 LSI->ArrayIndexVars.push_back(IterationVar);
10621
Douglas Gregor18fe0842012-02-09 02:45:47 +000010622 // Create a reference to the iteration variable.
10623 ExprResult IterationVarRef
10624 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10625 assert(!IterationVarRef.isInvalid() &&
10626 "Reference to invented variable cannot fail!");
10627 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10628 assert(!IterationVarRef.isInvalid() &&
10629 "Conversion of invented variable cannot fail!");
10630
10631 // Subscript the array with this iteration variable.
10632 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10633 Ref, Loc, IterationVarRef.take(), Loc);
10634 if (Subscript.isInvalid()) {
10635 S.CleanupVarDeclMarking();
10636 S.DiscardCleanupsInEvaluationContext();
10637 S.PopExpressionEvaluationContext();
10638 return ExprError();
10639 }
10640
10641 Ref = Subscript.take();
10642 BaseType = Array->getElementType();
10643 }
10644
10645 // Construct the entity that we will be initializing. For an array, this
10646 // will be first element in the array, which may require several levels
10647 // of array-subscript entities.
10648 SmallVector<InitializedEntity, 4> Entities;
10649 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010650 Entities.push_back(
10651 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010652 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10653 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10654 0,
10655 Entities.back()));
10656
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010657 InitializationKind InitKind
10658 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010659 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010660 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010661 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010662 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010663
10664 // If this initialization requires any cleanups (e.g., due to a
10665 // default argument to a copy constructor), note that for the
10666 // lambda.
10667 if (S.ExprNeedsCleanups)
10668 LSI->ExprNeedsCleanups = true;
10669
10670 // Exit the expression evaluation context used for the capture.
10671 S.CleanupVarDeclMarking();
10672 S.DiscardCleanupsInEvaluationContext();
10673 S.PopExpressionEvaluationContext();
10674 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010675}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010676
Douglas Gregor999713e2012-02-18 09:37:24 +000010677bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10678 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10679 bool BuildAndDiagnose,
10680 QualType &CaptureType,
10681 QualType &DeclRefType) {
10682 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010683
Eli Friedmanb942cb22012-02-03 22:47:37 +000010684 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010685 if (Var->getDeclContext() == DC) return true;
10686 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010687
Douglas Gregorf8af9822012-02-12 18:42:33 +000010688 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010689
Douglas Gregor999713e2012-02-18 09:37:24 +000010690 // Walk up the stack to determine whether we can capture the variable,
10691 // performing the "simple" checks that don't depend on type. We stop when
10692 // we've either hit the declared scope of the variable or find an existing
10693 // capture of that variable.
10694 CaptureType = Var->getType();
10695 DeclRefType = CaptureType.getNonReferenceType();
10696 bool Explicit = (Kind != TryCapture_Implicit);
10697 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010698 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010699 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010700 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010701 DeclContext *ParentDC;
10702 if (isa<BlockDecl>(DC))
10703 ParentDC = DC->getParent();
10704 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010705 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010706 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10707 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010708 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010709 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010710 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010711 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010712 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010713
Eli Friedmanb942cb22012-02-03 22:47:37 +000010714 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010715 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010716
Eli Friedmanb942cb22012-02-03 22:47:37 +000010717 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010718 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010719 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010720 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010721
10722 // Retrieve the capture type for this variable.
10723 CaptureType = CSI->getCapture(Var).getCaptureType();
10724
10725 // Compute the type of an expression that refers to this variable.
10726 DeclRefType = CaptureType.getNonReferenceType();
10727
10728 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10729 if (Cap.isCopyCapture() &&
10730 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10731 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010732 break;
10733 }
10734
Douglas Gregorf8af9822012-02-12 18:42:33 +000010735 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010736 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010737
10738 // Lambdas are not allowed to capture unnamed variables
10739 // (e.g. anonymous unions).
10740 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10741 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010742 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010743 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010744 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10745 Diag(Var->getLocation(), diag::note_declared_at);
10746 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010747 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010748 }
10749
10750 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010751 if (Var->getType()->isVariablyModifiedType()) {
10752 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010753 if (IsBlock)
10754 Diag(Loc, diag::err_ref_vm_type);
10755 else
10756 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10757 Diag(Var->getLocation(), diag::note_previous_decl)
10758 << Var->getDeclName();
10759 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010760 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010761 }
Fariborz Jahanianb20eb102013-01-08 23:48:48 +000010762 // Prohibit structs with flexible array members too.
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010763 // We cannot capture what is in the tail end of the struct.
10764 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
Fariborz Jahaniane178e702013-01-09 00:09:15 +000010765 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010766 if (BuildAndDiagnose) {
10767 if (IsBlock)
10768 Diag(Loc, diag::err_ref_flexarray_type);
Fariborz Jahaniane178e702013-01-09 00:09:15 +000010769 else
10770 Diag(Loc, diag::err_lambda_capture_flexarray_type)
10771 << Var->getDeclName();
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010772 Diag(Var->getLocation(), diag::note_previous_decl)
10773 << Var->getDeclName();
10774 }
10775 return true;
10776 }
10777 }
Eli Friedmanb942cb22012-02-03 22:47:37 +000010778 // Lambdas are not allowed to capture __block variables; they don't
10779 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010780 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010781 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010782 Diag(Loc, diag::err_lambda_capture_block)
10783 << Var->getDeclName();
10784 Diag(Var->getLocation(), diag::note_previous_decl)
10785 << Var->getDeclName();
10786 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010787 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010788 }
10789
Douglas Gregorf8af9822012-02-12 18:42:33 +000010790 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10791 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010792 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010793 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10794 Diag(Var->getLocation(), diag::note_previous_decl)
10795 << Var->getDeclName();
10796 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10797 diag::note_lambda_decl);
10798 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010799 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010800 }
10801
10802 FunctionScopesIndex--;
10803 DC = ParentDC;
10804 Explicit = false;
10805 } while (!Var->getDeclContext()->Equals(DC));
10806
Douglas Gregor999713e2012-02-18 09:37:24 +000010807 // Walk back down the scope stack, computing the type of the capture at
10808 // each step, checking type-specific requirements, and adding captures if
10809 // requested.
10810 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10811 ++I) {
10812 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010813
Douglas Gregor999713e2012-02-18 09:37:24 +000010814 // Compute the type of the capture and of a reference to the capture within
10815 // this scope.
10816 if (isa<BlockScopeInfo>(CSI)) {
10817 Expr *CopyExpr = 0;
10818 bool ByRef = false;
10819
10820 // Blocks are not allowed to capture arrays.
10821 if (CaptureType->isArrayType()) {
10822 if (BuildAndDiagnose) {
10823 Diag(Loc, diag::err_ref_array_type);
10824 Diag(Var->getLocation(), diag::note_previous_decl)
10825 << Var->getDeclName();
10826 }
10827 return true;
10828 }
10829
John McCall100c6492012-03-30 05:23:48 +000010830 // Forbid the block-capture of autoreleasing variables.
10831 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10832 if (BuildAndDiagnose) {
10833 Diag(Loc, diag::err_arc_autoreleasing_capture)
10834 << /*block*/ 0;
10835 Diag(Var->getLocation(), diag::note_previous_decl)
10836 << Var->getDeclName();
10837 }
10838 return true;
10839 }
10840
Douglas Gregor999713e2012-02-18 09:37:24 +000010841 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10842 // Block capture by reference does not change the capture or
10843 // declaration reference types.
10844 ByRef = true;
10845 } else {
10846 // Block capture by copy introduces 'const'.
10847 CaptureType = CaptureType.getNonReferenceType().withConst();
10848 DeclRefType = CaptureType;
10849
David Blaikie4e4d0842012-03-11 07:00:24 +000010850 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010851 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10852 // The capture logic needs the destructor, so make sure we mark it.
10853 // Usually this is unnecessary because most local variables have
10854 // their destructors marked at declaration time, but parameters are
10855 // an exception because it's technically only the call site that
10856 // actually requires the destructor.
10857 if (isa<ParmVarDecl>(Var))
10858 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor464a01a2012-12-01 01:01:09 +000010859
Douglas Gregor999713e2012-02-18 09:37:24 +000010860 // According to the blocks spec, the capture of a variable from
10861 // the stack requires a const copy constructor. This is not true
10862 // of the copy/move done to move a __block variable to the heap.
Douglas Gregor464a01a2012-12-01 01:01:09 +000010863 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
Douglas Gregor999713e2012-02-18 09:37:24 +000010864 DeclRefType.withConst(),
10865 VK_LValue, Loc);
Douglas Gregor464a01a2012-12-01 01:01:09 +000010866
Douglas Gregor999713e2012-02-18 09:37:24 +000010867 ExprResult Result
10868 = PerformCopyInitialization(
10869 InitializedEntity::InitializeBlock(Var->getLocation(),
10870 CaptureType, false),
10871 Loc, Owned(DeclRef));
10872
10873 // Build a full-expression copy expression if initialization
10874 // succeeded and used a non-trivial constructor. Recover from
10875 // errors by pretending that the copy isn't necessary.
10876 if (!Result.isInvalid() &&
10877 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10878 ->isTrivial()) {
10879 Result = MaybeCreateExprWithCleanups(Result);
10880 CopyExpr = Result.take();
10881 }
10882 }
10883 }
10884 }
10885
10886 // Actually capture the variable.
10887 if (BuildAndDiagnose)
10888 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10889 SourceLocation(), CaptureType, CopyExpr);
10890 Nested = true;
10891 continue;
10892 }
Douglas Gregor68932842012-02-18 05:51:20 +000010893
Douglas Gregor999713e2012-02-18 09:37:24 +000010894 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10895
10896 // Determine whether we are capturing by reference or by value.
10897 bool ByRef = false;
10898 if (I == N - 1 && Kind != TryCapture_Implicit) {
10899 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010900 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010901 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010902 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010903
10904 // Compute the type of the field that will capture this variable.
10905 if (ByRef) {
10906 // C++11 [expr.prim.lambda]p15:
10907 // An entity is captured by reference if it is implicitly or
10908 // explicitly captured but not captured by copy. It is
10909 // unspecified whether additional unnamed non-static data
10910 // members are declared in the closure type for entities
10911 // captured by reference.
10912 //
10913 // FIXME: It is not clear whether we want to build an lvalue reference
10914 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10915 // to do the former, while EDG does the latter. Core issue 1249 will
10916 // clarify, but for now we follow GCC because it's a more permissive and
10917 // easily defensible position.
10918 CaptureType = Context.getLValueReferenceType(DeclRefType);
10919 } else {
10920 // C++11 [expr.prim.lambda]p14:
10921 // For each entity captured by copy, an unnamed non-static
10922 // data member is declared in the closure type. The
10923 // declaration order of these members is unspecified. The type
10924 // of such a data member is the type of the corresponding
10925 // captured entity if the entity is not a reference to an
10926 // object, or the referenced type otherwise. [Note: If the
10927 // captured entity is a reference to a function, the
10928 // corresponding data member is also a reference to a
10929 // function. - end note ]
10930 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10931 if (!RefType->getPointeeType()->isFunctionType())
10932 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010933 }
John McCall100c6492012-03-30 05:23:48 +000010934
10935 // Forbid the lambda copy-capture of autoreleasing variables.
10936 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10937 if (BuildAndDiagnose) {
10938 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10939 Diag(Var->getLocation(), diag::note_previous_decl)
10940 << Var->getDeclName();
10941 }
10942 return true;
10943 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010944 }
10945
Douglas Gregor999713e2012-02-18 09:37:24 +000010946 // Capture this variable in the lambda.
10947 Expr *CopyExpr = 0;
10948 if (BuildAndDiagnose) {
10949 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010950 DeclRefType, Loc,
Douglas Gregor464a01a2012-12-01 01:01:09 +000010951 Nested);
Douglas Gregor999713e2012-02-18 09:37:24 +000010952 if (!Result.isInvalid())
10953 CopyExpr = Result.take();
10954 }
10955
10956 // Compute the type of a reference to this captured variable.
10957 if (ByRef)
10958 DeclRefType = CaptureType.getNonReferenceType();
10959 else {
10960 // C++ [expr.prim.lambda]p5:
10961 // The closure type for a lambda-expression has a public inline
10962 // function call operator [...]. This function call operator is
10963 // declared const (9.3.1) if and only if the lambda-expression’s
10964 // parameter-declaration-clause is not followed by mutable.
10965 DeclRefType = CaptureType.getNonReferenceType();
10966 if (!LSI->Mutable && !CaptureType->isReferenceType())
10967 DeclRefType.addConst();
10968 }
10969
10970 // Add the capture.
10971 if (BuildAndDiagnose)
10972 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10973 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010974 Nested = true;
10975 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010976
10977 return false;
10978}
10979
10980bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10981 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10982 QualType CaptureType;
10983 QualType DeclRefType;
10984 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10985 /*BuildAndDiagnose=*/true, CaptureType,
10986 DeclRefType);
10987}
10988
10989QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10990 QualType CaptureType;
10991 QualType DeclRefType;
10992
10993 // Determine whether we can capture this variable.
10994 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10995 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10996 return QualType();
10997
10998 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010999}
11000
Eli Friedmand2cce132012-02-02 23:15:15 +000011001static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11002 SourceLocation Loc) {
11003 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000011004 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011005 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000011006 Var->getLinkage() != ExternalLinkage &&
11007 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011008 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
11009 if (old.isInvalid()) old = Loc;
11010 }
11011
Douglas Gregor999713e2012-02-18 09:37:24 +000011012 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011013
Eli Friedmand2cce132012-02-02 23:15:15 +000011014 Var->setUsed(true);
11015}
11016
11017void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11018 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11019 // an object that satisfies the requirements for appearing in a
11020 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11021 // is immediately applied." This function handles the lvalue-to-rvalue
11022 // conversion part.
11023 MaybeODRUseExprs.erase(E->IgnoreParens());
11024}
11025
Eli Friedmanac626012012-02-29 03:16:56 +000011026ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11027 if (!Res.isUsable())
11028 return Res;
11029
11030 // If a constant-expression is a reference to a variable where we delay
11031 // deciding whether it is an odr-use, just assume we will apply the
11032 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11033 // (a non-type template argument), we have special handling anyway.
11034 UpdateMarkingForLValueToRValue(Res.get());
11035 return Res;
11036}
11037
Eli Friedmand2cce132012-02-02 23:15:15 +000011038void Sema::CleanupVarDeclMarking() {
11039 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11040 e = MaybeODRUseExprs.end();
11041 i != e; ++i) {
11042 VarDecl *Var;
11043 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000011044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011045 Var = cast<VarDecl>(DRE->getDecl());
11046 Loc = DRE->getLocation();
11047 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11048 Var = cast<VarDecl>(ME->getMemberDecl());
11049 Loc = ME->getMemberLoc();
11050 } else {
11051 llvm_unreachable("Unexpcted expression");
11052 }
11053
11054 MarkVarDeclODRUsed(*this, Var, Loc);
11055 }
11056
11057 MaybeODRUseExprs.clear();
11058}
11059
11060// Mark a VarDecl referenced, and perform the necessary handling to compute
11061// odr-uses.
11062static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11063 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011064 Var->setReferenced();
11065
Eli Friedmand2cce132012-02-02 23:15:15 +000011066 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011067 return;
11068
11069 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000011070 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011071 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11072 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000011073 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11074 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011075 (!AlreadyInstantiated ||
11076 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000011077 if (!AlreadyInstantiated) {
11078 // This is a modification of an existing AST node. Notify listeners.
11079 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11080 L->StaticDataMemberInstantiated(Var);
11081 MSInfo->setPointOfInstantiation(Loc);
11082 }
11083 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011084 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011085 // Do not defer instantiations of variables which could be used in a
11086 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011087 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011088 else
Richard Smith37ce0102012-02-15 02:42:50 +000011089 SemaRef.PendingInstantiations.push_back(
11090 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011091 }
11092 }
11093
Richard Smith5016a702012-10-20 01:38:33 +000011094 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11095 // the requirements for appearing in a constant expression (5.19) and, if
11096 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000011097 // is immediately applied." We check the first part here, and
11098 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11099 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000011100 // C++03 depends on whether we get the C++03 version correct. The second
11101 // part does not apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011102 const VarDecl *DefVD;
Richard Smith5016a702012-10-20 01:38:33 +000011103 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011104 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5016a702012-10-20 01:38:33 +000011105 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11106 if (!Var->getType()->isReferenceType())
11107 SemaRef.MaybeODRUseExprs.insert(E);
11108 } else
Eli Friedmand2cce132012-02-02 23:15:15 +000011109 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11110}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011111
Eli Friedmand2cce132012-02-02 23:15:15 +000011112/// \brief Mark a variable referenced, and check whether it is odr-used
11113/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11114/// used directly for normal expressions referring to VarDecl.
11115void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11116 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011117}
11118
11119static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11120 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011121 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11122 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11123 return;
11124 }
11125
Eli Friedman5f2987c2012-02-02 03:46:19 +000011126 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011127
11128 // If this is a call to a method via a cast, also mark the method in the
11129 // derived class used in case codegen can devirtualize the call.
11130 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11131 if (!ME)
11132 return;
11133 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11134 if (!MD)
11135 return;
11136 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011137 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011138 if (!MostDerivedClassDecl)
11139 return;
11140 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011141 if (!DM)
11142 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011143 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011144}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011145
Eli Friedman5f2987c2012-02-02 03:46:19 +000011146/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11147void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11148 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11149}
11150
11151/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11152void Sema::MarkMemberReferenced(MemberExpr *E) {
11153 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11154}
11155
Douglas Gregor73d90922012-02-10 09:26:04 +000011156/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011157/// marks the declaration referenced, and performs odr-use checking for functions
11158/// and variables. This method should not be used when building an normal
11159/// expression which refers to a variable.
11160void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11161 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11162 MarkVariableReferenced(Loc, VD);
11163 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11164 MarkFunctionReferenced(Loc, FD);
11165 else
11166 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011167}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011168
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011169namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011170 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011171 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011172 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011173 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11174 Sema &S;
11175 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011176
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011177 public:
11178 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011179
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011180 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011181
11182 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11183 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011184 };
11185}
11186
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011187bool MarkReferencedDecls::TraverseTemplateArgument(
11188 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011189 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011190 if (Decl *D = Arg.getAsDecl())
11191 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011192 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011193
11194 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011195}
11196
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011197bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011198 if (ClassTemplateSpecializationDecl *Spec
11199 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11200 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011201 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011202 }
11203
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011204 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011205}
11206
11207void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11208 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011209 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011210}
11211
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011212namespace {
11213 /// \brief Helper class that marks all of the declarations referenced by
11214 /// potentially-evaluated subexpressions as "referenced".
11215 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11216 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011217 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011218
11219 public:
11220 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11221
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011222 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11223 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011224
11225 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011226 // If we were asked not to visit local variables, don't.
11227 if (SkipLocalVariables) {
11228 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11229 if (VD->hasLocalStorage())
11230 return;
11231 }
11232
Eli Friedman5f2987c2012-02-02 03:46:19 +000011233 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011234 }
11235
11236 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011237 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011238 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011239 }
11240
John McCall80ee6e82011-11-10 05:35:25 +000011241 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011242 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011243 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11244 Visit(E->getSubExpr());
11245 }
11246
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011247 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011248 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011249 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011250 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011251 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011252 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011253 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011254
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011255 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11256 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011257 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011258 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11259 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11260 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011261 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011262 S.LookupDestructor(Record));
11263 }
11264
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011265 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011266 }
11267
11268 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011269 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011270 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011271 }
11272
Douglas Gregor102ff972010-10-19 17:17:35 +000011273 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11274 Visit(E->getExpr());
11275 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011276
11277 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11278 Inherited::VisitImplicitCastExpr(E);
11279
11280 if (E->getCastKind() == CK_LValueToRValue)
11281 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11282 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011283 };
11284}
11285
11286/// \brief Mark any declarations that appear within this expression or any
11287/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011288///
11289/// \param SkipLocalVariables If true, don't mark local variables as
11290/// 'referenced'.
11291void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11292 bool SkipLocalVariables) {
11293 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011294}
11295
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011296/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11297/// of the program being compiled.
11298///
11299/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011300/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011301/// possibility that the code will actually be executable. Code in sizeof()
11302/// expressions, code used only during overload resolution, etc., are not
11303/// potentially evaluated. This routine will suppress such diagnostics or,
11304/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011305/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011306/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011307///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011308/// This routine should be used for all diagnostics that describe the run-time
11309/// behavior of a program, such as passing a non-POD value through an ellipsis.
11310/// Failure to do so will likely result in spurious diagnostics or failures
11311/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011312bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011313 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011314 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011315 case Unevaluated:
11316 // The argument will never be evaluated, so don't complain.
11317 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011318
Richard Smithf6702a32011-12-20 02:08:33 +000011319 case ConstantEvaluated:
11320 // Relevant diagnostics should be produced by constant evaluation.
11321 break;
11322
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011323 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011324 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011325 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011326 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011327 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011328 }
11329 else
11330 Diag(Loc, PD);
11331
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011332 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011333 }
11334
11335 return false;
11336}
11337
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011338bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11339 CallExpr *CE, FunctionDecl *FD) {
11340 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11341 return false;
11342
Richard Smith76f3f692012-02-22 02:04:18 +000011343 // If we're inside a decltype's expression, don't check for a valid return
11344 // type or construct temporaries until we know whether this is the last call.
11345 if (ExprEvalContexts.back().IsDecltype) {
11346 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11347 return false;
11348 }
11349
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011350 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011351 FunctionDecl *FD;
11352 CallExpr *CE;
11353
11354 public:
11355 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11356 : FD(FD), CE(CE) { }
11357
11358 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11359 if (!FD) {
11360 S.Diag(Loc, diag::err_call_incomplete_return)
11361 << T << CE->getSourceRange();
11362 return;
11363 }
11364
11365 S.Diag(Loc, diag::err_call_function_incomplete_return)
11366 << CE->getSourceRange() << FD->getDeclName() << T;
11367 S.Diag(FD->getLocation(),
11368 diag::note_function_with_incomplete_return_type_declared_here)
11369 << FD->getDeclName();
11370 }
11371 } Diagnoser(FD, CE);
11372
11373 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011374 return true;
11375
11376 return false;
11377}
11378
Douglas Gregor92c3a042011-01-19 16:50:08 +000011379// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011380// will prevent this condition from triggering, which is what we want.
11381void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11382 SourceLocation Loc;
11383
John McCalla52ef082009-11-11 02:41:58 +000011384 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011385 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011386
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011387 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011388 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011389 return;
11390
Douglas Gregor92c3a042011-01-19 16:50:08 +000011391 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11392
John McCallc8d8ac52009-11-12 00:06:05 +000011393 // Greylist some idioms by putting them into a warning subcategory.
11394 if (ObjCMessageExpr *ME
11395 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11396 Selector Sel = ME->getSelector();
11397
John McCallc8d8ac52009-11-12 00:06:05 +000011398 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011399 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011400 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11401
11402 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011403 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011404 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11405 }
John McCalla52ef082009-11-11 02:41:58 +000011406
John McCall5a881bb2009-10-12 21:59:07 +000011407 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011408 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011409 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011410 return;
11411
Douglas Gregor92c3a042011-01-19 16:50:08 +000011412 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011413 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011414 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11415 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11416 else {
John McCall5a881bb2009-10-12 21:59:07 +000011417 // Not an assignment.
11418 return;
11419 }
11420
Douglas Gregor55b38842010-04-14 16:09:52 +000011421 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011422
Daniel Dunbar96a00142012-03-09 18:35:03 +000011423 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011424 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11425 Diag(Loc, diag::note_condition_assign_silence)
11426 << FixItHint::CreateInsertion(Open, "(")
11427 << FixItHint::CreateInsertion(Close, ")");
11428
Douglas Gregor92c3a042011-01-19 16:50:08 +000011429 if (IsOrAssign)
11430 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11431 << FixItHint::CreateReplacement(Loc, "!=");
11432 else
11433 Diag(Loc, diag::note_condition_assign_to_comparison)
11434 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011435}
11436
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011437/// \brief Redundant parentheses over an equality comparison can indicate
11438/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011439void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011440 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011441 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011442 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11443 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011444 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011445 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011446 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011447
Richard Trieuccd891a2011-09-09 01:45:06 +000011448 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011449
11450 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011451 if (opE->getOpcode() == BO_EQ &&
11452 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11453 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011454 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011455
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011456 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011457 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011458 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011459 << FixItHint::CreateRemoval(ParenERange.getBegin())
11460 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011461 Diag(Loc, diag::note_equality_comparison_to_assign)
11462 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011463 }
11464}
11465
John Wiegley429bb272011-04-08 18:41:53 +000011466ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011467 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011468 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11469 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011470
John McCall864c0412011-04-26 20:42:42 +000011471 ExprResult result = CheckPlaceholderExpr(E);
11472 if (result.isInvalid()) return ExprError();
11473 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011474
John McCall864c0412011-04-26 20:42:42 +000011475 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011476 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011477 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11478
John Wiegley429bb272011-04-08 18:41:53 +000011479 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11480 if (ERes.isInvalid())
11481 return ExprError();
11482 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011483
11484 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011485 if (!T->isScalarType()) { // C99 6.8.4.1p1
11486 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11487 << T << E->getSourceRange();
11488 return ExprError();
11489 }
John McCall5a881bb2009-10-12 21:59:07 +000011490 }
11491
John Wiegley429bb272011-04-08 18:41:53 +000011492 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011493}
Douglas Gregor586596f2010-05-06 17:25:47 +000011494
John McCall60d7b3a2010-08-24 06:29:42 +000011495ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011496 Expr *SubExpr) {
11497 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011498 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011499
Richard Trieuccd891a2011-09-09 01:45:06 +000011500 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011501}
John McCall2a984ca2010-10-12 00:20:44 +000011502
John McCall1de4d4e2011-04-07 08:22:57 +000011503namespace {
John McCall755d8492011-04-12 00:42:48 +000011504 /// A visitor for rebuilding a call to an __unknown_any expression
11505 /// to have an appropriate type.
11506 struct RebuildUnknownAnyFunction
11507 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11508
11509 Sema &S;
11510
11511 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11512
11513 ExprResult VisitStmt(Stmt *S) {
11514 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011515 }
11516
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011517 ExprResult VisitExpr(Expr *E) {
11518 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11519 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011520 return ExprError();
11521 }
11522
11523 /// Rebuild an expression which simply semantically wraps another
11524 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011525 template <class T> ExprResult rebuildSugarExpr(T *E) {
11526 ExprResult SubResult = Visit(E->getSubExpr());
11527 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011528
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011529 Expr *SubExpr = SubResult.take();
11530 E->setSubExpr(SubExpr);
11531 E->setType(SubExpr->getType());
11532 E->setValueKind(SubExpr->getValueKind());
11533 assert(E->getObjectKind() == OK_Ordinary);
11534 return E;
John McCall755d8492011-04-12 00:42:48 +000011535 }
11536
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011537 ExprResult VisitParenExpr(ParenExpr *E) {
11538 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011539 }
11540
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011541 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11542 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011543 }
11544
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011545 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11546 ExprResult SubResult = Visit(E->getSubExpr());
11547 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011548
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011549 Expr *SubExpr = SubResult.take();
11550 E->setSubExpr(SubExpr);
11551 E->setType(S.Context.getPointerType(SubExpr->getType()));
11552 assert(E->getValueKind() == VK_RValue);
11553 assert(E->getObjectKind() == OK_Ordinary);
11554 return E;
John McCall755d8492011-04-12 00:42:48 +000011555 }
11556
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011557 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11558 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011559
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011560 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011561
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011562 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011563 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011564 !(isa<CXXMethodDecl>(VD) &&
11565 cast<CXXMethodDecl>(VD)->isInstance()))
11566 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011567
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011568 return E;
John McCall755d8492011-04-12 00:42:48 +000011569 }
11570
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011571 ExprResult VisitMemberExpr(MemberExpr *E) {
11572 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011573 }
11574
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011575 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11576 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011577 }
11578 };
11579}
11580
11581/// Given a function expression of unknown-any type, try to rebuild it
11582/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011583static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11584 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11585 if (Result.isInvalid()) return ExprError();
11586 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011587}
11588
11589namespace {
John McCall379b5152011-04-11 07:02:50 +000011590 /// A visitor for rebuilding an expression of type __unknown_anytype
11591 /// into one which resolves the type directly on the referring
11592 /// expression. Strict preservation of the original source
11593 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011594 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011595 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011596
11597 Sema &S;
11598
11599 /// The current destination type.
11600 QualType DestType;
11601
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011602 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11603 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011604
John McCalla5fc4722011-04-09 22:50:59 +000011605 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011606 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011607 }
11608
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011609 ExprResult VisitExpr(Expr *E) {
11610 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11611 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011612 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011613 }
11614
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011615 ExprResult VisitCallExpr(CallExpr *E);
11616 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011617
John McCalla5fc4722011-04-09 22:50:59 +000011618 /// Rebuild an expression which simply semantically wraps another
11619 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011620 template <class T> ExprResult rebuildSugarExpr(T *E) {
11621 ExprResult SubResult = Visit(E->getSubExpr());
11622 if (SubResult.isInvalid()) return ExprError();
11623 Expr *SubExpr = SubResult.take();
11624 E->setSubExpr(SubExpr);
11625 E->setType(SubExpr->getType());
11626 E->setValueKind(SubExpr->getValueKind());
11627 assert(E->getObjectKind() == OK_Ordinary);
11628 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011629 }
John McCall1de4d4e2011-04-07 08:22:57 +000011630
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011631 ExprResult VisitParenExpr(ParenExpr *E) {
11632 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011633 }
11634
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011635 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11636 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011637 }
11638
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011639 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11640 const PointerType *Ptr = DestType->getAs<PointerType>();
11641 if (!Ptr) {
11642 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11643 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011644 return ExprError();
11645 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011646 assert(E->getValueKind() == VK_RValue);
11647 assert(E->getObjectKind() == OK_Ordinary);
11648 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011649
11650 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011651 DestType = Ptr->getPointeeType();
11652 ExprResult SubResult = Visit(E->getSubExpr());
11653 if (SubResult.isInvalid()) return ExprError();
11654 E->setSubExpr(SubResult.take());
11655 return E;
John McCall755d8492011-04-12 00:42:48 +000011656 }
11657
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011658 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011659
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011660 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011661
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011662 ExprResult VisitMemberExpr(MemberExpr *E) {
11663 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011664 }
John McCalla5fc4722011-04-09 22:50:59 +000011665
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011666 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11667 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011668 }
11669 };
11670}
11671
John McCall379b5152011-04-11 07:02:50 +000011672/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011673ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11674 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011675
11676 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011677 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011678 FK_FunctionPointer,
11679 FK_BlockPointer
11680 };
11681
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011682 FnKind Kind;
11683 QualType CalleeType = CalleeExpr->getType();
11684 if (CalleeType == S.Context.BoundMemberTy) {
11685 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11686 Kind = FK_MemberFunction;
11687 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11688 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11689 CalleeType = Ptr->getPointeeType();
11690 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011691 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011692 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11693 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011694 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011695 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011696
11697 // Verify that this is a legal result type of a function.
11698 if (DestType->isArrayType() || DestType->isFunctionType()) {
11699 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011700 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011701 diagID = diag::err_block_returning_array_function;
11702
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011703 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011704 << DestType->isFunctionType() << DestType;
11705 return ExprError();
11706 }
11707
11708 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011709 E->setType(DestType.getNonLValueExprType(S.Context));
11710 E->setValueKind(Expr::getValueKindForType(DestType));
11711 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011712
11713 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011714 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011715 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011716 Proto->arg_type_begin(),
11717 Proto->getNumArgs(),
11718 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011719 else
11720 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011721 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011722
11723 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011724 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011725 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011726 // Nothing to do.
11727 break;
11728
11729 case FK_FunctionPointer:
11730 DestType = S.Context.getPointerType(DestType);
11731 break;
11732
11733 case FK_BlockPointer:
11734 DestType = S.Context.getBlockPointerType(DestType);
11735 break;
11736 }
11737
11738 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011739 ExprResult CalleeResult = Visit(CalleeExpr);
11740 if (!CalleeResult.isUsable()) return ExprError();
11741 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011742
11743 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011744 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011745}
11746
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011747ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011748 // Verify that this is a legal result type of a call.
11749 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011750 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011751 << DestType->isFunctionType() << DestType;
11752 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011753 }
11754
John McCall48218c62011-07-13 17:56:40 +000011755 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011756 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11757 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11758 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011759 }
John McCall755d8492011-04-12 00:42:48 +000011760
John McCall379b5152011-04-11 07:02:50 +000011761 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011762 E->setType(DestType.getNonReferenceType());
11763 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011764
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011765 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011766}
11767
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011768ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011769 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011770 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011771 assert(E->getValueKind() == VK_RValue);
11772 assert(E->getObjectKind() == OK_Ordinary);
11773
11774 E->setType(DestType);
11775
11776 // Rebuild the sub-expression as the pointee (function) type.
11777 DestType = DestType->castAs<PointerType>()->getPointeeType();
11778
11779 ExprResult Result = Visit(E->getSubExpr());
11780 if (!Result.isUsable()) return ExprError();
11781
11782 E->setSubExpr(Result.take());
11783 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011784 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011785 assert(E->getValueKind() == VK_RValue);
11786 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011787
Sean Callanance9c8312012-03-06 21:34:12 +000011788 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011789
Sean Callanance9c8312012-03-06 21:34:12 +000011790 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011791
Sean Callanance9c8312012-03-06 21:34:12 +000011792 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11793 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011794
Sean Callanance9c8312012-03-06 21:34:12 +000011795 ExprResult Result = Visit(E->getSubExpr());
11796 if (!Result.isUsable()) return ExprError();
11797
11798 E->setSubExpr(Result.take());
11799 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011800 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011801 llvm_unreachable("Unhandled cast type!");
11802 }
John McCall379b5152011-04-11 07:02:50 +000011803}
11804
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011805ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11806 ExprValueKind ValueKind = VK_LValue;
11807 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011808
11809 // We know how to make this work for certain kinds of decls:
11810
11811 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011812 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11813 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11814 DestType = Ptr->getPointeeType();
11815 ExprResult Result = resolveDecl(E, VD);
11816 if (Result.isInvalid()) return ExprError();
11817 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011818 CK_FunctionToPointerDecay, VK_RValue);
11819 }
11820
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011821 if (!Type->isFunctionType()) {
11822 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11823 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011824 return ExprError();
11825 }
John McCall379b5152011-04-11 07:02:50 +000011826
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011827 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11828 if (MD->isInstance()) {
11829 ValueKind = VK_RValue;
11830 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011831 }
11832
John McCall379b5152011-04-11 07:02:50 +000011833 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011834 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011835 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011836
11837 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011838 } else if (isa<VarDecl>(VD)) {
11839 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11840 Type = RefTy->getPointeeType();
11841 } else if (Type->isFunctionType()) {
11842 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11843 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011844 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011845 }
11846
11847 // - nothing else
11848 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011849 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11850 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011851 return ExprError();
11852 }
11853
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011854 VD->setType(DestType);
11855 E->setType(Type);
11856 E->setValueKind(ValueKind);
11857 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011858}
11859
John McCall1de4d4e2011-04-07 08:22:57 +000011860/// Check a cast of an unknown-any type. We intentionally only
11861/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011862ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11863 Expr *CastExpr, CastKind &CastKind,
11864 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011865 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011866 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011867 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011868
Richard Trieuccd891a2011-09-09 01:45:06 +000011869 CastExpr = result.take();
11870 VK = CastExpr->getValueKind();
11871 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011872
Richard Trieuccd891a2011-09-09 01:45:06 +000011873 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011874}
11875
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011876ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11877 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11878}
11879
John McCallb8a8de32012-11-14 00:49:39 +000011880QualType Sema::checkUnknownAnyArg(Expr *&arg) {
11881 // Filter out placeholders.
11882 ExprResult argR = CheckPlaceholderExpr(arg);
11883 if (argR.isInvalid()) return QualType();
11884 arg = argR.take();
11885
11886 // If the argument is an explicit cast, use that exact type as the
11887 // effective parameter type.
11888 if (ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg)) {
11889 return castArg->getTypeAsWritten();
11890 }
11891
11892 // Otherwise, try to pass by value.
11893 return arg->getType().getUnqualifiedType();
11894}
11895
Richard Trieuccd891a2011-09-09 01:45:06 +000011896static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11897 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011898 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011899 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011900 E = E->IgnoreParenImpCasts();
11901 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11902 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011903 diagID = diag::err_uncasted_call_of_unknown_any;
11904 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011905 break;
John McCall379b5152011-04-11 07:02:50 +000011906 }
John McCall1de4d4e2011-04-07 08:22:57 +000011907 }
11908
John McCall379b5152011-04-11 07:02:50 +000011909 SourceLocation loc;
11910 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011911 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011912 loc = ref->getLocation();
11913 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011914 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011915 loc = mem->getMemberLoc();
11916 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011917 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011918 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011919 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011920 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011921 if (!d) {
11922 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11923 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11924 << orig->getSourceRange();
11925 return ExprError();
11926 }
John McCall379b5152011-04-11 07:02:50 +000011927 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011928 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11929 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011930 return ExprError();
11931 }
11932
11933 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011934
11935 // Never recoverable.
11936 return ExprError();
11937}
11938
John McCall2a984ca2010-10-12 00:20:44 +000011939/// Check for operands with placeholder types and complain if found.
11940/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011941ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011942 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11943 if (!placeholderType) return Owned(E);
11944
11945 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011946
John McCall1de4d4e2011-04-07 08:22:57 +000011947 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011948 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011949 // Try to resolve a single function template specialization.
11950 // This is obligatory.
11951 ExprResult result = Owned(E);
11952 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11953 return result;
11954
11955 // If that failed, try to recover with a call.
11956 } else {
11957 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11958 /*complain*/ true);
11959 return result;
11960 }
11961 }
John McCall1de4d4e2011-04-07 08:22:57 +000011962
John McCall864c0412011-04-26 20:42:42 +000011963 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011964 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011965 ExprResult result = Owned(E);
11966 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11967 /*complain*/ true);
11968 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011969 }
11970
11971 // ARC unbridged casts.
11972 case BuiltinType::ARCUnbridgedCast: {
11973 Expr *realCast = stripARCUnbridgedCast(E);
11974 diagnoseARCUnbridgedCast(realCast);
11975 return Owned(realCast);
11976 }
John McCall864c0412011-04-26 20:42:42 +000011977
John McCall1de4d4e2011-04-07 08:22:57 +000011978 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011979 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011980 return diagnoseUnknownAnyExpr(*this, E);
11981
John McCall3c3b7f92011-10-25 17:37:35 +000011982 // Pseudo-objects.
11983 case BuiltinType::PseudoObject:
11984 return checkPseudoObjectRValue(E);
11985
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011986 case BuiltinType::BuiltinFn:
11987 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11988 return ExprError();
11989
John McCalle0a22d02011-10-18 21:02:43 +000011990 // Everything else should be impossible.
11991#define BUILTIN_TYPE(Id, SingletonId) \
11992 case BuiltinType::Id:
11993#define PLACEHOLDER_TYPE(Id, SingletonId)
11994#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011995 break;
11996 }
11997
11998 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011999}
Richard Trieubb9b80c2011-04-21 21:44:26 +000012000
Richard Trieuccd891a2011-09-09 01:45:06 +000012001bool Sema::CheckCaseExpression(Expr *E) {
12002 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000012003 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000012004 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12005 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000012006 return false;
12007}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012008
12009/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12010ExprResult
12011Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12012 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12013 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000012014 QualType BoolT = Context.ObjCBuiltinBoolTy;
12015 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000012016 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012017 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000012018 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000012019 NamedDecl *ND = Result.getFoundDecl();
12020 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12021 Context.setBOOLDecl(TD);
12022 }
12023 }
12024 if (Context.getBOOLDecl())
12025 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012026 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012027 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012028}