blob: 3d66baa925907d02f6fe95d374bafcd977309483 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenekd6cf9122012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Jordan Rose04bec392012-10-10 16:42:54 +000090
Fariborz Jahanianfd090882012-09-21 20:46:37 +000091 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000092 if (Result == AR_Deprecated || Result == AR_Unavailable) {
93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95 AvailabilityResult PDeclResult = PD->getAvailability(0);
96 if (PDeclResult == Result)
97 ObjCPDecl = PD;
98 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000099 }
Jordan Rose04bec392012-10-10 16:42:54 +0000100 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000101
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 switch (Result) {
103 case AR_Available:
104 case AR_NotYetIntroduced:
105 break;
106
107 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000109 break;
110
111 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000112 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000114 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000116 if (ObjCPDecl)
117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118 << ObjCPDecl->getDeclName() << 1;
119 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000120 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000122 << D->getDeclName();
123 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000124 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000125 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000126 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000127 S.Diag(D->getLocation(), diag::note_unavailable_here)
128 << isa<FunctionDecl>(D) << false;
129 if (ObjCPDecl)
130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000132 }
133 break;
134 }
135 return Result;
136}
137
Richard Smith6c4c36c2012-03-30 20:53:28 +0000138/// \brief Emit a note explaining that this function is deleted or unavailable.
139void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141
Richard Smith5bdaac52012-04-02 20:59:25 +0000142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143 // If the method was explicitly defaulted, point at that declaration.
144 if (!Method->isImplicit())
145 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146
147 // Try to diagnose why this special member function was implicitly
148 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000149 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000150 if (CSM != CXXInvalid)
151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
152
153 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000154 }
155
156 Diag(Decl->getLocation(), diag::note_unavailable_here)
157 << 1 << Decl->isDeleted();
158}
159
Jordan Rose0eb3f452012-06-18 22:09:19 +0000160/// \brief Determine whether a FunctionDecl was ever declared with an
161/// explicit storage class.
162static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164 E = D->redecls_end();
165 I != E; ++I) {
166 if (I->getStorageClassAsWritten() != SC_None)
167 return true;
168 }
169 return false;
170}
171
172/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000173/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000175/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000176/// in many cases it will not behave correctly. This is not enabled in C++ mode
177/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178/// and so while there may still be user mistakes, most of the time we can't
179/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000180static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181 const NamedDecl *D,
182 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000183 // This is disabled under C++; there are too many ways for this to fire in
184 // contexts where the warning is a false positive, or where it is technically
185 // correct but benign.
186 if (S.getLangOpts().CPlusPlus)
187 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000188
189 // Check if this is an inlined function or method.
190 FunctionDecl *Current = S.getCurFunctionDecl();
191 if (!Current)
192 return;
193 if (!Current->isInlined())
194 return;
195 if (Current->getLinkage() != ExternalLinkage)
196 return;
197
198 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000199 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000200 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000201
Jordan Rose05233272012-06-21 05:54:50 +0000202 // Downgrade from ExtWarn to Extension if
203 // (1) the supposedly external inline function is in the main file,
204 // and probably won't be included anywhere else.
205 // (2) the thing we're referencing is a pure function.
206 // (3) the thing we're referencing is another inline function.
207 // This last can give us false negatives, but it's better than warning on
208 // wrappers for simple C library functions.
209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211 if (!DowngradeWarning && UsedFn)
212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213
214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215 : diag::warn_internal_in_extern_inline)
216 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000217
218 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000219 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
224 }
225
226 S.Diag(D->getCanonicalDecl()->getLocation(),
227 diag::note_internal_decl_declared_here)
228 << D;
229}
230
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000231/// \brief Determine whether the use of this declaration is valid, and
232/// emit any corresponding diagnostics.
233///
234/// This routine diagnoses various problems with referencing
235/// declarations that can occur when using a declaration. For example,
236/// it might warn if a deprecated or unavailable declaration is being
237/// used, or produce an error (and return true) if a C++0x deleted
238/// function is being used.
239///
240/// \returns true if there was an error (this declaration cannot be
241/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000242///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000243bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000244 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000246 // If there were any diagnostics suppressed by template argument deduction,
247 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253 Diag(Suppressed[I].first, Suppressed[I].second);
254
255 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000256 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000257 // entry from the table, because we want to avoid ever emitting these
258 // diagnostics again.
259 Suppressed.clear();
260 }
261 }
262
Richard Smith34b41d92011-02-20 03:19:35 +0000263 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000264 if (ParsingInitForAutoVars.count(D)) {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << D->getDeclName();
267 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000268 }
269
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000270 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000272 if (FD->isDeleted()) {
273 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000274 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000275 return true;
276 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000277 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000279
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000280 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000281
Jordan Rose0eb3f452012-06-18 22:09:19 +0000282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000283
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000284 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000285}
286
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000287/// \brief Retrieve the message suffix that should be added to a
288/// diagnostic complaining about the given function being deleted or
289/// unavailable.
290std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291 // FIXME: C++0x implicitly-deleted special member functions could be
292 // detected here so that we could improve diagnostics to say, e.g.,
293 // "base class 'A' had a deleted copy constructor".
294 if (FD->isDeleted())
295 return std::string();
296
297 std::string Message;
298 if (FD->getAvailability(&Message))
299 return ": " + Message;
300
301 return std::string();
302}
303
John McCall3323fad2011-09-09 07:56:05 +0000304/// DiagnoseSentinelCalls - This routine checks whether a call or
305/// message-send is to a declaration with the sentinel attribute, and
306/// if so, it checks that the requirements of the sentinel are
307/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000308void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000309 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000310 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000311 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000312 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000313
John McCall3323fad2011-09-09 07:56:05 +0000314 // The number of formal parameters of the declaration.
315 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCall3323fad2011-09-09 07:56:05 +0000317 // The kind of declaration. This is also an index into a %select in
318 // the diagnostic.
319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
320
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000322 numFormalParams = MD->param_size();
323 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000325 numFormalParams = FD->param_size();
326 calleeType = CT_Function;
327 } else if (isa<VarDecl>(D)) {
328 QualType type = cast<ValueDecl>(D)->getType();
329 const FunctionType *fn = 0;
330 if (const PointerType *ptr = type->getAs<PointerType>()) {
331 fn = ptr->getPointeeType()->getAs<FunctionType>();
332 if (!fn) return;
333 calleeType = CT_Function;
334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335 fn = ptr->getPointeeType()->castAs<FunctionType>();
336 calleeType = CT_Block;
337 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000338 return;
John McCall3323fad2011-09-09 07:56:05 +0000339 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000340
John McCall3323fad2011-09-09 07:56:05 +0000341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342 numFormalParams = proto->getNumArgs();
343 } else {
344 numFormalParams = 0;
345 }
346 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000347 return;
348 }
John McCall3323fad2011-09-09 07:56:05 +0000349
350 // "nullPos" is the number of formal parameters at the end which
351 // effectively count as part of the variadic arguments. This is
352 // useful if you would prefer to not have *any* formal parameters,
353 // but the language forces you to have at least one.
354 unsigned nullPos = attr->getNullPos();
355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
357
358 // The number of arguments which should follow the sentinel.
359 unsigned numArgsAfterSentinel = attr->getSentinel();
360
361 // If there aren't enough arguments for all the formal parameters,
362 // the sentinel, and the args after the sentinel, complain.
363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000366 return;
367 }
John McCall3323fad2011-09-09 07:56:05 +0000368
369 // Otherwise, find the sentinel expression.
370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000371 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000372 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000373 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000374
John McCall3323fad2011-09-09 07:56:05 +0000375 // Pick a reasonable string to insert. Optimistically use 'nil' or
376 // 'NULL' if those are actually defined in the context. Only use
377 // 'nil' for ObjC methods, where it's much more likely that the
378 // variadic arguments form a list of object pointers.
379 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000382 if (calleeType == CT_Method &&
383 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000384 NullValue = "nil";
385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000387 else
John McCall3323fad2011-09-09 07:56:05 +0000388 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000389
390 if (MissingNilLoc.isInvalid())
391 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
392 else
393 Diag(MissingNilLoc, diag::warn_missing_sentinel)
394 << calleeType
395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000397}
398
Richard Trieuccd891a2011-09-09 01:45:06 +0000399SourceRange Sema::getExprRange(Expr *E) const {
400 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000401}
402
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403//===----------------------------------------------------------------------===//
404// Standard Promotions and Conversions
405//===----------------------------------------------------------------------===//
406
Chris Lattnere7a2e912008-07-25 21:10:04 +0000407/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000408ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000409 // Handle any placeholder expressions which made it here.
410 if (E->getType()->isPlaceholderType()) {
411 ExprResult result = CheckPlaceholderExpr(E);
412 if (result.isInvalid()) return ExprError();
413 E = result.take();
414 }
415
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416 QualType Ty = E->getType();
417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
418
Chris Lattnere7a2e912008-07-25 21:10:04 +0000419 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000420 E = ImpCastExprToType(E, Context.getPointerType(Ty),
421 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000422 else if (Ty->isArrayType()) {
423 // In C90 mode, arrays only promote to pointers if the array expression is
424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425 // type 'array of type' is converted to an expression that has type 'pointer
426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
427 // that has type 'array of type' ...". The relevant change is "an lvalue"
428 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000429 //
430 // C++ 4.2p1:
431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432 // T" can be converted to an rvalue of type "pointer to T".
433 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000437 }
John Wiegley429bb272011-04-08 18:41:53 +0000438 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000439}
440
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000441static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442 // Check to see if we are dereferencing a null pointer. If so,
443 // and if not volatile-qualified, this is undefined behavior that the
444 // optimizer will delete, so warn about it. People sometimes try to use this
445 // to get a deterministic trap and are surprised by clang's behavior. This
446 // only handles the pattern "*null", which is a very syntactic check.
447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448 if (UO->getOpcode() == UO_Deref &&
449 UO->getSubExpr()->IgnoreParenCasts()->
450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451 !UO->getType().isVolatileQualified()) {
452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453 S.PDiag(diag::warn_indirection_through_null)
454 << UO->getSubExpr()->getSourceRange());
455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456 S.PDiag(diag::note_indirection_through_null));
457 }
458}
459
John Wiegley429bb272011-04-08 18:41:53 +0000460ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000461 // Handle any placeholder expressions which made it here.
462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
465 E = result.take();
466 }
467
John McCall0ae287a2010-12-01 04:43:34 +0000468 // C++ [conv.lval]p1:
469 // A glvalue of a non-function, non-array type T can be
470 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000472
John McCall409fa9a2010-12-06 20:48:59 +0000473 QualType T = E->getType();
474 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000475
John McCall409fa9a2010-12-06 20:48:59 +0000476 // We don't want to throw lvalue-to-rvalue casts on top of
477 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000479 (E->getType() == Context.OverloadTy ||
480 T->isDependentType() ||
481 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000482 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000483
484 // The C standard is actually really unclear on this point, and
485 // DR106 tells us what the result should be but not why. It's
486 // generally best to say that void types just doesn't undergo
487 // lvalue-to-rvalue at all. Note that expressions of unqualified
488 // 'void' type are never l-values, but qualified void can be.
489 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000490 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000491
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000492 CheckForNullPointerDereference(*this, E);
493
John McCall409fa9a2010-12-06 20:48:59 +0000494 // C++ [conv.lval]p1:
495 // [...] If T is a non-class type, the type of the prvalue is the
496 // cv-unqualified version of T. Otherwise, the type of the
497 // rvalue is T.
498 //
499 // C99 6.3.2.1p2:
500 // If the lvalue has qualified type, the value has the unqualified
501 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000502 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000503 if (T.hasQualifiers())
504 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000505
Eli Friedmand2cce132012-02-02 23:15:15 +0000506 UpdateMarkingForLValueToRValue(E);
507
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000508 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
509 E, 0, VK_RValue));
510
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000511 // C11 6.3.2.1p2:
512 // ... if the lvalue has atomic type, the value has the non-atomic version
513 // of the type of the lvalue ...
514 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
515 T = Atomic->getValueType().getUnqualifiedType();
516 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
517 Res.get(), 0, VK_RValue));
518 }
519
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000521}
522
John Wiegley429bb272011-04-08 18:41:53 +0000523ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
524 ExprResult Res = DefaultFunctionArrayConversion(E);
525 if (Res.isInvalid())
526 return ExprError();
527 Res = DefaultLvalueConversion(Res.take());
528 if (Res.isInvalid())
529 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000530 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000531}
532
533
Chris Lattnere7a2e912008-07-25 21:10:04 +0000534/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000535/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000536/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000537/// apply if the array is an argument to the sizeof or address (&) operators.
538/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000539ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000540 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000541 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
542 if (Res.isInvalid())
543 return Owned(E);
544 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000547 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000548
549 // Half FP is a bit different: it's a storage-only type, meaning that any
550 // "use" of it should be promoted to float.
551 if (Ty->isHalfType())
552 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
553
John McCall0ae287a2010-12-01 04:43:34 +0000554 // Try to perform integral promotions if the object has a theoretically
555 // promotable type.
556 if (Ty->isIntegralOrUnscopedEnumerationType()) {
557 // C99 6.3.1.1p2:
558 //
559 // The following may be used in an expression wherever an int or
560 // unsigned int may be used:
561 // - an object or expression with an integer type whose integer
562 // conversion rank is less than or equal to the rank of int
563 // and unsigned int.
564 // - A bit-field of type _Bool, int, signed int, or unsigned int.
565 //
566 // If an int can represent all values of the original type, the
567 // value is converted to an int; otherwise, it is converted to an
568 // unsigned int. These are called the integer promotions. All
569 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000570
John McCall0ae287a2010-12-01 04:43:34 +0000571 QualType PTy = Context.isPromotableBitField(E);
572 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000573 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
574 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000575 }
576 if (Ty->isPromotableIntegerType()) {
577 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000578 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
579 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000580 }
Eli Friedman04e83572009-08-20 04:21:42 +0000581 }
John Wiegley429bb272011-04-08 18:41:53 +0000582 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000583}
584
Chris Lattner05faf172008-07-25 22:25:12 +0000585/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000586/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000587/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000588ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
589 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000590 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000591
John Wiegley429bb272011-04-08 18:41:53 +0000592 ExprResult Res = UsualUnaryConversions(E);
593 if (Res.isInvalid())
594 return Owned(E);
595 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000596
Chris Lattner05faf172008-07-25 22:25:12 +0000597 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000598 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000599 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
600
John McCall96a914a2011-08-27 22:06:17 +0000601 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000602 // promotion, even on class types, but note:
603 // C++11 [conv.lval]p2:
604 // When an lvalue-to-rvalue conversion occurs in an unevaluated
605 // operand or a subexpression thereof the value contained in the
606 // referenced object is not accessed. Otherwise, if the glvalue
607 // has a class type, the conversion copy-initializes a temporary
608 // of type T from the glvalue and the result of the conversion
609 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000610 // FIXME: add some way to gate this entire thing for correctness in
611 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000612 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000613 ExprResult Temp = PerformCopyInitialization(
614 InitializedEntity::InitializeTemporary(E->getType()),
615 E->getExprLoc(),
616 Owned(E));
617 if (Temp.isInvalid())
618 return ExprError();
619 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000620 }
621
John Wiegley429bb272011-04-08 18:41:53 +0000622 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000623}
624
Richard Smith831421f2012-06-25 20:30:08 +0000625/// Determine the degree of POD-ness for an expression.
626/// Incomplete types are considered POD, since this check can be performed
627/// when we're in an unevaluated context.
628Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000629 if (Ty->isIncompleteType()) {
630 if (Ty->isObjCObjectType())
631 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000632 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000633 }
634
635 if (Ty.isCXX98PODType(Context))
636 return VAK_Valid;
637
Richard Smith831421f2012-06-25 20:30:08 +0000638 // C++0x [expr.call]p7:
639 // Passing a potentially-evaluated argument of class type (Clause 9)
640 // having a non-trivial copy constructor, a non-trivial move constructor,
641 // or a non-trivial destructor, with no corresponding parameter,
642 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000643 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
644 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
645 if (Record->hasTrivialCopyConstructor() &&
646 Record->hasTrivialMoveConstructor() &&
647 Record->hasTrivialDestructor())
648 return VAK_ValidInCXX11;
649
650 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
651 return VAK_Valid;
652 return VAK_Invalid;
653}
654
655bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
656 // Don't allow one to pass an Objective-C interface to a vararg.
657 const QualType & Ty = E->getType();
658
659 // Complain about passing non-POD types through varargs.
660 switch (isValidVarArgType(Ty)) {
661 case VAK_Valid:
662 break;
663 case VAK_ValidInCXX11:
664 DiagRuntimeBehavior(E->getLocStart(), 0,
665 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
666 << E->getType() << CT);
667 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000668 case VAK_Invalid: {
669 if (Ty->isObjCObjectType())
670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
672 << Ty << CT);
673
Richard Smith831421f2012-06-25 20:30:08 +0000674 return DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
676 << getLangOpts().CPlusPlus0x << Ty << CT);
677 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000678 }
Richard Smith831421f2012-06-25 20:30:08 +0000679 // c++ rules are enforced elsewhere.
680 return false;
681}
682
Chris Lattner312531a2009-04-12 08:11:20 +0000683/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000684/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000685ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000686 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000687 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000688 // Strip the unbridged-cast placeholder expression off, if applicable.
689 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
690 (CT == VariadicMethod ||
691 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
692 E = stripARCUnbridgedCast(E);
693
694 // Otherwise, do normal placeholder checking.
695 } else {
696 ExprResult ExprRes = CheckPlaceholderExpr(E);
697 if (ExprRes.isInvalid())
698 return ExprError();
699 E = ExprRes.take();
700 }
701 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000702
John McCall5acb0c92011-10-17 18:40:02 +0000703 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000704 if (ExprRes.isInvalid())
705 return ExprError();
706 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Richard Smith831421f2012-06-25 20:30:08 +0000708 // Diagnostics regarding non-POD argument types are
709 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000710 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000711 // Turn this into a trap.
712 CXXScopeSpec SS;
713 SourceLocation TemplateKWLoc;
714 UnqualifiedId Name;
715 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
716 E->getLocStart());
717 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
718 Name, true, false);
719 if (TrapFn.isInvalid())
720 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000721
Richard Smith831421f2012-06-25 20:30:08 +0000722 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
723 E->getLocStart(), MultiExprArg(),
724 E->getLocEnd());
725 if (Call.isInvalid())
726 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000727
Richard Smith831421f2012-06-25 20:30:08 +0000728 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
729 Call.get(), E);
730 if (Comma.isInvalid())
731 return ExprError();
732 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000733 }
Richard Smith831421f2012-06-25 20:30:08 +0000734
David Blaikie4e4d0842012-03-11 07:00:24 +0000735 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000736 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000737 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000738 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000739
John Wiegley429bb272011-04-08 18:41:53 +0000740 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000741}
742
Richard Trieu8289f492011-09-02 20:58:51 +0000743/// \brief Converts an integer to complex float type. Helper function of
744/// UsualArithmeticConversions()
745///
746/// \return false if the integer expression is an integer type and is
747/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000748static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
749 ExprResult &ComplexExpr,
750 QualType IntTy,
751 QualType ComplexTy,
752 bool SkipCast) {
753 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
754 if (SkipCast) return false;
755 if (IntTy->isIntegerType()) {
756 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
757 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000759 CK_FloatingRealToComplex);
760 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000761 assert(IntTy->isComplexIntegerType());
762 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000763 CK_IntegralComplexToFloatingComplex);
764 }
765 return false;
766}
767
768/// \brief Takes two complex float types and converts them to the same type.
769/// Helper function of UsualArithmeticConversions()
770static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000771handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
772 ExprResult &RHS, QualType LHSType,
773 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000774 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000776
777 if (order < 0) {
778 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783 if (order > 0)
784 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000785 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
786 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000787}
788
789/// \brief Converts otherExpr to complex float and promotes complexExpr if
790/// necessary. Helper function of UsualArithmeticConversions()
791static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 ExprResult &ComplexExpr,
793 ExprResult &OtherExpr,
794 QualType ComplexTy,
795 QualType OtherTy,
796 bool ConvertComplexExpr,
797 bool ConvertOtherExpr) {
798 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000799
800 // If just the complexExpr is complex, the otherExpr needs to be converted,
801 // and the complexExpr might need to be promoted.
802 if (order > 0) { // complexExpr is wider
803 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000804 if (ConvertOtherExpr) {
805 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
807 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000808 CK_FloatingRealToComplex);
809 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000811 }
812
813 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000814 QualType result = (order == 0 ? ComplexTy :
815 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000816
817 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000818 if (ConvertOtherExpr)
819 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000820 CK_FloatingRealToComplex);
821
822 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000823 if (ConvertComplexExpr && order < 0)
824 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000825 CK_FloatingComplexCast);
826
827 return result;
828}
829
830/// \brief Handle arithmetic conversion with complex types. Helper function of
831/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000832static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
833 ExprResult &RHS, QualType LHSType,
834 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000835 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000836 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000837 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000838 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000839 return LHSType;
840 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000841 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000842 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000843
844 // This handles complex/complex, complex/float, or float/complex.
845 // When both operands are complex, the shorter operand is converted to the
846 // type of the longer, and that is the type of the result. This corresponds
847 // to what is done when combining two real floating-point operands.
848 // The fun begins when size promotion occur across type domains.
849 // From H&S 6.3.4: When one operand is complex and the other is a real
850 // floating-point type, the less precise type is converted, within it's
851 // real or complex domain, to the precision of the other type. For example,
852 // when combining a "long double" with a "double _Complex", the
853 // "double _Complex" is promoted to "long double _Complex".
854
Richard Trieucafd30b2011-09-06 18:25:09 +0000855 bool LHSComplexFloat = LHSType->isComplexType();
856 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000857
858 // If both are complex, just cast to the more precise type.
859 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000860 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
861 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000862 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000863
864 // If only one operand is complex, promote it if necessary and convert the
865 // other operand to complex.
866 if (LHSComplexFloat)
867 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000868 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000869 /*convertOtherExpr*/ true);
870
871 assert(RHSComplexFloat);
872 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000873 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000874 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000875}
876
877/// \brief Hande arithmetic conversion from integer to float. Helper function
878/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000879static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
880 ExprResult &IntExpr,
881 QualType FloatTy, QualType IntTy,
882 bool ConvertFloat, bool ConvertInt) {
883 if (IntTy->isIntegerType()) {
884 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000885 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000886 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000887 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000889 }
890
891 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000892 assert(IntTy->isComplexIntegerType());
893 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000894
895 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000896 if (ConvertInt)
897 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000898 CK_IntegralComplexToFloatingComplex);
899
900 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (ConvertFloat)
902 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000903 CK_FloatingRealToComplex);
904
905 return result;
906}
907
908/// \brief Handle arithmethic conversion with floating point types. Helper
909/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000910static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
911 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000912 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000913 bool LHSFloat = LHSType->isRealFloatingType();
914 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000915
916 // If we have two real floating types, convert the smaller operand
917 // to the bigger result.
918 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000919 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000920 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000921 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
922 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000923 }
924
925 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000926 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
928 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000929 }
930
931 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000933 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000934 /*convertInt=*/ true);
935 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000936 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000937 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000938 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000939}
940
941/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000942/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000943// FIXME: if the operands are (int, _Complex long), we currently
944// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000945static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
946 ExprResult &RHS, QualType LHSType,
947 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000948 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000949 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
950 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000951
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000952 if (LHSComplexInt && RHSComplexInt) {
953 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
954 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000955 assert(order && "inequal types with equal element ordering");
956 if (order > 0) {
957 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000958 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
959 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960 }
961
Richard Trieuccd891a2011-09-09 01:45:06 +0000962 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000963 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
964 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000965 }
966
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000967 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000968 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000969 // FIXME: This needs to take integer ranks into account
970 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
971 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000972 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
973 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000974 }
975
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000976 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000977 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000978 // FIXME: This needs to take integer ranks into account
979 if (!IsCompAssign) {
980 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
981 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000983 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000984 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000985}
986
987/// \brief Handle integer arithmetic conversions. Helper function of
988/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
990 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000991 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000992 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000993 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
994 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
995 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
996 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000997 // Same signedness; use the higher-ranked type
998 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1000 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001001 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001002 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1003 return RHSType;
1004 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001005 // The unsigned type has greater than or equal rank to the
1006 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 if (RHSSigned) {
1008 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1009 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001010 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001011 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1012 return RHSType;
1013 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001014 // The two types are different widths; if we are here, that
1015 // means the signed type is larger than the unsigned type, so
1016 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001017 if (LHSSigned) {
1018 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1019 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001020 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1022 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001023 } else {
1024 // The signed type is higher-ranked than the unsigned type,
1025 // but isn't actually any bigger (like unsigned int and long
1026 // on most 32-bit systems). Use the unsigned type corresponding
1027 // to the signed type.
1028 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001029 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1030 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001031 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001033 return result;
1034 }
1035}
1036
Chris Lattnere7a2e912008-07-25 21:10:04 +00001037/// UsualArithmeticConversions - Performs various conversions that are common to
1038/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001039/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001040/// responsible for emitting appropriate error diagnostics.
1041/// FIXME: verify the conversion rules for "complex int" are consistent with
1042/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001043QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001044 bool IsCompAssign) {
1045 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001046 LHS = UsualUnaryConversions(LHS.take());
1047 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001048 return QualType();
1049 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001050
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 RHS = UsualUnaryConversions(RHS.take());
1052 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001053 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001054
Mike Stump1eb44332009-09-09 15:08:12 +00001055 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001056 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001057 QualType LHSType =
1058 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1059 QualType RHSType =
1060 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001061
Eli Friedman860a3192012-06-16 02:19:17 +00001062 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1063 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1064 LHSType = AtomicLHS->getValueType();
1065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001066 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType == RHSType)
1068 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001069
1070 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1071 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001073 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001074
John McCallcf33b242010-11-13 08:17:45 +00001075 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001076 QualType LHSUnpromotedType = LHSType;
1077 if (LHSType->isPromotableIntegerType())
1078 LHSType = Context.getPromotedIntegerType(LHSType);
1079 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001080 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001081 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001082 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001083 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001084
John McCallcf33b242010-11-13 08:17:45 +00001085 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001086 if (LHSType == RHSType)
1087 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001088
1089 // At this point, we have two different arithmetic types.
1090
1091 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001092 if (LHSType->isComplexType() || RHSType->isComplexType())
1093 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001094 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001095
1096 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001097 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1098 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001099 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001100
1101 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001102 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001103 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001104 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001105
1106 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001107 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001108 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001109}
1110
Chris Lattnere7a2e912008-07-25 21:10:04 +00001111//===----------------------------------------------------------------------===//
1112// Semantic Analysis for various Expression Types
1113//===----------------------------------------------------------------------===//
1114
1115
Peter Collingbournef111d932011-04-15 00:35:48 +00001116ExprResult
1117Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1118 SourceLocation DefaultLoc,
1119 SourceLocation RParenLoc,
1120 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001121 MultiTypeArg ArgTypes,
1122 MultiExprArg ArgExprs) {
1123 unsigned NumAssocs = ArgTypes.size();
1124 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001125
Benjamin Kramer5354e772012-08-23 23:38:35 +00001126 ParsedType *ParsedTypes = ArgTypes.data();
1127 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001128
1129 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1130 for (unsigned i = 0; i < NumAssocs; ++i) {
1131 if (ParsedTypes[i])
1132 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1133 else
1134 Types[i] = 0;
1135 }
1136
1137 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1138 ControllingExpr, Types, Exprs,
1139 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001140 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001141 return ER;
1142}
1143
1144ExprResult
1145Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1146 SourceLocation DefaultLoc,
1147 SourceLocation RParenLoc,
1148 Expr *ControllingExpr,
1149 TypeSourceInfo **Types,
1150 Expr **Exprs,
1151 unsigned NumAssocs) {
1152 bool TypeErrorFound = false,
1153 IsResultDependent = ControllingExpr->isTypeDependent(),
1154 ContainsUnexpandedParameterPack
1155 = ControllingExpr->containsUnexpandedParameterPack();
1156
1157 for (unsigned i = 0; i < NumAssocs; ++i) {
1158 if (Exprs[i]->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]) {
1162 if (Types[i]->getType()->containsUnexpandedParameterPack())
1163 ContainsUnexpandedParameterPack = true;
1164
1165 if (Types[i]->getType()->isDependentType()) {
1166 IsResultDependent = true;
1167 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001168 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001169 // complete object type other than a variably modified type."
1170 unsigned D = 0;
1171 if (Types[i]->getType()->isIncompleteType())
1172 D = diag::err_assoc_type_incomplete;
1173 else if (!Types[i]->getType()->isObjectType())
1174 D = diag::err_assoc_type_nonobject;
1175 else if (Types[i]->getType()->isVariablyModifiedType())
1176 D = diag::err_assoc_type_variably_modified;
1177
1178 if (D != 0) {
1179 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1180 << Types[i]->getTypeLoc().getSourceRange()
1181 << Types[i]->getType();
1182 TypeErrorFound = true;
1183 }
1184
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001185 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001186 // selection shall specify compatible types."
1187 for (unsigned j = i+1; j < NumAssocs; ++j)
1188 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1189 Context.typesAreCompatible(Types[i]->getType(),
1190 Types[j]->getType())) {
1191 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1192 diag::err_assoc_compatible_types)
1193 << Types[j]->getTypeLoc().getSourceRange()
1194 << Types[j]->getType()
1195 << Types[i]->getType();
1196 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1197 diag::note_compat_assoc)
1198 << Types[i]->getTypeLoc().getSourceRange()
1199 << Types[i]->getType();
1200 TypeErrorFound = true;
1201 }
1202 }
1203 }
1204 }
1205 if (TypeErrorFound)
1206 return ExprError();
1207
1208 // If we determined that the generic selection is result-dependent, don't
1209 // try to compute the result expression.
1210 if (IsResultDependent)
1211 return Owned(new (Context) GenericSelectionExpr(
1212 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001213 llvm::makeArrayRef(Types, NumAssocs),
1214 llvm::makeArrayRef(Exprs, NumAssocs),
1215 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001216
Chris Lattner5f9e2722011-07-23 10:55:15 +00001217 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001218 unsigned DefaultIndex = -1U;
1219 for (unsigned i = 0; i < NumAssocs; ++i) {
1220 if (!Types[i])
1221 DefaultIndex = i;
1222 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1223 Types[i]->getType()))
1224 CompatIndices.push_back(i);
1225 }
1226
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001227 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001228 // type compatible with at most one of the types named in its generic
1229 // association list."
1230 if (CompatIndices.size() > 1) {
1231 // We strip parens here because the controlling expression is typically
1232 // parenthesized in macro definitions.
1233 ControllingExpr = ControllingExpr->IgnoreParens();
1234 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1235 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1236 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001237 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001238 E = CompatIndices.end(); I != E; ++I) {
1239 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1240 diag::note_compat_assoc)
1241 << Types[*I]->getTypeLoc().getSourceRange()
1242 << Types[*I]->getType();
1243 }
1244 return ExprError();
1245 }
1246
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001247 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001248 // its controlling expression shall have type compatible with exactly one of
1249 // the types named in its generic association list."
1250 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1251 // We strip parens here because the controlling expression is typically
1252 // parenthesized in macro definitions.
1253 ControllingExpr = ControllingExpr->IgnoreParens();
1254 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1255 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1256 return ExprError();
1257 }
1258
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001259 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001260 // type name that is compatible with the type of the controlling expression,
1261 // then the result expression of the generic selection is the expression
1262 // in that generic association. Otherwise, the result expression of the
1263 // generic selection is the expression in the default generic association."
1264 unsigned ResultIndex =
1265 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1266
1267 return Owned(new (Context) GenericSelectionExpr(
1268 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001269 llvm::makeArrayRef(Types, NumAssocs),
1270 llvm::makeArrayRef(Exprs, NumAssocs),
1271 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001272 ResultIndex));
1273}
1274
Richard Smithdd66be72012-03-08 01:34:56 +00001275/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1276/// location of the token and the offset of the ud-suffix within it.
1277static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1278 unsigned Offset) {
1279 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001281}
1282
Richard Smith36f5cfe2012-03-09 08:00:36 +00001283/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1284/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1285static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1286 IdentifierInfo *UDSuffix,
1287 SourceLocation UDSuffixLoc,
1288 ArrayRef<Expr*> Args,
1289 SourceLocation LitEndLoc) {
1290 assert(Args.size() <= 2 && "too many arguments for literal operator");
1291
1292 QualType ArgTy[2];
1293 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1294 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1295 if (ArgTy[ArgIdx]->isArrayType())
1296 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1297 }
1298
1299 DeclarationName OpName =
1300 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1301 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1302 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1303
1304 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1305 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1306 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1307 return ExprError();
1308
1309 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1310}
1311
Steve Narofff69936d2007-09-16 03:34:24 +00001312/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001313/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1314/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1315/// multiple tokens. However, the common case is that StringToks points to one
1316/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001317///
John McCall60d7b3a2010-08-24 06:29:42 +00001318ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001319Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1320 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 assert(NumStringToks && "Must have at least one string!");
1322
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001323 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001325 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Chris Lattner5f9e2722011-07-23 10:55:15 +00001327 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 for (unsigned i = 0; i != NumStringToks; ++i)
1329 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001330
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001331 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001332 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001333 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001334 else if (Literal.isUTF16())
1335 StrTy = Context.Char16Ty;
1336 else if (Literal.isUTF32())
1337 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001338 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001339 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001340
Douglas Gregor5cee1192011-07-27 05:40:30 +00001341 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1342 if (Literal.isWide())
1343 Kind = StringLiteral::Wide;
1344 else if (Literal.isUTF8())
1345 Kind = StringLiteral::UTF8;
1346 else if (Literal.isUTF16())
1347 Kind = StringLiteral::UTF16;
1348 else if (Literal.isUTF32())
1349 Kind = StringLiteral::UTF32;
1350
Douglas Gregor77a52232008-09-12 00:47:35 +00001351 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001353 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001354
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001355 // Get an array type for the string, according to C99 6.4.5. This includes
1356 // the nul terminator character as well as the string length for pascal
1357 // strings.
1358 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001359 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001360 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001363 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1364 Kind, Literal.Pascal, StrTy,
1365 &StringTokLocs[0],
1366 StringTokLocs.size());
1367 if (Literal.getUDSuffix().empty())
1368 return Owned(Lit);
1369
1370 // We're building a user-defined literal.
1371 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001372 SourceLocation UDSuffixLoc =
1373 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1374 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001375
Richard Smith36f5cfe2012-03-09 08:00:36 +00001376 // Make sure we're allowed user-defined literals here.
1377 if (!UDLScope)
1378 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1379
Richard Smith9fcce652012-03-07 08:35:16 +00001380 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1381 // operator "" X (str, len)
1382 QualType SizeType = Context.getSizeType();
1383 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1384 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1385 StringTokLocs[0]);
1386 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001387 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1388 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
1390
John McCall60d7b3a2010-08-24 06:29:42 +00001391ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001392Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001393 SourceLocation Loc,
1394 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001395 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001396 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001397}
1398
John McCall76a40212011-02-09 01:13:10 +00001399/// BuildDeclRefExpr - Build an expression that references a
1400/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001401ExprResult
John McCall76a40212011-02-09 01:13:10 +00001402Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001403 const DeclarationNameInfo &NameInfo,
1404 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001406 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1407 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1408 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1409 CalleeTarget = IdentifyCUDATarget(Callee);
1410 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1411 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1412 << CalleeTarget << D->getIdentifier() << CallerTarget;
1413 Diag(D->getLocation(), diag::note_previous_decl)
1414 << D->getIdentifier();
1415 return ExprError();
1416 }
1417 }
1418
John McCallf4b88a42012-03-10 09:33:50 +00001419 bool refersToEnclosingScope =
1420 (CurContext != D->getDeclContext() &&
1421 D->getDeclContext()->isFunctionOrMethod());
1422
Eli Friedman5f2987c2012-02-02 03:46:19 +00001423 DeclRefExpr *E = DeclRefExpr::Create(Context,
1424 SS ? SS->getWithLocInContext(Context)
1425 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001426 SourceLocation(),
1427 D, refersToEnclosingScope,
1428 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Eli Friedman5f2987c2012-02-02 03:46:19 +00001430 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001431
Jordan Rose7a270482012-09-28 22:21:35 +00001432 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1433 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1434 DiagnosticsEngine::Level Level =
1435 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1436 E->getLocStart());
1437 if (Level != DiagnosticsEngine::Ignored)
1438 getCurFunction()->recordUseOfWeak(E);
1439 }
1440
John McCall7eb0a9e2010-11-24 05:12:34 +00001441 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001442 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1443 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001444 E->setObjectKind(OK_BitField);
1445
1446 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001447}
1448
Abramo Bagnara25777432010-08-11 22:01:17 +00001449/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001450/// possibly a list of template arguments.
1451///
1452/// If this produces template arguments, it is permitted to call
1453/// DecomposeTemplateName.
1454///
1455/// This actually loses a lot of source location information for
1456/// non-standard name kinds; we should consider preserving that in
1457/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001458void
1459Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1460 TemplateArgumentListInfo &Buffer,
1461 DeclarationNameInfo &NameInfo,
1462 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001463 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1464 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1465 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1466
Benjamin Kramer5354e772012-08-23 23:38:35 +00001467 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001468 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001469 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001470
John McCall2b5289b2010-08-23 07:28:44 +00001471 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001472 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001473 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001474 TemplateArgs = &Buffer;
1475 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001477 TemplateArgs = 0;
1478 }
1479}
1480
John McCall578b69b2009-12-16 08:11:27 +00001481/// Diagnose an empty lookup.
1482///
1483/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001484bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001485 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001486 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001487 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001488 DeclarationName Name = R.getLookupName();
1489
John McCall578b69b2009-12-16 08:11:27 +00001490 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001491 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001492 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1493 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001494 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001495 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001496 diagnostic_suggest = diag::err_undeclared_use_suggest;
1497 }
John McCall578b69b2009-12-16 08:11:27 +00001498
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001499 // If the original lookup was an unqualified lookup, fake an
1500 // unqualified lookup. This is useful when (for example) the
1501 // original lookup would not have found something because it was a
1502 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001503 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1504 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001505 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001506 if (isa<CXXRecordDecl>(DC)) {
1507 LookupQualifiedName(R, DC);
1508
1509 if (!R.empty()) {
1510 // Don't give errors about ambiguities in this lookup.
1511 R.suppressDiagnostics();
1512
Francois Pichete6226ae2011-11-17 03:44:24 +00001513 // During a default argument instantiation the CurContext points
1514 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1515 // function parameter list, hence add an explicit check.
1516 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1517 ActiveTemplateInstantiations.back().Kind ==
1518 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001519 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1520 bool isInstance = CurMethod &&
1521 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001522 DC == CurMethod->getParent() && !isDefaultArgument;
1523
John McCall578b69b2009-12-16 08:11:27 +00001524
1525 // Give a code modification hint to insert 'this->'.
1526 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1527 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001528 if (getLangOpts().MicrosoftMode)
1529 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001530 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001531 Diag(R.getNameLoc(), diagnostic) << Name
1532 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001533 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1534 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001535
1536
1537 CXXMethodDecl *DepMethod;
1538 if (CurMethod->getTemplatedKind() ==
1539 FunctionDecl::TK_FunctionTemplateSpecialization)
1540 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1541 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1542 else
1543 DepMethod = cast<CXXMethodDecl>(
1544 CurMethod->getInstantiatedFromMemberFunction());
1545 assert(DepMethod && "No template pattern found");
1546
1547 QualType DepThisType = DepMethod->getThisType(Context);
1548 CheckCXXThisCapture(R.getNameLoc());
1549 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550 R.getNameLoc(), DepThisType, false);
1551 TemplateArgumentListInfo TList;
1552 if (ULE->hasExplicitTemplateArgs())
1553 ULE->copyTemplateArgumentsInto(TList);
1554
1555 CXXScopeSpec SS;
1556 SS.Adopt(ULE->getQualifierLoc());
1557 CXXDependentScopeMemberExpr *DepExpr =
1558 CXXDependentScopeMemberExpr::Create(
1559 Context, DepThis, DepThisType, true, SourceLocation(),
1560 SS.getWithLocInContext(Context),
1561 ULE->getTemplateKeywordLoc(), 0,
1562 R.getLookupNameInfo(),
1563 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1564 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001565 } else {
John McCall578b69b2009-12-16 08:11:27 +00001566 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001567 }
John McCall578b69b2009-12-16 08:11:27 +00001568
1569 // Do we really want to note all of these?
1570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1572
Francois Pichete6226ae2011-11-17 03:44:24 +00001573 // Return true if we are inside a default argument instantiation
1574 // and the found name refers to an instance member function, otherwise
1575 // the function calling DiagnoseEmptyLookup will try to create an
1576 // implicit member call and this is wrong for default argument.
1577 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1578 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1579 return true;
1580 }
1581
John McCall578b69b2009-12-16 08:11:27 +00001582 // Tell the callee to try to recover.
1583 return false;
1584 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001585
1586 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001587 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001588
1589 // In Microsoft mode, if we are performing lookup from within a friend
1590 // function definition declared at class scope then we must set
1591 // DC to the lexical parent to be able to search into the parent
1592 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001593 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001594 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1595 DC->getLexicalParent()->isRecord())
1596 DC = DC->getLexicalParent();
1597 else
1598 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001599 }
1600
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001601 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001602 TypoCorrection Corrected;
1603 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001604 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001605 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1606 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 R.setLookupName(Corrected.getCorrection());
1608
Hans Wennborg701d1e72011-07-12 08:45:31 +00001609 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001610 if (Corrected.isOverloaded()) {
1611 OverloadCandidateSet OCS(R.getNameLoc());
1612 OverloadCandidateSet::iterator Best;
1613 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1614 CDEnd = Corrected.end();
1615 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001616 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001617 dyn_cast<FunctionTemplateDecl>(*CD))
1618 AddTemplateOverloadCandidate(
1619 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001621 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1622 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1623 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001624 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001625 }
1626 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1627 case OR_Success:
1628 ND = Best->Function;
1629 break;
1630 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001631 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001632 }
1633 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001634 R.addDecl(ND);
1635 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001636 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1638 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001639 else
1640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001641 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00001643 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1644 CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001645 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001646 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001647 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001648
1649 // Tell the callee to try to recover.
1650 return false;
1651 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001652
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001653 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001654 // FIXME: If we ended up with a typo for a type name or
1655 // Objective-C class name, we're in trouble because the parser
1656 // is in the wrong place to recover. Suggest the typo
1657 // correction, but don't make it a fix-it since we're not going
1658 // to recover well anyway.
1659 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001660 Diag(R.getNameLoc(), diagnostic_suggest)
1661 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001662 else
1663 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001664 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001665 << SS.getRange();
1666
1667 // Don't try to recover; it won't work.
1668 return true;
1669 }
1670 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001671 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001672 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001673 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001674 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001675 else
Douglas Gregord203a162010-01-01 00:15:04 +00001676 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001677 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001678 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001679 return true;
1680 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001681 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001682 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001683
1684 // Emit a special diagnostic for failed member lookups.
1685 // FIXME: computing the declaration context might fail here (?)
1686 if (!SS.isEmpty()) {
1687 Diag(R.getNameLoc(), diag::err_no_member)
1688 << Name << computeDeclContext(SS, false)
1689 << SS.getRange();
1690 return true;
1691 }
1692
John McCall578b69b2009-12-16 08:11:27 +00001693 // Give up, we can't recover.
1694 Diag(R.getNameLoc(), diagnostic) << Name;
1695 return true;
1696}
1697
John McCall60d7b3a2010-08-24 06:29:42 +00001698ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001699 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001700 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001701 UnqualifiedId &Id,
1702 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001703 bool IsAddressOfOperand,
1704 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001705 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001706 "cannot be direct & operand and have a trailing lparen");
1707
1708 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001709 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001710
John McCall129e2df2009-11-30 22:42:35 +00001711 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001712
1713 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001714 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001715 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001716 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001717
Abramo Bagnara25777432010-08-11 22:01:17 +00001718 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001719 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001720 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001721
John McCallf7a1a742009-11-24 19:00:30 +00001722 // C++ [temp.dep.expr]p3:
1723 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001724 // -- an identifier that was declared with a dependent type,
1725 // (note: handled after lookup)
1726 // -- a template-id that is dependent,
1727 // (note: handled in BuildTemplateIdExpr)
1728 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001729 // -- a nested-name-specifier that contains a class-name that
1730 // names a dependent type.
1731 // Determine whether this is a member of an unknown specialization;
1732 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001733 bool DependentID = false;
1734 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1735 Name.getCXXNameType()->isDependentType()) {
1736 DependentID = true;
1737 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001738 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001739 if (RequireCompleteDeclContext(SS, DC))
1740 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001741 } else {
1742 DependentID = true;
1743 }
1744 }
1745
Chris Lattner337e5502011-02-18 01:27:55 +00001746 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001749
John McCallf7a1a742009-11-24 19:00:30 +00001750 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001751 LookupResult R(*this, NameInfo,
1752 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1753 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001755 // Lookup the template name again to correctly establish the context in
1756 // which it was found. This is really unfortunate as we already did the
1757 // lookup to determine that it was a template name in the first place. If
1758 // this becomes a performance hit, we can work harder to preserve those
1759 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001760 bool MemberOfUnknownSpecialization;
1761 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1762 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001763
1764 if (MemberOfUnknownSpecialization ||
1765 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001766 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1767 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001768 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001769 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001770 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001772 // If the result might be in a dependent base class, this is a dependent
1773 // id-expression.
1774 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001775 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1776 IsAddressOfOperand, TemplateArgs);
1777
John McCallf7a1a742009-11-24 19:00:30 +00001778 // If this reference is in an Objective-C method, then we need to do
1779 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001780 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001781 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001782 if (E.isInvalid())
1783 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Chris Lattner337e5502011-02-18 01:27:55 +00001785 if (Expr *Ex = E.takeAs<Expr>())
1786 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001787 }
Chris Lattner8a934232008-03-31 00:36:02 +00001788 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001789
John McCallf7a1a742009-11-24 19:00:30 +00001790 if (R.isAmbiguous())
1791 return ExprError();
1792
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001793 // Determine whether this name might be a candidate for
1794 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001795 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001796
John McCallf7a1a742009-11-24 19:00:30 +00001797 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001799 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001800 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001801 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1802 if (D) R.addDecl(D);
1803 }
1804
1805 // If this name wasn't predeclared and if this is not a function
1806 // call, diagnose the problem.
1807 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001808
1809 // In Microsoft mode, if we are inside a template class member function
1810 // and we can't resolve an identifier then assume the identifier is type
1811 // dependent. The goal is to postpone name lookup to instantiation time
1812 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001813 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001814 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001815 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1816 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001817
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001818 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001819 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001820 return ExprError();
1821
1822 assert(!R.empty() &&
1823 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001824
1825 // If we found an Objective-C instance variable, let
1826 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001827 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001828 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1829 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001830 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001831 // In a hopelessly buggy code, Objective-C instance variable
1832 // lookup fails and no expression will be built to reference it.
1833 if (!E.isInvalid() && !E.get())
1834 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001835 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001836 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 }
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
John McCallf7a1a742009-11-24 19:00:30 +00001840 // This is guaranteed from this point on.
1841 assert(!R.empty() || ADL);
1842
John McCallaa81e162009-12-01 22:10:20 +00001843 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001844 // C++ [class.mfct.non-static]p3:
1845 // When an id-expression that is not part of a class member access
1846 // syntax and not used to form a pointer to member is used in the
1847 // body of a non-static member function of class X, if name lookup
1848 // resolves the name in the id-expression to a non-static non-type
1849 // member of some class C, the id-expression is transformed into a
1850 // class member access expression using (*this) as the
1851 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001852 //
1853 // But we don't actually need to do this for '&' operands if R
1854 // resolved to a function or overloaded function set, because the
1855 // expression is ill-formed if it actually works out to be a
1856 // non-static member function:
1857 //
1858 // C++ [expr.ref]p4:
1859 // Otherwise, if E1.E2 refers to a non-static member function. . .
1860 // [t]he expression can be used only as the left-hand operand of a
1861 // member function call.
1862 //
1863 // There are other safeguards against such uses, but it's important
1864 // to get this right here so that we don't end up making a
1865 // spuriously dependent expression if we're inside a dependent
1866 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001867 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001868 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001869 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001870 MightBeImplicitMember = true;
1871 else if (!SS.isEmpty())
1872 MightBeImplicitMember = false;
1873 else if (R.isOverloadedResult())
1874 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001875 else if (R.isUnresolvableResult())
1876 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001877 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001878 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1879 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001880
1881 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001882 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1883 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001884 }
1885
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001886 if (TemplateArgs || TemplateKWLoc.isValid())
1887 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001888
John McCallf7a1a742009-11-24 19:00:30 +00001889 return BuildDeclarationNameExpr(SS, R, ADL);
1890}
1891
John McCall129e2df2009-11-30 22:42:35 +00001892/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1893/// declaration name, generally during template instantiation.
1894/// There's a large number of things which don't need to be done along
1895/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001896ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001897Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001898 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001899 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001900 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
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
1913 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001914 Diag(NameInfo.getLoc(), diag::err_no_member)
1915 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001916 return ExprError();
1917 }
1918
1919 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1920}
1921
1922/// LookupInObjCMethod - The parser has read a name in, and Sema has
1923/// detected that we're currently inside an ObjC method. Perform some
1924/// additional lookup.
1925///
1926/// Ideally, most of this would be done by lookup, but there's
1927/// actually quite a lot of extra work involved.
1928///
1929/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001930ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001931Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001932 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001933 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001934 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001935
John McCallf7a1a742009-11-24 19:00:30 +00001936 // There are two cases to handle here. 1) scoped lookup could have failed,
1937 // in which case we should look for an ivar. 2) scoped lookup could have
1938 // found a decl, but that decl is outside the current instance method (i.e.
1939 // a global variable). In these two cases, we do a lookup for an ivar with
1940 // this name, if the lookup sucedes, we replace it our current decl.
1941
1942 // If we're in a class method, we don't normally want to look for
1943 // ivars. But if we don't find anything else, and there's an
1944 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001945 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001946
1947 bool LookForIvars;
1948 if (Lookup.empty())
1949 LookForIvars = true;
1950 else if (IsClassMethod)
1951 LookForIvars = false;
1952 else
1953 LookForIvars = (Lookup.isSingleResult() &&
1954 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001955 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001956 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001957 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001958 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001959 ObjCIvarDecl *IV = 0;
1960 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001961 // Diagnose using an ivar in a class method.
1962 if (IsClassMethod)
1963 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1964 << IV->getDeclName());
1965
1966 // If we're referencing an invalid decl, just return this as a silent
1967 // error node. The error diagnostic was already emitted on the decl.
1968 if (IV->isInvalidDecl())
1969 return ExprError();
1970
1971 // Check if referencing a field with __attribute__((deprecated)).
1972 if (DiagnoseUseOfDecl(IV, Loc))
1973 return ExprError();
1974
1975 // Diagnose the use of an ivar outside of the declaring class.
1976 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001977 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001978 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001979 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1980
1981 // FIXME: This should use a new expr for a direct reference, don't
1982 // turn this into Self->ivar, just return a BareIVarExpr or something.
1983 IdentifierInfo &II = Context.Idents.get("self");
1984 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001985 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001986 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001987 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001988 SourceLocation TemplateKWLoc;
1989 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001990 SelfName, false, false);
1991 if (SelfExpr.isInvalid())
1992 return ExprError();
1993
John Wiegley429bb272011-04-08 18:41:53 +00001994 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1995 if (SelfExpr.isInvalid())
1996 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001997
Eli Friedman5f2987c2012-02-02 03:46:19 +00001998 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001999
2000 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2001 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2002 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002003
2004 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2005 Loc,
2006 SelfExpr.take(),
2007 true, true);
2008
2009 if (getLangOpts().ObjCAutoRefCount) {
2010 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2011 DiagnosticsEngine::Level Level =
2012 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2013 if (Level != DiagnosticsEngine::Ignored)
2014 getCurFunction()->recordUseOfWeak(Result);
2015 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002016 if (CurContext->isClosure())
2017 Diag(Loc, diag::warn_implicitly_retains_self)
2018 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002019 }
2020
2021 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002022 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002023 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002024 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002025 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2026 ObjCInterfaceDecl *ClassDeclared;
2027 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2028 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002029 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002030 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2031 }
John McCallf7a1a742009-11-24 19:00:30 +00002032 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002033 } else if (Lookup.isSingleResult() &&
2034 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2035 // If accessing a stand-alone ivar in a class method, this is an error.
2036 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2037 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2038 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002039 }
2040
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002041 if (Lookup.empty() && II && AllowBuiltinCreation) {
2042 // FIXME. Consolidate this with similar code in LookupName.
2043 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002044 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002045 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2046 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2047 S, Lookup.isForRedeclaration(),
2048 Lookup.getNameLoc());
2049 if (D) Lookup.addDecl(D);
2050 }
2051 }
2052 }
John McCallf7a1a742009-11-24 19:00:30 +00002053 // Sentinel value saying that we didn't do anything special.
2054 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002055}
John McCallba135432009-11-21 08:51:07 +00002056
John McCall6bb80172010-03-30 21:47:33 +00002057/// \brief Cast a base object to a member's actual type.
2058///
2059/// Logically this happens in three phases:
2060///
2061/// * First we cast from the base type to the naming class.
2062/// The naming class is the class into which we were looking
2063/// when we found the member; it's the qualifier type if a
2064/// qualifier was provided, and otherwise it's the base type.
2065///
2066/// * Next we cast from the naming class to the declaring class.
2067/// If the member we found was brought into a class's scope by
2068/// a using declaration, this is that class; otherwise it's
2069/// the class declaring the member.
2070///
2071/// * Finally we cast from the declaring class to the "true"
2072/// declaring class of the member. This conversion does not
2073/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002074ExprResult
2075Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002076 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002077 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002078 NamedDecl *Member) {
2079 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2080 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002081 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002082
Douglas Gregor5fccd362010-03-03 23:55:11 +00002083 QualType DestRecordType;
2084 QualType DestType;
2085 QualType FromRecordType;
2086 QualType FromType = From->getType();
2087 bool PointerConversions = false;
2088 if (isa<FieldDecl>(Member)) {
2089 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002090
Douglas Gregor5fccd362010-03-03 23:55:11 +00002091 if (FromType->getAs<PointerType>()) {
2092 DestType = Context.getPointerType(DestRecordType);
2093 FromRecordType = FromType->getPointeeType();
2094 PointerConversions = true;
2095 } else {
2096 DestType = DestRecordType;
2097 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002098 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002099 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2100 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002101 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002102
Douglas Gregor5fccd362010-03-03 23:55:11 +00002103 DestType = Method->getThisType(Context);
2104 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002105
Douglas Gregor5fccd362010-03-03 23:55:11 +00002106 if (FromType->getAs<PointerType>()) {
2107 FromRecordType = FromType->getPointeeType();
2108 PointerConversions = true;
2109 } else {
2110 FromRecordType = FromType;
2111 DestType = DestRecordType;
2112 }
2113 } else {
2114 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002115 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002116 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002117
Douglas Gregor5fccd362010-03-03 23:55:11 +00002118 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002119 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002120
Douglas Gregor5fccd362010-03-03 23:55:11 +00002121 // If the unqualified types are the same, no conversion is necessary.
2122 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002123 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002124
John McCall6bb80172010-03-30 21:47:33 +00002125 SourceRange FromRange = From->getSourceRange();
2126 SourceLocation FromLoc = FromRange.getBegin();
2127
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002128 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002129
Douglas Gregor5fccd362010-03-03 23:55:11 +00002130 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002131 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002132 // class name.
2133 //
2134 // If the member was a qualified name and the qualified referred to a
2135 // specific base subobject type, we'll cast to that intermediate type
2136 // first and then to the object in which the member is declared. That allows
2137 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2138 //
2139 // class Base { public: int x; };
2140 // class Derived1 : public Base { };
2141 // class Derived2 : public Base { };
2142 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2143 //
2144 // void VeryDerived::f() {
2145 // x = 17; // error: ambiguous base subobjects
2146 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2147 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002148 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002149 QualType QType = QualType(Qualifier->getAsType(), 0);
2150 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2151 assert(QType->isRecordType() && "lookup done with non-record type");
2152
2153 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2154
2155 // In C++98, the qualifier type doesn't actually have to be a base
2156 // type of the object type, in which case we just ignore it.
2157 // Otherwise build the appropriate casts.
2158 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002159 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002160 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002161 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002162 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002163
Douglas Gregor5fccd362010-03-03 23:55:11 +00002164 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002165 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002166 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2167 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002168
2169 FromType = QType;
2170 FromRecordType = QRecordType;
2171
2172 // If the qualifier type was the same as the destination type,
2173 // we're done.
2174 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002175 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002176 }
2177 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002178
John McCall6bb80172010-03-30 21:47:33 +00002179 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002180
John McCall6bb80172010-03-30 21:47:33 +00002181 // If we actually found the member through a using declaration, cast
2182 // down to the using declaration's type.
2183 //
2184 // Pointer equality is fine here because only one declaration of a
2185 // class ever has member declarations.
2186 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2187 assert(isa<UsingShadowDecl>(FoundDecl));
2188 QualType URecordType = Context.getTypeDeclType(
2189 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2190
2191 // We only need to do this if the naming-class to declaring-class
2192 // conversion is non-trivial.
2193 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2194 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002195 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002196 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002197 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002198 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002199
John McCall6bb80172010-03-30 21:47:33 +00002200 QualType UType = URecordType;
2201 if (PointerConversions)
2202 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002203 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2204 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002205 FromType = UType;
2206 FromRecordType = URecordType;
2207 }
2208
2209 // We don't do access control for the conversion from the
2210 // declaring class to the true declaring class.
2211 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002212 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002213
John McCallf871d0c2010-08-07 06:22:56 +00002214 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002215 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2216 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002217 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002218 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002219
John Wiegley429bb272011-04-08 18:41:53 +00002220 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2221 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002222}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002223
John McCallf7a1a742009-11-24 19:00:30 +00002224bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002225 const LookupResult &R,
2226 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002227 // Only when used directly as the postfix-expression of a call.
2228 if (!HasTrailingLParen)
2229 return false;
2230
2231 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002232 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002233 return false;
2234
2235 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002236 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002237 return false;
2238
2239 // Turn off ADL when we find certain kinds of declarations during
2240 // normal lookup:
2241 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2242 NamedDecl *D = *I;
2243
2244 // C++0x [basic.lookup.argdep]p3:
2245 // -- a declaration of a class member
2246 // Since using decls preserve this property, we check this on the
2247 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002248 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002249 return false;
2250
2251 // C++0x [basic.lookup.argdep]p3:
2252 // -- a block-scope function declaration that is not a
2253 // using-declaration
2254 // NOTE: we also trigger this for function templates (in fact, we
2255 // don't check the decl type at all, since all other decl types
2256 // turn off ADL anyway).
2257 if (isa<UsingShadowDecl>(D))
2258 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2259 else if (D->getDeclContext()->isFunctionOrMethod())
2260 return false;
2261
2262 // C++0x [basic.lookup.argdep]p3:
2263 // -- a declaration that is neither a function or a function
2264 // template
2265 // And also for builtin functions.
2266 if (isa<FunctionDecl>(D)) {
2267 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2268
2269 // But also builtin functions.
2270 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2271 return false;
2272 } else if (!isa<FunctionTemplateDecl>(D))
2273 return false;
2274 }
2275
2276 return true;
2277}
2278
2279
John McCallba135432009-11-21 08:51:07 +00002280/// Diagnoses obvious problems with the use of the given declaration
2281/// as an expression. This is only actually called for lookups that
2282/// were not overloaded, and it doesn't promise that the declaration
2283/// will in fact be used.
2284static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002285 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002286 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2287 return true;
2288 }
2289
2290 if (isa<ObjCInterfaceDecl>(D)) {
2291 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2292 return true;
2293 }
2294
2295 if (isa<NamespaceDecl>(D)) {
2296 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2297 return true;
2298 }
2299
2300 return false;
2301}
2302
John McCall60d7b3a2010-08-24 06:29:42 +00002303ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002304Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002305 LookupResult &R,
2306 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002307 // If this is a single, fully-resolved result and we don't need ADL,
2308 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002309 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002310 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2311 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002312
2313 // We only need to check the declaration if there's exactly one
2314 // result, because in the overloaded case the results can only be
2315 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002316 if (R.isSingleResult() &&
2317 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002318 return ExprError();
2319
John McCallc373d482010-01-27 01:50:18 +00002320 // Otherwise, just build an unresolved lookup expression. Suppress
2321 // any lookup-related diagnostics; we'll hash these out later, when
2322 // we've picked a target.
2323 R.suppressDiagnostics();
2324
John McCallba135432009-11-21 08:51:07 +00002325 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002326 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002327 SS.getWithLocInContext(Context),
2328 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002329 NeedsADL, R.isOverloadedResult(),
2330 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002331
2332 return Owned(ULE);
2333}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002334
John McCallba135432009-11-21 08:51:07 +00002335/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002336ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002337Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002338 const DeclarationNameInfo &NameInfo,
2339 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002340 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002341 assert(!isa<FunctionTemplateDecl>(D) &&
2342 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002343
Abramo Bagnara25777432010-08-11 22:01:17 +00002344 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002345 if (CheckDeclInExpr(*this, Loc, D))
2346 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002347
Douglas Gregor9af2f522009-12-01 16:58:18 +00002348 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2349 // Specifically diagnose references to class templates that are missing
2350 // a template argument list.
2351 Diag(Loc, diag::err_template_decl_ref)
2352 << Template << SS.getRange();
2353 Diag(Template->getLocation(), diag::note_template_decl_here);
2354 return ExprError();
2355 }
2356
2357 // Make sure that we're referring to a value.
2358 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2359 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002360 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002361 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002362 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002363 return ExprError();
2364 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002365
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002366 // Check whether this declaration can be used. Note that we suppress
2367 // this check when we're going to perform argument-dependent lookup
2368 // on this function name, because this might not be the function
2369 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002370 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002371 return ExprError();
2372
Steve Naroffdd972f22008-09-05 22:11:13 +00002373 // Only create DeclRefExpr's for valid Decl's.
2374 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002375 return ExprError();
2376
John McCall5808ce42011-02-03 08:15:49 +00002377 // Handle members of anonymous structs and unions. If we got here,
2378 // and the reference is to a class member indirect field, then this
2379 // must be the subject of a pointer-to-member expression.
2380 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2381 if (!indirectField->isCXXClassMember())
2382 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2383 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002384
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002385 {
John McCall76a40212011-02-09 01:13:10 +00002386 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002387 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002388
2389 switch (D->getKind()) {
2390 // Ignore all the non-ValueDecl kinds.
2391#define ABSTRACT_DECL(kind)
2392#define VALUE(type, base)
2393#define DECL(type, base) \
2394 case Decl::type:
2395#include "clang/AST/DeclNodes.inc"
2396 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002397
2398 // These shouldn't make it here.
2399 case Decl::ObjCAtDefsField:
2400 case Decl::ObjCIvar:
2401 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002402
2403 // Enum constants are always r-values and never references.
2404 // Unresolved using declarations are dependent.
2405 case Decl::EnumConstant:
2406 case Decl::UnresolvedUsingValue:
2407 valueKind = VK_RValue;
2408 break;
2409
2410 // Fields and indirect fields that got here must be for
2411 // pointer-to-member expressions; we just call them l-values for
2412 // internal consistency, because this subexpression doesn't really
2413 // exist in the high-level semantics.
2414 case Decl::Field:
2415 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002416 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002417 "building reference to field in C?");
2418
2419 // These can't have reference type in well-formed programs, but
2420 // for internal consistency we do this anyway.
2421 type = type.getNonReferenceType();
2422 valueKind = VK_LValue;
2423 break;
2424
2425 // Non-type template parameters are either l-values or r-values
2426 // depending on the type.
2427 case Decl::NonTypeTemplateParm: {
2428 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2429 type = reftype->getPointeeType();
2430 valueKind = VK_LValue; // even if the parameter is an r-value reference
2431 break;
2432 }
2433
2434 // For non-references, we need to strip qualifiers just in case
2435 // the template parameter was declared as 'const int' or whatever.
2436 valueKind = VK_RValue;
2437 type = type.getUnqualifiedType();
2438 break;
2439 }
2440
2441 case Decl::Var:
2442 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002443 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002444 !type.hasQualifiers() &&
2445 type->isVoidType()) {
2446 valueKind = VK_RValue;
2447 break;
2448 }
2449 // fallthrough
2450
2451 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002452 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002453 // These are always l-values.
2454 valueKind = VK_LValue;
2455 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002456
Douglas Gregor68932842012-02-18 05:51:20 +00002457 // FIXME: Does the addition of const really only apply in
2458 // potentially-evaluated contexts? Since the variable isn't actually
2459 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002460 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002461 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2462 if (!CapturedType.isNull())
2463 type = CapturedType;
2464 }
2465
John McCall76a40212011-02-09 01:13:10 +00002466 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002467 }
2468
John McCall76a40212011-02-09 01:13:10 +00002469 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002470 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2471 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2472 type = Context.BuiltinFnTy;
2473 valueKind = VK_RValue;
2474 break;
2475 }
2476 }
2477
John McCall755d8492011-04-12 00:42:48 +00002478 const FunctionType *fty = type->castAs<FunctionType>();
2479
2480 // If we're referring to a function with an __unknown_anytype
2481 // result type, make the entire expression __unknown_anytype.
2482 if (fty->getResultType() == Context.UnknownAnyTy) {
2483 type = Context.UnknownAnyTy;
2484 valueKind = VK_RValue;
2485 break;
2486 }
2487
John McCall76a40212011-02-09 01:13:10 +00002488 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002489 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002490 valueKind = VK_LValue;
2491 break;
2492 }
2493
2494 // C99 DR 316 says that, if a function type comes from a
2495 // function definition (without a prototype), that type is only
2496 // used for checking compatibility. Therefore, when referencing
2497 // the function, we pretend that we don't have the full function
2498 // type.
John McCall755d8492011-04-12 00:42:48 +00002499 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2500 isa<FunctionProtoType>(fty))
2501 type = Context.getFunctionNoProtoType(fty->getResultType(),
2502 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002503
2504 // Functions are r-values in C.
2505 valueKind = VK_RValue;
2506 break;
2507 }
2508
2509 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002510 // If we're referring to a method with an __unknown_anytype
2511 // result type, make the entire expression __unknown_anytype.
2512 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002513 if (const FunctionProtoType *proto
2514 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002515 if (proto->getResultType() == Context.UnknownAnyTy) {
2516 type = Context.UnknownAnyTy;
2517 valueKind = VK_RValue;
2518 break;
2519 }
2520
John McCall76a40212011-02-09 01:13:10 +00002521 // C++ methods are l-values if static, r-values if non-static.
2522 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2523 valueKind = VK_LValue;
2524 break;
2525 }
2526 // fallthrough
2527
2528 case Decl::CXXConversion:
2529 case Decl::CXXDestructor:
2530 case Decl::CXXConstructor:
2531 valueKind = VK_RValue;
2532 break;
2533 }
2534
2535 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2536 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002537}
2538
John McCall755d8492011-04-12 00:42:48 +00002539ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002540 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002541
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002543 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002544 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2545 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002546 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002547 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002549
Chris Lattnerfa28b302008-01-12 08:14:25 +00002550 // Pre-defined identifiers are of type char[x], where x is the length of the
2551 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Anders Carlsson3a082d82009-09-08 18:24:21 +00002553 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002554 if (!currentDecl && getCurBlock())
2555 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002556 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002557 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002558 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002559 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002560
Anders Carlsson773f3972009-09-11 01:22:35 +00002561 QualType ResTy;
2562 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2563 ResTy = Context.DependentTy;
2564 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002565 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002566
Anders Carlsson773f3972009-09-11 01:22:35 +00002567 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002568 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002569 ResTy = Context.WCharTy.withConst();
2570 else
2571 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002572 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2573 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002574 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002575}
2576
Richard Smith36f5cfe2012-03-09 08:00:36 +00002577ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002578 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002579 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002580 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002581 if (Invalid)
2582 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002583
Benjamin Kramerddeea562010-02-27 13:44:12 +00002584 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002585 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002587 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002588
Chris Lattnere8337df2009-12-30 21:19:39 +00002589 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002590 if (Literal.isWide())
2591 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002592 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002593 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002594 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002595 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002596 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002597 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002598 else
2599 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002600
Douglas Gregor5cee1192011-07-27 05:40:30 +00002601 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2602 if (Literal.isWide())
2603 Kind = CharacterLiteral::Wide;
2604 else if (Literal.isUTF16())
2605 Kind = CharacterLiteral::UTF16;
2606 else if (Literal.isUTF32())
2607 Kind = CharacterLiteral::UTF32;
2608
Richard Smithdd66be72012-03-08 01:34:56 +00002609 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2610 Tok.getLocation());
2611
2612 if (Literal.getUDSuffix().empty())
2613 return Owned(Lit);
2614
2615 // We're building a user-defined literal.
2616 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2617 SourceLocation UDSuffixLoc =
2618 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2619
Richard Smith36f5cfe2012-03-09 08:00:36 +00002620 // Make sure we're allowed user-defined literals here.
2621 if (!UDLScope)
2622 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2623
Richard Smithdd66be72012-03-08 01:34:56 +00002624 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2625 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002626 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2627 llvm::makeArrayRef(&Lit, 1),
2628 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002629}
2630
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002631ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2632 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2633 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2634 Context.IntTy, Loc));
2635}
2636
Richard Smithb453ad32012-03-08 08:45:32 +00002637static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2638 QualType Ty, SourceLocation Loc) {
2639 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2640
2641 using llvm::APFloat;
2642 APFloat Val(Format);
2643
2644 APFloat::opStatus result = Literal.GetFloatValue(Val);
2645
2646 // Overflow is always an error, but underflow is only an error if
2647 // we underflowed to zero (APFloat reports denormals as underflow).
2648 if ((result & APFloat::opOverflow) ||
2649 ((result & APFloat::opUnderflow) && Val.isZero())) {
2650 unsigned diagnostic;
2651 SmallString<20> buffer;
2652 if (result & APFloat::opOverflow) {
2653 diagnostic = diag::warn_float_overflow;
2654 APFloat::getLargest(Format).toString(buffer);
2655 } else {
2656 diagnostic = diag::warn_float_underflow;
2657 APFloat::getSmallest(Format).toString(buffer);
2658 }
2659
2660 S.Diag(Loc, diagnostic)
2661 << Ty
2662 << StringRef(buffer.data(), buffer.size());
2663 }
2664
2665 bool isExact = (result == APFloat::opOK);
2666 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2667}
2668
Richard Smith36f5cfe2012-03-09 08:00:36 +00002669ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002670 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002671 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002673 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002674 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 }
Ted Kremenek28396602009-01-13 23:19:12 +00002676
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002677 SmallString<128> SpellingBuffer;
2678 // NumericLiteralParser wants to overread by one character. Add padding to
2679 // the buffer in case the token is copied to the buffer. If getSpelling()
2680 // returns a StringRef to the memory buffer, it should have a null char at
2681 // the EOF, so it is also safe.
2682 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002683
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002685 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002686 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002687 if (Invalid)
2688 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002689
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002690 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002692 return ExprError();
2693
Richard Smithb453ad32012-03-08 08:45:32 +00002694 if (Literal.hasUDSuffix()) {
2695 // We're building a user-defined literal.
2696 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2697 SourceLocation UDSuffixLoc =
2698 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2699
Richard Smith36f5cfe2012-03-09 08:00:36 +00002700 // Make sure we're allowed user-defined literals here.
2701 if (!UDLScope)
2702 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002703
Richard Smith36f5cfe2012-03-09 08:00:36 +00002704 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002705 if (Literal.isFloatingLiteral()) {
2706 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2707 // long double, the literal is treated as a call of the form
2708 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002709 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002710 } else {
2711 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2712 // unsigned long long, the literal is treated as a call of the form
2713 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002714 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002715 }
2716
Richard Smith36f5cfe2012-03-09 08:00:36 +00002717 DeclarationName OpName =
2718 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2719 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2720 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2721
2722 // Perform literal operator lookup to determine if we're building a raw
2723 // literal or a cooked one.
2724 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2725 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2726 /*AllowRawAndTemplate*/true)) {
2727 case LOLR_Error:
2728 return ExprError();
2729
2730 case LOLR_Cooked: {
2731 Expr *Lit;
2732 if (Literal.isFloatingLiteral()) {
2733 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2734 } else {
2735 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2736 if (Literal.GetIntegerValue(ResultVal))
2737 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2738 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2739 Tok.getLocation());
2740 }
2741 return BuildLiteralOperatorCall(R, OpNameInfo,
2742 llvm::makeArrayRef(&Lit, 1),
2743 Tok.getLocation());
2744 }
2745
2746 case LOLR_Raw: {
2747 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2748 // literal is treated as a call of the form
2749 // operator "" X ("n")
2750 SourceLocation TokLoc = Tok.getLocation();
2751 unsigned Length = Literal.getUDSuffixOffset();
2752 QualType StrTy = Context.getConstantArrayType(
2753 Context.CharTy, llvm::APInt(32, Length + 1),
2754 ArrayType::Normal, 0);
2755 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002756 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002757 /*Pascal*/false, StrTy, &TokLoc, 1);
2758 return BuildLiteralOperatorCall(R, OpNameInfo,
2759 llvm::makeArrayRef(&Lit, 1), TokLoc);
2760 }
2761
2762 case LOLR_Template:
2763 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2764 // template), L is treated as a call fo the form
2765 // operator "" X <'c1', 'c2', ... 'ck'>()
2766 // where n is the source character sequence c1 c2 ... ck.
2767 TemplateArgumentListInfo ExplicitArgs;
2768 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2769 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2770 llvm::APSInt Value(CharBits, CharIsUnsigned);
2771 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002772 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002773 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002774 TemplateArgumentLocInfo ArgInfo;
2775 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2776 }
2777 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2778 Tok.getLocation(), &ExplicitArgs);
2779 }
2780
2781 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002782 }
2783
Chris Lattner5d661452007-08-26 03:42:43 +00002784 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002785
Chris Lattner5d661452007-08-26 03:42:43 +00002786 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002787 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002788 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002789 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002790 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002791 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002792 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002793 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002794
Richard Smithb453ad32012-03-08 08:45:32 +00002795 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002796
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002797 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002798 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002799 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002800 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002801 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002802 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002803 }
2804 }
Chris Lattner5d661452007-08-26 03:42:43 +00002805 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002806 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002807 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002808 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002809
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002810 // 'long long' is a C99 or C++11 feature.
2811 if (!getLangOpts().C99 && Literal.isLongLong) {
2812 if (getLangOpts().CPlusPlus)
2813 Diag(Tok.getLocation(),
2814 getLangOpts().CPlusPlus0x ?
2815 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2816 else
2817 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2818 }
Neil Boothb9449512007-08-29 22:00:19 +00002819
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002821 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2822 // The microsoft literal suffix extensions support 128-bit literals, which
2823 // may be wider than [u]intmax_t.
2824 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2825 MaxWidth = 128;
2826 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002827
Reid Spencer5f016e22007-07-11 17:01:13 +00002828 if (Literal.GetIntegerValue(ResultVal)) {
2829 // If this value didn't fit into uintmax_t, warn and force to ull.
2830 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002831 Ty = Context.UnsignedLongLongTy;
2832 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002833 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002834 } else {
2835 // If this value fits into a ULL, try to figure out what else it fits into
2836 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002837
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2839 // be an unsigned int.
2840 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2841
2842 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002843 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002844 if (!Literal.isLong && !Literal.isLongLong) {
2845 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002846 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002847
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 // Does it fit in a unsigned int?
2849 if (ResultVal.isIntN(IntSize)) {
2850 // Does it fit in a signed int?
2851 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002852 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002854 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002855 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002858
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002860 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002861 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002862
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 // Does it fit in a unsigned long?
2864 if (ResultVal.isIntN(LongSize)) {
2865 // Does it fit in a signed long?
2866 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002867 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002869 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002870 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002872 }
2873
Stephen Canonb9e05f12012-05-03 22:49:43 +00002874 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002875 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002876 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002877
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 // Does it fit in a unsigned long long?
2879 if (ResultVal.isIntN(LongLongSize)) {
2880 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002881 // To be compatible with MSVC, hex integer literals ending with the
2882 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002883 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002884 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002885 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002887 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002888 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 }
2890 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002891
2892 // If it doesn't fit in unsigned long long, and we're using Microsoft
2893 // extensions, then its a 128-bit integer literal.
2894 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2895 if (Literal.isUnsigned)
2896 Ty = Context.UnsignedInt128Ty;
2897 else
2898 Ty = Context.Int128Ty;
2899 Width = 128;
2900 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002901
Reid Spencer5f016e22007-07-11 17:01:13 +00002902 // If we still couldn't decide a type, we probably have something that
2903 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002904 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002906 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002907 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002908 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002909
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002910 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002911 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002913 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002914 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002915
Chris Lattner5d661452007-08-26 03:42:43 +00002916 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2917 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002918 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002919 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002920
2921 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002922}
2923
Richard Trieuccd891a2011-09-09 01:45:06 +00002924ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002925 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002926 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002927}
2928
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002929static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2930 SourceLocation Loc,
2931 SourceRange ArgRange) {
2932 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2933 // scalar or vector data type argument..."
2934 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2935 // type (C99 6.2.5p18) or void.
2936 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2937 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2938 << T << ArgRange;
2939 return true;
2940 }
2941
2942 assert((T->isVoidType() || !T->isIncompleteType()) &&
2943 "Scalar types should always be complete");
2944 return false;
2945}
2946
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002947static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2948 SourceLocation Loc,
2949 SourceRange ArgRange,
2950 UnaryExprOrTypeTrait TraitKind) {
2951 // C99 6.5.3.4p1:
2952 if (T->isFunctionType()) {
2953 // alignof(function) is allowed as an extension.
2954 if (TraitKind == UETT_SizeOf)
2955 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2956 return false;
2957 }
2958
2959 // Allow sizeof(void)/alignof(void) as an extension.
2960 if (T->isVoidType()) {
2961 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2962 return false;
2963 }
2964
2965 return true;
2966}
2967
2968static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2969 SourceLocation Loc,
2970 SourceRange ArgRange,
2971 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002972 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2973 // runtime doesn't allow it.
2974 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002975 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2976 << T << (TraitKind == UETT_SizeOf)
2977 << ArgRange;
2978 return true;
2979 }
2980
2981 return false;
2982}
2983
Chandler Carruth9d342d02011-05-26 08:53:10 +00002984/// \brief Check the constrains on expression operands to unary type expression
2985/// and type traits.
2986///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002987/// Completes any types necessary and validates the constraints on the operand
2988/// expression. The logic mostly mirrors the type-based overload, but may modify
2989/// the expression as it completes the type for that expression through template
2990/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002991bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002992 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002993 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002994
2995 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2996 // the result is the size of the referenced type."
2997 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2998 // result shall be the alignment of the referenced type."
2999 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3000 ExprTy = Ref->getPointeeType();
3001
3002 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003003 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3004 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003005
3006 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003007 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3008 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003009 return false;
3010
Richard Trieuccd891a2011-09-09 01:45:06 +00003011 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003012 diag::err_sizeof_alignof_incomplete_type,
3013 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003014 return true;
3015
3016 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003017 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003018 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3019 ExprTy = Ref->getPointeeType();
3020
Richard Trieuccd891a2011-09-09 01:45:06 +00003021 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3022 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003023 return true;
3024
Nico Webercf739922011-06-15 02:47:03 +00003025 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003026 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003027 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3028 QualType OType = PVD->getOriginalType();
3029 QualType Type = PVD->getType();
3030 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003031 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003032 << Type << OType;
3033 Diag(PVD->getLocation(), diag::note_declared_at);
3034 }
3035 }
3036 }
3037 }
3038
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003039 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003040}
3041
3042/// \brief Check the constraints on operands to unary expression and type
3043/// traits.
3044///
3045/// This will complete any types necessary, and validate the various constraints
3046/// on those operands.
3047///
Reid Spencer5f016e22007-07-11 17:01:13 +00003048/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003049/// C99 6.3.2.1p[2-4] all state:
3050/// Except when it is the operand of the sizeof operator ...
3051///
3052/// C++ [expr.sizeof]p4
3053/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3054/// standard conversions are not applied to the operand of sizeof.
3055///
3056/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003057bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003058 SourceLocation OpLoc,
3059 SourceRange ExprRange,
3060 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003061 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003062 return false;
3063
Sebastian Redl5d484e82009-11-23 17:18:46 +00003064 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3065 // the result is the size of the referenced type."
3066 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3067 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003068 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3069 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003070
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003071 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003072 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003073
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003074 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003075 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003076 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003077 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Richard Trieuccd891a2011-09-09 01:45:06 +00003079 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003080 diag::err_sizeof_alignof_incomplete_type,
3081 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003082 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Richard Trieuccd891a2011-09-09 01:45:06 +00003084 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003085 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003086 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Chris Lattner1efaa952009-04-24 00:30:45 +00003088 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003089}
3090
Chandler Carruth9d342d02011-05-26 08:53:10 +00003091static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003092 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003093
Mike Stump1eb44332009-09-09 15:08:12 +00003094 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003095 if (isa<DeclRefExpr>(E))
3096 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003097
3098 // Cannot know anything else if the expression is dependent.
3099 if (E->isTypeDependent())
3100 return false;
3101
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003102 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003103 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3104 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003105 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003106 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003107
3108 // Alignment of a field access is always okay, so long as it isn't a
3109 // bit-field.
3110 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003111 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003112 return false;
3113
Chandler Carruth9d342d02011-05-26 08:53:10 +00003114 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003115}
3116
Chandler Carruth9d342d02011-05-26 08:53:10 +00003117bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003118 E = E->IgnoreParens();
3119
3120 // Cannot know anything else if the expression is dependent.
3121 if (E->isTypeDependent())
3122 return false;
3123
Chandler Carruth9d342d02011-05-26 08:53:10 +00003124 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003125}
3126
Douglas Gregorba498172009-03-13 21:01:28 +00003127/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003128ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3130 SourceLocation OpLoc,
3131 UnaryExprOrTypeTrait ExprKind,
3132 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003133 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003134 return ExprError();
3135
John McCalla93c9342009-12-07 02:54:59 +00003136 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003137
Douglas Gregorba498172009-03-13 21:01:28 +00003138 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003139 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003140 return ExprError();
3141
3142 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003143 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3144 Context.getSizeType(),
3145 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003146}
3147
3148/// \brief Build a sizeof or alignof expression given an expression
3149/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003150ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003151Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3152 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003153 ExprResult PE = CheckPlaceholderExpr(E);
3154 if (PE.isInvalid())
3155 return ExprError();
3156
3157 E = PE.get();
3158
Douglas Gregorba498172009-03-13 21:01:28 +00003159 // Verify that the operand is valid.
3160 bool isInvalid = false;
3161 if (E->isTypeDependent()) {
3162 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003163 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003164 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003165 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003166 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003167 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003168 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003169 isInvalid = true;
3170 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003171 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003172 }
3173
3174 if (isInvalid)
3175 return ExprError();
3176
Eli Friedman71b8fb52012-01-21 01:01:51 +00003177 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3178 PE = TranformToPotentiallyEvaluated(E);
3179 if (PE.isInvalid()) return ExprError();
3180 E = PE.take();
3181 }
3182
Douglas Gregorba498172009-03-13 21:01:28 +00003183 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003184 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003185 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003186 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003187}
3188
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003189/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3190/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003191/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003192ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003193Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003194 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003195 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003197 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003198
Richard Trieuccd891a2011-09-09 01:45:06 +00003199 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003200 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003201 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003202 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003203 }
Sebastian Redl05189992008-11-11 17:56:53 +00003204
Douglas Gregorba498172009-03-13 21:01:28 +00003205 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003206 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003207 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003208}
3209
John Wiegley429bb272011-04-08 18:41:53 +00003210static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003211 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003212 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003213 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003214
John McCallf6a16482010-12-04 03:47:34 +00003215 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003216 if (V.get()->getObjectKind() != OK_Ordinary) {
3217 V = S.DefaultLvalueConversion(V.take());
3218 if (V.isInvalid())
3219 return QualType();
3220 }
John McCallf6a16482010-12-04 03:47:34 +00003221
Chris Lattnercc26ed72007-08-26 05:39:26 +00003222 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003223 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003224 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003225
Chris Lattnercc26ed72007-08-26 05:39:26 +00003226 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003227 if (V.get()->getType()->isArithmeticType())
3228 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003229
John McCall2cd11fe2010-10-12 02:09:17 +00003230 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003231 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003232 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003233 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003234 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003235 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003236 }
3237
Chris Lattnercc26ed72007-08-26 05:39:26 +00003238 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003239 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003240 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003241 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003242}
3243
3244
Reid Spencer5f016e22007-07-11 17:01:13 +00003245
John McCall60d7b3a2010-08-24 06:29:42 +00003246ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003247Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003248 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003249 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003250 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003251 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003252 case tok::plusplus: Opc = UO_PostInc; break;
3253 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003254 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003255
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003256 // Since this might is a postfix expression, get rid of ParenListExprs.
3257 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3258 if (Result.isInvalid()) return ExprError();
3259 Input = Result.take();
3260
John McCall9ae2f072010-08-23 23:25:46 +00003261 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003262}
3263
John McCall1503f0d2012-07-31 05:14:30 +00003264/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3265///
3266/// \return true on error
3267static bool checkArithmeticOnObjCPointer(Sema &S,
3268 SourceLocation opLoc,
3269 Expr *op) {
3270 assert(op->getType()->isObjCObjectPointerType());
3271 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3272 return false;
3273
3274 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3275 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3276 << op->getSourceRange();
3277 return true;
3278}
3279
John McCall60d7b3a2010-08-24 06:29:42 +00003280ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003281Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3282 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003283 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003284 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003285 if (Result.isInvalid()) return ExprError();
3286 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003287
John McCall9ae2f072010-08-23 23:25:46 +00003288 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003289
David Blaikie4e4d0842012-03-11 07:00:24 +00003290 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003291 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003292 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003293 Context.DependentTy,
3294 VK_LValue, OK_Ordinary,
3295 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003296 }
3297
David Blaikie4e4d0842012-03-11 07:00:24 +00003298 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003299 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003300 LHSExp->getType()->isEnumeralType() ||
3301 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003302 RHSExp->getType()->isEnumeralType()) &&
3303 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003304 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003305 }
3306
John McCall9ae2f072010-08-23 23:25:46 +00003307 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003308}
3309
John McCall60d7b3a2010-08-24 06:29:42 +00003310ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003311Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003312 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003313 Expr *LHSExp = Base;
3314 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003315
Chris Lattner12d9ff62007-07-16 00:14:47 +00003316 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003317 if (!LHSExp->getType()->getAs<VectorType>()) {
3318 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3319 if (Result.isInvalid())
3320 return ExprError();
3321 LHSExp = Result.take();
3322 }
3323 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3324 if (Result.isInvalid())
3325 return ExprError();
3326 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003327
Chris Lattner12d9ff62007-07-16 00:14:47 +00003328 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003329 ExprValueKind VK = VK_LValue;
3330 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003331
Reid Spencer5f016e22007-07-11 17:01:13 +00003332 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003333 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003334 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003335 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003336 Expr *BaseExpr, *IndexExpr;
3337 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003338 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3339 BaseExpr = LHSExp;
3340 IndexExpr = RHSExp;
3341 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003342 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003343 BaseExpr = LHSExp;
3344 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003345 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003346 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003347 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003348 BaseExpr = LHSExp;
3349 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003350
3351 // Use custom logic if this should be the pseudo-object subscript
3352 // expression.
3353 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3354 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3355
Steve Naroff14108da2009-07-10 23:34:53 +00003356 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003357 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3358 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3359 << ResultType << BaseExpr->getSourceRange();
3360 return ExprError();
3361 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003362 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3363 // Handle the uncommon case of "123[Ptr]".
3364 BaseExpr = RHSExp;
3365 IndexExpr = LHSExp;
3366 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003367 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003368 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003369 // Handle the uncommon case of "123[Ptr]".
3370 BaseExpr = RHSExp;
3371 IndexExpr = LHSExp;
3372 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003373 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3374 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3375 << ResultType << BaseExpr->getSourceRange();
3376 return ExprError();
3377 }
John McCall183700f2009-09-21 23:43:11 +00003378 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003379 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003380 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003381 VK = LHSExp->getValueKind();
3382 if (VK != VK_RValue)
3383 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003384
Chris Lattner12d9ff62007-07-16 00:14:47 +00003385 // FIXME: need to deal with const...
3386 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003387 } else if (LHSTy->isArrayType()) {
3388 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003389 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003390 // wasn't promoted because of the C90 rule that doesn't
3391 // allow promoting non-lvalue arrays. Warn, then
3392 // force the promotion here.
3393 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3394 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003395 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3396 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003397 LHSTy = LHSExp->getType();
3398
3399 BaseExpr = LHSExp;
3400 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003401 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003402 } else if (RHSTy->isArrayType()) {
3403 // Same as previous, except for 123[f().a] case
3404 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3405 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003406 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3407 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003408 RHSTy = RHSExp->getType();
3409
3410 BaseExpr = RHSExp;
3411 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003412 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003413 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003414 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3415 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003416 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003418 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003419 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3420 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003421
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003422 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003423 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3424 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003425 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3426
Douglas Gregore7450f52009-03-24 19:52:54 +00003427 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003428 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3429 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003430 // incomplete types are not object types.
3431 if (ResultType->isFunctionType()) {
3432 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3433 << ResultType << BaseExpr->getSourceRange();
3434 return ExprError();
3435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
David Blaikie4e4d0842012-03-11 07:00:24 +00003437 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003438 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003439 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3440 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003441
3442 // C forbids expressions of unqualified void type from being l-values.
3443 // See IsCForbiddenLValueType.
3444 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003445 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003446 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003447 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003448 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003449
John McCall09431682010-11-18 19:01:18 +00003450 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003451 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003452
Mike Stumpeed9cac2009-02-19 03:04:26 +00003453 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003454 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003455}
3456
John McCall60d7b3a2010-08-24 06:29:42 +00003457ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003458 FunctionDecl *FD,
3459 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003460 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003461 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003462 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003463 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003464 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003465 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003466 return ExprError();
3467 }
3468
3469 if (Param->hasUninstantiatedDefaultArg()) {
3470 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003471
Richard Smithadb1d4c2012-07-22 23:45:10 +00003472 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3473 Param);
3474
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003475 // Instantiate the expression.
3476 MultiLevelTemplateArgumentList ArgList
3477 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003478
Nico Weber08e41a62010-11-29 18:19:25 +00003479 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003480 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003481 InstantiatingTemplate Inst(*this, CallLoc, Param,
3482 ArrayRef<TemplateArgument>(Innermost.first,
3483 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003484 if (Inst)
3485 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003486
Nico Weber08e41a62010-11-29 18:19:25 +00003487 ExprResult Result;
3488 {
3489 // C++ [dcl.fct.default]p5:
3490 // The names in the [default argument] expression are bound, and
3491 // the semantic constraints are checked, at the point where the
3492 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003493 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003494 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003495 Result = SubstExpr(UninstExpr, ArgList);
3496 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003497 if (Result.isInvalid())
3498 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003500 // Check the expression as an initializer for the parameter.
3501 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003502 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003503 InitializationKind Kind
3504 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003505 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003506 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003507
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003508 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003509 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003510 if (Result.isInvalid())
3511 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003512
David Blaikiec1c07252012-04-30 18:21:31 +00003513 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003514 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003515 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003516 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003517 }
3518
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003519 // If the default expression creates temporaries, we need to
3520 // push them to the current stack of expression temporaries so they'll
3521 // be properly destroyed.
3522 // FIXME: We should really be rebuilding the default argument with new
3523 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003524 // We don't need to do that with block decls, though, because
3525 // blocks in default argument expression can never capture anything.
3526 if (isa<ExprWithCleanups>(Param->getInit())) {
3527 // Set the "needs cleanups" bit regardless of whether there are
3528 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003529 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003530
3531 // Append all the objects to the cleanup list. Right now, this
3532 // should always be a no-op, because blocks in default argument
3533 // expressions should never be able to capture anything.
3534 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3535 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003536 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003537
3538 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003539 // Just mark all of the declarations in this potentially-evaluated expression
3540 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003541 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3542 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003543 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003544}
3545
Richard Smith831421f2012-06-25 20:30:08 +00003546
3547Sema::VariadicCallType
3548Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3549 Expr *Fn) {
3550 if (Proto && Proto->isVariadic()) {
3551 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3552 return VariadicConstructor;
3553 else if (Fn && Fn->getType()->isBlockPointerType())
3554 return VariadicBlock;
3555 else if (FDecl) {
3556 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3557 if (Method->isInstance())
3558 return VariadicMethod;
3559 }
3560 return VariadicFunction;
3561 }
3562 return VariadicDoesNotApply;
3563}
3564
Douglas Gregor88a35142008-12-22 05:46:06 +00003565/// ConvertArgumentsForCall - Converts the arguments specified in
3566/// Args/NumArgs to the parameter types of the function FDecl with
3567/// function prototype Proto. Call is the call expression itself, and
3568/// Fn is the function expression. For a C++ member function, this
3569/// routine does not attempt to convert the object argument. Returns
3570/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003571bool
3572Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003573 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003574 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003575 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003576 SourceLocation RParenLoc,
3577 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003578 // Bail out early if calling a builtin with custom typechecking.
3579 // We don't need to do this in the
3580 if (FDecl)
3581 if (unsigned ID = FDecl->getBuiltinID())
3582 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3583 return false;
3584
Mike Stumpeed9cac2009-02-19 03:04:26 +00003585 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003586 // assignment, to the types of the corresponding parameter, ...
3587 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003588 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003589 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003590 unsigned FnKind = Fn->getType()->isBlockPointerType()
3591 ? 1 /* block */
3592 : (IsExecConfig ? 3 /* kernel function (exec config) */
3593 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003594
Douglas Gregor88a35142008-12-22 05:46:06 +00003595 // If too few arguments are available (and we don't have default
3596 // arguments for the remaining parameters), don't make the call.
3597 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003598 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003599 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3600 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3601 ? diag::err_typecheck_call_too_few_args_one
3602 : diag::err_typecheck_call_too_few_args_at_least_one)
3603 << FnKind
3604 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3605 else
3606 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3607 ? diag::err_typecheck_call_too_few_args
3608 : diag::err_typecheck_call_too_few_args_at_least)
3609 << FnKind
3610 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003611
3612 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003613 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003614 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3615 << FDecl;
3616
3617 return true;
3618 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003619 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003620 }
3621
3622 // If too many are passed and not variadic, error on the extras and drop
3623 // them.
3624 if (NumArgs > NumArgsInProto) {
3625 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003626 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3627 Diag(Args[NumArgsInProto]->getLocStart(),
3628 MinArgs == NumArgsInProto
3629 ? diag::err_typecheck_call_too_many_args_one
3630 : diag::err_typecheck_call_too_many_args_at_most_one)
3631 << FnKind
3632 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3633 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3634 Args[NumArgs-1]->getLocEnd());
3635 else
3636 Diag(Args[NumArgsInProto]->getLocStart(),
3637 MinArgs == NumArgsInProto
3638 ? diag::err_typecheck_call_too_many_args
3639 : diag::err_typecheck_call_too_many_args_at_most)
3640 << FnKind
3641 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3642 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3643 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003644
3645 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003646 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003647 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3648 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003649
Douglas Gregor88a35142008-12-22 05:46:06 +00003650 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003651 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003652 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003653 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003654 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003655 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003656 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3657
Daniel Dunbar96a00142012-03-09 18:35:03 +00003658 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003659 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003660 if (Invalid)
3661 return true;
3662 unsigned TotalNumArgs = AllArgs.size();
3663 for (unsigned i = 0; i < TotalNumArgs; ++i)
3664 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003665
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003666 return false;
3667}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003668
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003669bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3670 FunctionDecl *FDecl,
3671 const FunctionProtoType *Proto,
3672 unsigned FirstProtoArg,
3673 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003674 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003675 VariadicCallType CallType,
3676 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003677 unsigned NumArgsInProto = Proto->getNumArgs();
3678 unsigned NumArgsToCheck = NumArgs;
3679 bool Invalid = false;
3680 if (NumArgs != NumArgsInProto)
3681 // Use default arguments for missing arguments
3682 NumArgsToCheck = NumArgsInProto;
3683 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003684 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003685 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003686 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003687
Douglas Gregor88a35142008-12-22 05:46:06 +00003688 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003689 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003690 if (ArgIx < NumArgs) {
3691 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003692
Daniel Dunbar96a00142012-03-09 18:35:03 +00003693 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003694 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003695 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003696 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003697
Douglas Gregora188ff22009-12-22 16:09:06 +00003698 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003699 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003700 if (FDecl && i < FDecl->getNumParams())
3701 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003702
John McCall5acb0c92011-10-17 18:40:02 +00003703 // Strip the unbridged-cast placeholder expression off, if applicable.
3704 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3705 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3706 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3707 Arg = stripARCUnbridgedCast(Arg);
3708
Douglas Gregora188ff22009-12-22 16:09:06 +00003709 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003710 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003711 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3712 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003713 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003714 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003715 Owned(Arg),
3716 /*TopLevelOfInitList=*/false,
3717 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003718 if (ArgE.isInvalid())
3719 return true;
3720
3721 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003722 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003723 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003724
John McCall60d7b3a2010-08-24 06:29:42 +00003725 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003726 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003727 if (ArgExpr.isInvalid())
3728 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003729
Anders Carlsson56c5e332009-08-25 03:49:14 +00003730 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003731 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003732
3733 // Check for array bounds violations for each argument to the call. This
3734 // check only triggers warnings when the argument isn't a more complex Expr
3735 // with its own checking, such as a BinaryOperator.
3736 CheckArrayAccess(Arg);
3737
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003738 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3739 CheckStaticArrayArgument(CallLoc, Param, Arg);
3740
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003741 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003742 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003743
Douglas Gregor88a35142008-12-22 05:46:06 +00003744 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003745 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003746 // Assume that extern "C" functions with variadic arguments that
3747 // return __unknown_anytype aren't *really* variadic.
3748 if (Proto->getResultType() == Context.UnknownAnyTy &&
3749 FDecl && FDecl->isExternC()) {
3750 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3751 ExprResult arg;
3752 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3753 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3754 else
3755 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3756 Invalid |= arg.isInvalid();
3757 AllArgs.push_back(arg.take());
3758 }
3759
3760 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3761 } else {
3762 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003763 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3764 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003765 Invalid |= Arg.isInvalid();
3766 AllArgs.push_back(Arg.take());
3767 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003768 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003769
3770 // Check for array bounds violations.
3771 for (unsigned i = ArgIx; i != NumArgs; ++i)
3772 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003773 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003774 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003775}
3776
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003777static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3778 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3779 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3780 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3781 << ATL->getLocalSourceRange();
3782}
3783
3784/// CheckStaticArrayArgument - If the given argument corresponds to a static
3785/// array parameter, check that it is non-null, and that if it is formed by
3786/// array-to-pointer decay, the underlying array is sufficiently large.
3787///
3788/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3789/// array type derivation, then for each call to the function, the value of the
3790/// corresponding actual argument shall provide access to the first element of
3791/// an array with at least as many elements as specified by the size expression.
3792void
3793Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3794 ParmVarDecl *Param,
3795 const Expr *ArgExpr) {
3796 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003797 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003798 return;
3799
3800 QualType OrigTy = Param->getOriginalType();
3801
3802 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3803 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3804 return;
3805
3806 if (ArgExpr->isNullPointerConstant(Context,
3807 Expr::NPC_NeverValueDependent)) {
3808 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3809 DiagnoseCalleeStaticArrayParam(*this, Param);
3810 return;
3811 }
3812
3813 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3814 if (!CAT)
3815 return;
3816
3817 const ConstantArrayType *ArgCAT =
3818 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3819 if (!ArgCAT)
3820 return;
3821
3822 if (ArgCAT->getSize().ult(CAT->getSize())) {
3823 Diag(CallLoc, diag::warn_static_array_too_small)
3824 << ArgExpr->getSourceRange()
3825 << (unsigned) ArgCAT->getSize().getZExtValue()
3826 << (unsigned) CAT->getSize().getZExtValue();
3827 DiagnoseCalleeStaticArrayParam(*this, Param);
3828 }
3829}
3830
John McCall755d8492011-04-12 00:42:48 +00003831/// Given a function expression of unknown-any type, try to rebuild it
3832/// to have a function type.
3833static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3834
Steve Narofff69936d2007-09-16 03:34:24 +00003835/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003836/// This provides the location of the left/right parens and a list of comma
3837/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003838ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003839Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003840 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003841 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003842 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003843 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003844 if (Result.isInvalid()) return ExprError();
3845 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003846
David Blaikie4e4d0842012-03-11 07:00:24 +00003847 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003848 // If this is a pseudo-destructor expression, build the call immediately.
3849 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003850 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003851 // Pseudo-destructor calls should not have any arguments.
3852 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003853 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003854 SourceRange(ArgExprs[0]->getLocStart(),
3855 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003858 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3859 Context.VoidTy, VK_RValue,
3860 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003861 }
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Douglas Gregor17330012009-02-04 15:01:18 +00003863 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003864 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003865 // FIXME: Will need to cache the results of name lookup (including ADL) in
3866 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003867 bool Dependent = false;
3868 if (Fn->isTypeDependent())
3869 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003870 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003871 Dependent = true;
3872
Peter Collingbournee08ce652011-02-09 21:07:24 +00003873 if (Dependent) {
3874 if (ExecConfig) {
3875 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003876 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003877 Context.DependentTy, VK_RValue, RParenLoc));
3878 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003879 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003880 Context.DependentTy, VK_RValue,
3881 RParenLoc));
3882 }
3883 }
Douglas Gregor17330012009-02-04 15:01:18 +00003884
3885 // Determine whether this is a call to an object (C++ [over.call.object]).
3886 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003887 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3888 ArgExprs.data(),
3889 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003890
John McCall755d8492011-04-12 00:42:48 +00003891 if (Fn->getType() == Context.UnknownAnyTy) {
3892 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3893 if (result.isInvalid()) return ExprError();
3894 Fn = result.take();
3895 }
3896
John McCall864c0412011-04-26 20:42:42 +00003897 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003898 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3899 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003900 }
John McCall864c0412011-04-26 20:42:42 +00003901 }
John McCall129e2df2009-11-30 22:42:35 +00003902
John McCall864c0412011-04-26 20:42:42 +00003903 // Check for overloaded calls. This can happen even in C due to extensions.
3904 if (Fn->getType() == Context.OverloadTy) {
3905 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3906
Douglas Gregoree697e62011-10-13 18:10:35 +00003907 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003908 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003909 OverloadExpr *ovl = find.Expression;
3910 if (isa<UnresolvedLookupExpr>(ovl)) {
3911 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003912 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3913 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003914 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003915 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3916 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003917 }
3918 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003919 }
3920
Douglas Gregorfa047642009-02-04 00:32:51 +00003921 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003922 if (Fn->getType() == Context.UnknownAnyTy) {
3923 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3924 if (result.isInvalid()) return ExprError();
3925 Fn = result.take();
3926 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003927
Eli Friedmanefa42f72009-12-26 03:35:45 +00003928 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003929
John McCall3b4294e2009-12-16 12:17:52 +00003930 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003931 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3932 if (UnOp->getOpcode() == UO_AddrOf)
3933 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3934
John McCall3b4294e2009-12-16 12:17:52 +00003935 if (isa<DeclRefExpr>(NakedFn))
3936 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003937 else if (isa<MemberExpr>(NakedFn))
3938 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003939
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003940 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3941 ArgExprs.size(), RParenLoc, ExecConfig,
3942 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003943}
3944
3945ExprResult
3946Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003947 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003948 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3949 if (!ConfigDecl)
3950 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3951 << "cudaConfigureCall");
3952 QualType ConfigQTy = ConfigDecl->getType();
3953
3954 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003955 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003956 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003957
Peter Collingbourne1f240762011-10-02 23:49:29 +00003958 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3959 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003960}
3961
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003962/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3963///
3964/// __builtin_astype( value, dst type )
3965///
Richard Trieuccd891a2011-09-09 01:45:06 +00003966ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003967 SourceLocation BuiltinLoc,
3968 SourceLocation RParenLoc) {
3969 ExprValueKind VK = VK_RValue;
3970 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003971 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3972 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003973 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3974 return ExprError(Diag(BuiltinLoc,
3975 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003976 << DstTy
3977 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003978 << E->getSourceRange());
3979 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003980 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003981}
3982
John McCall3b4294e2009-12-16 12:17:52 +00003983/// BuildResolvedCallExpr - Build a call to a resolved expression,
3984/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003985/// unary-convert to an expression of function-pointer or
3986/// block-pointer type.
3987///
3988/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003989ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003990Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3991 SourceLocation LParenLoc,
3992 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003993 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003994 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003995 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003996 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00003997
Chris Lattner04421082008-04-08 04:40:51 +00003998 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003999 // We special-case function promotion here because we only allow promoting
4000 // builtin functions to function pointers in the callee of a call.
4001 ExprResult Result;
4002 if (BuiltinID &&
4003 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4004 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4005 CK_BuiltinFnToFnPtr).take();
4006 } else {
4007 Result = UsualUnaryConversions(Fn);
4008 }
John Wiegley429bb272011-04-08 18:41:53 +00004009 if (Result.isInvalid())
4010 return ExprError();
4011 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004012
Chris Lattner925e60d2007-12-28 05:29:59 +00004013 // Make the call expr early, before semantic checks. This guarantees cleanup
4014 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004015 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004016 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004017 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4018 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004019 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004020 Context.BoolTy,
4021 VK_RValue,
4022 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004023 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004024 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004025 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004026 Context.BoolTy,
4027 VK_RValue,
4028 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004029
John McCall8e10f3b2011-02-26 05:39:39 +00004030 // Bail out early if calling a builtin with custom typechecking.
4031 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4032 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4033
John McCall1de4d4e2011-04-07 08:22:57 +00004034 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004035 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004036 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004037 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4038 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004039 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004040 if (FuncT == 0)
4041 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4042 << Fn->getType() << Fn->getSourceRange());
4043 } else if (const BlockPointerType *BPT =
4044 Fn->getType()->getAs<BlockPointerType>()) {
4045 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4046 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004047 // Handle calls to expressions of unknown-any type.
4048 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004049 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004050 if (rewrite.isInvalid()) return ExprError();
4051 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004052 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004053 goto retry;
4054 }
4055
Sebastian Redl0eb23302009-01-19 00:08:26 +00004056 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4057 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004058 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004059
David Blaikie4e4d0842012-03-11 07:00:24 +00004060 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004061 if (Config) {
4062 // CUDA: Kernel calls must be to global functions
4063 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4064 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4065 << FDecl->getName() << Fn->getSourceRange());
4066
4067 // CUDA: Kernel function must have 'void' return type
4068 if (!FuncT->getResultType()->isVoidType())
4069 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4070 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004071 } else {
4072 // CUDA: Calls to global functions must be configured
4073 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4074 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4075 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004076 }
4077 }
4078
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004079 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004080 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004081 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004082 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004083 return ExprError();
4084
Chris Lattner925e60d2007-12-28 05:29:59 +00004085 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004086 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004087 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004088
Richard Smith831421f2012-06-25 20:30:08 +00004089 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4090 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004091 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004092 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004093 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004094 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004095 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004096
Douglas Gregor74734d52009-04-02 15:37:10 +00004097 if (FDecl) {
4098 // Check if we have too few/too many template arguments, based
4099 // on our knowledge of the function definition.
4100 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004101 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004102 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004103 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004104 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4105 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004106 }
Douglas Gregor46542412010-10-25 20:39:23 +00004107
4108 // If the function we're calling isn't a function prototype, but we have
4109 // a function prototype from a prior declaratiom, use that prototype.
4110 if (!FDecl->hasPrototype())
4111 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004112 }
4113
Steve Naroffb291ab62007-08-28 23:30:39 +00004114 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004115 for (unsigned i = 0; i != NumArgs; i++) {
4116 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004117
4118 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004119 InitializedEntity Entity
4120 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004121 Proto->getArgType(i),
4122 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004123 ExprResult ArgE = PerformCopyInitialization(Entity,
4124 SourceLocation(),
4125 Owned(Arg));
4126 if (ArgE.isInvalid())
4127 return true;
4128
4129 Arg = ArgE.takeAs<Expr>();
4130
4131 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004132 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4133
4134 if (ArgE.isInvalid())
4135 return true;
4136
4137 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004138 }
4139
Daniel Dunbar96a00142012-03-09 18:35:03 +00004140 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004141 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004142 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004143 return ExprError();
4144
Chris Lattner925e60d2007-12-28 05:29:59 +00004145 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004147 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004148
Douglas Gregor88a35142008-12-22 05:46:06 +00004149 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4150 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004151 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4152 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004153
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004154 // Check for sentinels
4155 if (NDecl)
4156 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Chris Lattner59907c42007-08-10 20:18:51 +00004158 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004159 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004160 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004161 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004162
John McCall8e10f3b2011-02-26 05:39:39 +00004163 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004164 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004165 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004166 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004167 return ExprError();
4168 }
Chris Lattner59907c42007-08-10 20:18:51 +00004169
John McCall9ae2f072010-08-23 23:25:46 +00004170 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004171}
4172
John McCall60d7b3a2010-08-24 06:29:42 +00004173ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004174Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004175 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004176 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004177 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004178 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004179
4180 TypeSourceInfo *TInfo;
4181 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4182 if (!TInfo)
4183 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4184
John McCall9ae2f072010-08-23 23:25:46 +00004185 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004186}
4187
John McCall60d7b3a2010-08-24 06:29:42 +00004188ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004189Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004190 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004191 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004192
Eli Friedman6223c222008-05-20 05:22:08 +00004193 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004194 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004195 diag::err_illegal_decl_array_incomplete_type,
4196 SourceRange(LParenLoc,
4197 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004198 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004199 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004200 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004201 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004202 } else if (!literalType->isDependentType() &&
4203 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004204 diag::err_typecheck_decl_incomplete_type,
4205 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004206 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004207
Douglas Gregor99a2e602009-12-16 01:38:02 +00004208 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004209 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004210 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004211 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004212 SourceRange(LParenLoc, RParenLoc),
4213 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004214 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004215 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4216 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004217 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004218 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004219 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004220
Chris Lattner371f2582008-12-04 23:50:19 +00004221 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004222 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004223 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004224 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004225 }
Eli Friedman08544622009-12-22 02:35:53 +00004226
John McCallf89e55a2010-11-18 06:31:45 +00004227 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004228 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004229
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004230 return MaybeBindToTemporary(
4231 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004232 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004233}
4234
John McCall60d7b3a2010-08-24 06:29:42 +00004235ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004236Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004237 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004238 // Immediately handle non-overload placeholders. Overloads can be
4239 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004240 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4241 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4242 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004243
4244 // Ignore failures; dropping the entire initializer list because
4245 // of one failure would be terrible for indexing/etc.
4246 if (result.isInvalid()) continue;
4247
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004248 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004249 }
4250 }
4251
Steve Naroff08d92e42007-09-15 18:49:24 +00004252 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004253 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004254
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004255 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4256 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004257 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004258 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004259}
4260
John McCalldc05b112011-09-10 01:16:55 +00004261/// Do an explicit extend of the given block pointer if we're in ARC.
4262static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4263 assert(E.get()->getType()->isBlockPointerType());
4264 assert(E.get()->isRValue());
4265
4266 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004267 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004268
4269 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004270 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004271 /*base path*/ 0, VK_RValue);
4272 S.ExprNeedsCleanups = true;
4273}
4274
4275/// Prepare a conversion of the given expression to an ObjC object
4276/// pointer type.
4277CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4278 QualType type = E.get()->getType();
4279 if (type->isObjCObjectPointerType()) {
4280 return CK_BitCast;
4281 } else if (type->isBlockPointerType()) {
4282 maybeExtendBlockObject(*this, E);
4283 return CK_BlockPointerToObjCPointerCast;
4284 } else {
4285 assert(type->isPointerType());
4286 return CK_CPointerToObjCPointerCast;
4287 }
4288}
4289
John McCallf3ea8cf2010-11-14 08:17:51 +00004290/// Prepares for a scalar cast, performing all the necessary stages
4291/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004292CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004293 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4294 // Also, callers should have filtered out the invalid cases with
4295 // pointers. Everything else should be possible.
4296
John Wiegley429bb272011-04-08 18:41:53 +00004297 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004298 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004299 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004300
John McCall1d9b3b22011-09-09 05:25:32 +00004301 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004302 case Type::STK_MemberPointer:
4303 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004304
John McCall1d9b3b22011-09-09 05:25:32 +00004305 case Type::STK_CPointer:
4306 case Type::STK_BlockPointer:
4307 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004308 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004309 case Type::STK_CPointer:
4310 return CK_BitCast;
4311 case Type::STK_BlockPointer:
4312 return (SrcKind == Type::STK_BlockPointer
4313 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4314 case Type::STK_ObjCObjectPointer:
4315 if (SrcKind == Type::STK_ObjCObjectPointer)
4316 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004317 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004318 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004319 maybeExtendBlockObject(*this, Src);
4320 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004321 case Type::STK_Bool:
4322 return CK_PointerToBoolean;
4323 case Type::STK_Integral:
4324 return CK_PointerToIntegral;
4325 case Type::STK_Floating:
4326 case Type::STK_FloatingComplex:
4327 case Type::STK_IntegralComplex:
4328 case Type::STK_MemberPointer:
4329 llvm_unreachable("illegal cast from pointer");
4330 }
David Blaikie7530c032012-01-17 06:56:22 +00004331 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004332
John McCalldaa8e4e2010-11-15 09:13:47 +00004333 case Type::STK_Bool: // casting from bool is like casting from an integer
4334 case Type::STK_Integral:
4335 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004336 case Type::STK_CPointer:
4337 case Type::STK_ObjCObjectPointer:
4338 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004339 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004340 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004341 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004342 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004343 case Type::STK_Bool:
4344 return CK_IntegralToBoolean;
4345 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004346 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004347 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004348 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004349 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004350 Src = ImpCastExprToType(Src.take(),
4351 DestTy->castAs<ComplexType>()->getElementType(),
4352 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004353 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004354 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004355 Src = ImpCastExprToType(Src.take(),
4356 DestTy->castAs<ComplexType>()->getElementType(),
4357 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004358 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004359 case Type::STK_MemberPointer:
4360 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004361 }
David Blaikie7530c032012-01-17 06:56:22 +00004362 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004363
John McCalldaa8e4e2010-11-15 09:13:47 +00004364 case Type::STK_Floating:
4365 switch (DestTy->getScalarTypeKind()) {
4366 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004367 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004368 case Type::STK_Bool:
4369 return CK_FloatingToBoolean;
4370 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004371 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004372 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004373 Src = ImpCastExprToType(Src.take(),
4374 DestTy->castAs<ComplexType>()->getElementType(),
4375 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004376 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004377 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004378 Src = ImpCastExprToType(Src.take(),
4379 DestTy->castAs<ComplexType>()->getElementType(),
4380 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004381 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004382 case Type::STK_CPointer:
4383 case Type::STK_ObjCObjectPointer:
4384 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004385 llvm_unreachable("valid float->pointer cast?");
4386 case Type::STK_MemberPointer:
4387 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004388 }
David Blaikie7530c032012-01-17 06:56:22 +00004389 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004390
John McCalldaa8e4e2010-11-15 09:13:47 +00004391 case Type::STK_FloatingComplex:
4392 switch (DestTy->getScalarTypeKind()) {
4393 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004394 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004395 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004396 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004397 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004398 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4399 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004400 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004401 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004402 return CK_FloatingCast;
4403 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004404 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004405 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004406 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004407 Src = ImpCastExprToType(Src.take(),
4408 SrcTy->castAs<ComplexType>()->getElementType(),
4409 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004410 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004411 case Type::STK_CPointer:
4412 case Type::STK_ObjCObjectPointer:
4413 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004414 llvm_unreachable("valid complex float->pointer cast?");
4415 case Type::STK_MemberPointer:
4416 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004417 }
David Blaikie7530c032012-01-17 06:56:22 +00004418 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004419
John McCalldaa8e4e2010-11-15 09:13:47 +00004420 case Type::STK_IntegralComplex:
4421 switch (DestTy->getScalarTypeKind()) {
4422 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004423 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004424 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004425 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004426 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004427 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4428 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004429 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004430 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004431 return CK_IntegralCast;
4432 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004433 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004434 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004435 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004436 Src = ImpCastExprToType(Src.take(),
4437 SrcTy->castAs<ComplexType>()->getElementType(),
4438 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004439 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004440 case Type::STK_CPointer:
4441 case Type::STK_ObjCObjectPointer:
4442 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004443 llvm_unreachable("valid complex int->pointer cast?");
4444 case Type::STK_MemberPointer:
4445 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004446 }
David Blaikie7530c032012-01-17 06:56:22 +00004447 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004448 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004449
John McCallf3ea8cf2010-11-14 08:17:51 +00004450 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004451}
4452
Anders Carlssonc3516322009-10-16 02:48:28 +00004453bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004454 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004455 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004456
Anders Carlssona64db8f2007-11-27 05:51:55 +00004457 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004458 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004459 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004460 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004461 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004462 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004463 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004464 } else
4465 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004466 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004467 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004468
John McCall2de56d12010-08-25 11:45:40 +00004469 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004470 return false;
4471}
4472
John Wiegley429bb272011-04-08 18:41:53 +00004473ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4474 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004475 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004476
Anders Carlsson16a89042009-10-16 05:23:41 +00004477 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004478
Nate Begeman9b10da62009-06-27 22:05:55 +00004479 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4480 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004481 // In OpenCL, casts between vectors of different types are not allowed.
4482 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004483 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004484 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004485 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004486 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004487 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004488 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004489 return ExprError();
4490 }
John McCall2de56d12010-08-25 11:45:40 +00004491 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004492 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004493 }
4494
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004495 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004496 // conversion will take place first from scalar to elt type, and then
4497 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004498 if (SrcTy->isPointerType())
4499 return Diag(R.getBegin(),
4500 diag::err_invalid_conversion_between_vector_and_scalar)
4501 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004502
4503 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004504 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004505 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004506 if (CastExprRes.isInvalid())
4507 return ExprError();
4508 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004509
John McCall2de56d12010-08-25 11:45:40 +00004510 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004511 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004512}
4513
John McCall60d7b3a2010-08-24 06:29:42 +00004514ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004515Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4516 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004517 SourceLocation RParenLoc, Expr *CastExpr) {
4518 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004519 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004520
Richard Trieuccd891a2011-09-09 01:45:06 +00004521 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004522 if (D.isInvalidType())
4523 return ExprError();
4524
David Blaikie4e4d0842012-03-11 07:00:24 +00004525 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004526 // Check that there are no default arguments (C++ only).
4527 CheckExtraCXXDefaultArguments(D);
4528 }
4529
John McCalle82247a2011-10-01 05:17:03 +00004530 checkUnusedDeclAttributes(D);
4531
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004532 QualType castType = castTInfo->getType();
4533 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004535 bool isVectorLiteral = false;
4536
4537 // Check for an altivec or OpenCL literal,
4538 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004539 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4540 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004541 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004542 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004543 if (PLE && PLE->getNumExprs() == 0) {
4544 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4545 return ExprError();
4546 }
4547 if (PE || PLE->getNumExprs() == 1) {
4548 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4549 if (!E->getType()->isVectorType())
4550 isVectorLiteral = true;
4551 }
4552 else
4553 isVectorLiteral = true;
4554 }
4555
4556 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4557 // then handle it as such.
4558 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004559 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004560
Nate Begeman2ef13e52009-08-10 23:49:36 +00004561 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004562 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4563 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004564 if (isa<ParenListExpr>(CastExpr)) {
4565 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004566 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004567 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004568 }
John McCallb042fdf2010-01-15 18:56:44 +00004569
Richard Trieuccd891a2011-09-09 01:45:06 +00004570 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004571}
4572
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004573ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4574 SourceLocation RParenLoc, Expr *E,
4575 TypeSourceInfo *TInfo) {
4576 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4577 "Expected paren or paren list expression");
4578
4579 Expr **exprs;
4580 unsigned numExprs;
4581 Expr *subExpr;
4582 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4583 exprs = PE->getExprs();
4584 numExprs = PE->getNumExprs();
4585 } else {
4586 subExpr = cast<ParenExpr>(E)->getSubExpr();
4587 exprs = &subExpr;
4588 numExprs = 1;
4589 }
4590
4591 QualType Ty = TInfo->getType();
4592 assert(Ty->isVectorType() && "Expected vector type");
4593
Chris Lattner5f9e2722011-07-23 10:55:15 +00004594 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004595 const VectorType *VTy = Ty->getAs<VectorType>();
4596 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4597
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004598 // '(...)' form of vector initialization in AltiVec: the number of
4599 // initializers must be one or must match the size of the vector.
4600 // If a single value is specified in the initializer then it will be
4601 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004602 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004603 // The number of initializers must be one or must match the size of the
4604 // vector. If a single value is specified in the initializer then it will
4605 // be replicated to all the components of the vector
4606 if (numExprs == 1) {
4607 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004608 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4609 if (Literal.isInvalid())
4610 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004611 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004612 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004613 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4614 }
4615 else if (numExprs < numElems) {
4616 Diag(E->getExprLoc(),
4617 diag::err_incorrect_number_of_vector_initializers);
4618 return ExprError();
4619 }
4620 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004621 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004622 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004623 else {
4624 // For OpenCL, when the number of initializers is a single value,
4625 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004626 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004627 VTy->getVectorKind() == VectorType::GenericVector &&
4628 numExprs == 1) {
4629 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004630 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4631 if (Literal.isInvalid())
4632 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004633 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004634 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004635 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4636 }
4637
Benjamin Kramer14c59822012-02-14 12:06:21 +00004638 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004639 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004640 // FIXME: This means that pretty-printing the final AST will produce curly
4641 // braces instead of the original commas.
4642 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004643 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004644 initE->setType(Ty);
4645 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4646}
4647
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004648/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4649/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004650ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004651Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4652 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004653 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004654 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004655
John McCall60d7b3a2010-08-24 06:29:42 +00004656 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Nate Begeman2ef13e52009-08-10 23:49:36 +00004658 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004659 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4660 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004661
John McCall9ae2f072010-08-23 23:25:46 +00004662 if (Result.isInvalid()) return ExprError();
4663
4664 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004665}
4666
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004667ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4668 SourceLocation R,
4669 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004670 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4671 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004672 return Owned(expr);
4673}
4674
Chandler Carruth82214a82011-02-18 23:54:50 +00004675/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004676/// constant and the other is not a pointer. Returns true if a diagnostic is
4677/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004678bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004679 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004680 Expr *NullExpr = LHSExpr;
4681 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004682 Expr::NullPointerConstantKind NullKind =
4683 NullExpr->isNullPointerConstant(Context,
4684 Expr::NPC_ValueDependentIsNotNull);
4685
4686 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004687 NullExpr = RHSExpr;
4688 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004689 NullKind =
4690 NullExpr->isNullPointerConstant(Context,
4691 Expr::NPC_ValueDependentIsNotNull);
4692 }
4693
4694 if (NullKind == Expr::NPCK_NotNull)
4695 return false;
4696
David Blaikie50800fc2012-08-08 17:33:31 +00004697 if (NullKind == Expr::NPCK_ZeroExpression)
4698 return false;
4699
4700 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004701 // In this case, check to make sure that we got here from a "NULL"
4702 // string in the source code.
4703 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004704 SourceLocation loc = NullExpr->getExprLoc();
4705 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004706 return false;
4707 }
4708
4709 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4710 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4711 << NonPointerExpr->getType() << DiagType
4712 << NonPointerExpr->getSourceRange();
4713 return true;
4714}
4715
Richard Trieu26f96072011-09-02 01:51:02 +00004716/// \brief Return false if the condition expression is valid, true otherwise.
4717static bool checkCondition(Sema &S, Expr *Cond) {
4718 QualType CondTy = Cond->getType();
4719
4720 // C99 6.5.15p2
4721 if (CondTy->isScalarType()) return false;
4722
4723 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004724 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004725 return false;
4726
4727 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004728 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004729 diag::err_typecheck_cond_expect_scalar :
4730 diag::err_typecheck_cond_expect_scalar_or_vector)
4731 << CondTy;
4732 return true;
4733}
4734
4735/// \brief Return false if the two expressions can be converted to a vector,
4736/// true otherwise
4737static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4738 ExprResult &RHS,
4739 QualType CondTy) {
4740 // Both operands should be of scalar type.
4741 if (!LHS.get()->getType()->isScalarType()) {
4742 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4743 << CondTy;
4744 return true;
4745 }
4746 if (!RHS.get()->getType()->isScalarType()) {
4747 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4748 << CondTy;
4749 return true;
4750 }
4751
4752 // Implicity convert these scalars to the type of the condition.
4753 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4754 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4755 return false;
4756}
4757
4758/// \brief Handle when one or both operands are void type.
4759static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4760 ExprResult &RHS) {
4761 Expr *LHSExpr = LHS.get();
4762 Expr *RHSExpr = RHS.get();
4763
4764 if (!LHSExpr->getType()->isVoidType())
4765 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4766 << RHSExpr->getSourceRange();
4767 if (!RHSExpr->getType()->isVoidType())
4768 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4769 << LHSExpr->getSourceRange();
4770 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4771 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4772 return S.Context.VoidTy;
4773}
4774
4775/// \brief Return false if the NullExpr can be promoted to PointerTy,
4776/// true otherwise.
4777static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4778 QualType PointerTy) {
4779 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4780 !NullExpr.get()->isNullPointerConstant(S.Context,
4781 Expr::NPC_ValueDependentIsNull))
4782 return true;
4783
4784 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4785 return false;
4786}
4787
4788/// \brief Checks compatibility between two pointers and return the resulting
4789/// type.
4790static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4791 ExprResult &RHS,
4792 SourceLocation Loc) {
4793 QualType LHSTy = LHS.get()->getType();
4794 QualType RHSTy = RHS.get()->getType();
4795
4796 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4797 // Two identical pointers types are always compatible.
4798 return LHSTy;
4799 }
4800
4801 QualType lhptee, rhptee;
4802
4803 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004804 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4805 lhptee = LHSBTy->getPointeeType();
4806 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004807 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004808 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4809 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004810 }
4811
Eli Friedmanae916a12012-04-05 22:30:04 +00004812 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4813 // differently qualified versions of compatible types, the result type is
4814 // a pointer to an appropriately qualified version of the composite
4815 // type.
4816
4817 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4818 // clause doesn't make sense for our extensions. E.g. address space 2 should
4819 // be incompatible with address space 3: they may live on different devices or
4820 // anything.
4821 Qualifiers lhQual = lhptee.getQualifiers();
4822 Qualifiers rhQual = rhptee.getQualifiers();
4823
4824 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4825 lhQual.removeCVRQualifiers();
4826 rhQual.removeCVRQualifiers();
4827
4828 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4829 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4830
4831 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4832
4833 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004834 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4835 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4836 << RHS.get()->getSourceRange();
4837 // In this situation, we assume void* type. No especially good
4838 // reason, but this is what gcc does, and we do have to pick
4839 // to get a consistent AST.
4840 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4841 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4842 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4843 return incompatTy;
4844 }
4845
4846 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004847 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4848 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004849
Eli Friedmanae916a12012-04-05 22:30:04 +00004850 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4851 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4852 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004853}
4854
4855/// \brief Return the resulting type when the operands are both block pointers.
4856static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4857 ExprResult &LHS,
4858 ExprResult &RHS,
4859 SourceLocation Loc) {
4860 QualType LHSTy = LHS.get()->getType();
4861 QualType RHSTy = RHS.get()->getType();
4862
4863 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4864 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4865 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4866 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4867 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4868 return destType;
4869 }
4870 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4871 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4872 << RHS.get()->getSourceRange();
4873 return QualType();
4874 }
4875
4876 // We have 2 block pointer types.
4877 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4878}
4879
4880/// \brief Return the resulting type when the operands are both pointers.
4881static QualType
4882checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4883 ExprResult &RHS,
4884 SourceLocation Loc) {
4885 // get the pointer types
4886 QualType LHSTy = LHS.get()->getType();
4887 QualType RHSTy = RHS.get()->getType();
4888
4889 // get the "pointed to" types
4890 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4891 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4892
4893 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4894 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4895 // Figure out necessary qualifiers (C99 6.5.15p6)
4896 QualType destPointee
4897 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4898 QualType destType = S.Context.getPointerType(destPointee);
4899 // Add qualifiers if necessary.
4900 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4901 // Promote to void*.
4902 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4903 return destType;
4904 }
4905 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4906 QualType destPointee
4907 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4908 QualType destType = S.Context.getPointerType(destPointee);
4909 // Add qualifiers if necessary.
4910 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4911 // Promote to void*.
4912 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4913 return destType;
4914 }
4915
4916 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4917}
4918
4919/// \brief Return false if the first expression is not an integer and the second
4920/// expression is not a pointer, true otherwise.
4921static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4922 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004923 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004924 if (!PointerExpr->getType()->isPointerType() ||
4925 !Int.get()->getType()->isIntegerType())
4926 return false;
4927
Richard Trieuccd891a2011-09-09 01:45:06 +00004928 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4929 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004930
4931 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4932 << Expr1->getType() << Expr2->getType()
4933 << Expr1->getSourceRange() << Expr2->getSourceRange();
4934 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4935 CK_IntegralToPointer);
4936 return true;
4937}
4938
Richard Trieu33fc7572011-09-06 20:06:39 +00004939/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4940/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004941/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004942QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4943 ExprResult &RHS, ExprValueKind &VK,
4944 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004945 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004946
Richard Trieu33fc7572011-09-06 20:06:39 +00004947 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4948 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004949 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004950
Richard Trieu33fc7572011-09-06 20:06:39 +00004951 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4952 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004953 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004954
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004955 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004956 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004957 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004958
4959 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004960 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004961
John Wiegley429bb272011-04-08 18:41:53 +00004962 Cond = UsualUnaryConversions(Cond.take());
4963 if (Cond.isInvalid())
4964 return QualType();
4965 LHS = UsualUnaryConversions(LHS.take());
4966 if (LHS.isInvalid())
4967 return QualType();
4968 RHS = UsualUnaryConversions(RHS.take());
4969 if (RHS.isInvalid())
4970 return QualType();
4971
4972 QualType CondTy = Cond.get()->getType();
4973 QualType LHSTy = LHS.get()->getType();
4974 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004975
Reid Spencer5f016e22007-07-11 17:01:13 +00004976 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004977 if (checkCondition(*this, Cond.get()))
4978 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004979
Chris Lattner70d67a92008-01-06 22:42:25 +00004980 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004981 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004982 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004983
Nate Begeman6155d732010-09-20 22:41:17 +00004984 // OpenCL: If the condition is a vector, and both operands are scalar,
4985 // attempt to implicity convert them to the vector type to act like the
4986 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004987 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004988 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004989 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004990
Chris Lattner70d67a92008-01-06 22:42:25 +00004991 // If both operands have arithmetic type, do the usual arithmetic conversions
4992 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004993 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4994 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004995 if (LHS.isInvalid() || RHS.isInvalid())
4996 return QualType();
4997 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004998 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004999
Chris Lattner70d67a92008-01-06 22:42:25 +00005000 // If both operands are the same structure or union type, the result is that
5001 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005002 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5003 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005004 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005005 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005006 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005007 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005008 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005009 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005010
Chris Lattner70d67a92008-01-06 22:42:25 +00005011 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005012 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005013 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005014 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005015 }
Richard Trieu26f96072011-09-02 01:51:02 +00005016
Steve Naroffb6d54e52008-01-08 01:11:38 +00005017 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5018 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005019 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5020 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005021
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005022 // All objective-c pointer type analysis is done here.
5023 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5024 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005025 if (LHS.isInvalid() || RHS.isInvalid())
5026 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005027 if (!compositeType.isNull())
5028 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005029
5030
Steve Naroff7154a772009-07-01 14:36:47 +00005031 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005032 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5033 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5034 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005035
Steve Naroff7154a772009-07-01 14:36:47 +00005036 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005037 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5038 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5039 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005040
John McCall404cd162010-11-13 01:35:44 +00005041 // GCC compatibility: soften pointer/integer mismatch. Note that
5042 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005043 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5044 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005045 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005046 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5047 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005048 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005049
Chandler Carruth82214a82011-02-18 23:54:50 +00005050 // Emit a better diagnostic if one of the expressions is a null pointer
5051 // constant and the other is not a pointer type. In this case, the user most
5052 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005053 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005054 return QualType();
5055
Chris Lattner70d67a92008-01-06 22:42:25 +00005056 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005057 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005058 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5059 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005060 return QualType();
5061}
5062
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005063/// FindCompositeObjCPointerType - Helper method to find composite type of
5064/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005065QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005066 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005067 QualType LHSTy = LHS.get()->getType();
5068 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005069
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005070 // Handle things like Class and struct objc_class*. Here we case the result
5071 // to the pseudo-builtin, because that will be implicitly cast back to the
5072 // redefinition type if an attempt is made to access its fields.
5073 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005074 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005075 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005076 return LHSTy;
5077 }
5078 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005079 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005080 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005081 return RHSTy;
5082 }
5083 // And the same for struct objc_object* / id
5084 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005085 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005086 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005087 return LHSTy;
5088 }
5089 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005090 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005091 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005092 return RHSTy;
5093 }
5094 // And the same for struct objc_selector* / SEL
5095 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005096 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005097 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005098 return LHSTy;
5099 }
5100 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005101 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005102 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005103 return RHSTy;
5104 }
5105 // Check constraints for Objective-C object pointers types.
5106 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005107
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005108 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5109 // Two identical object pointer types are always compatible.
5110 return LHSTy;
5111 }
John McCall1d9b3b22011-09-09 05:25:32 +00005112 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005114 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005115
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005116 // If both operands are interfaces and either operand can be
5117 // assigned to the other, use that type as the composite
5118 // type. This allows
5119 // xxx ? (A*) a : (B*) b
5120 // where B is a subclass of A.
5121 //
5122 // Additionally, as for assignment, if either type is 'id'
5123 // allow silent coercion. Finally, if the types are
5124 // incompatible then make sure to use 'id' as the composite
5125 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005126
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005127 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5128 // It could return the composite type.
5129 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5130 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5131 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5132 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5133 } else if ((LHSTy->isObjCQualifiedIdType() ||
5134 RHSTy->isObjCQualifiedIdType()) &&
5135 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5136 // Need to handle "id<xx>" explicitly.
5137 // GCC allows qualified id and any Objective-C type to devolve to
5138 // id. Currently localizing to here until clear this should be
5139 // part of ObjCQualifiedIdTypesAreCompatible.
5140 compositeType = Context.getObjCIdType();
5141 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5142 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005143 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005144 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5145 ;
5146 else {
5147 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5148 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005149 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005150 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005151 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5152 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005153 return incompatTy;
5154 }
5155 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005156 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5157 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005158 return compositeType;
5159 }
5160 // Check Objective-C object pointer types and 'void *'
5161 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005162 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005163 // ARC forbids the implicit conversion of object pointers to 'void *',
5164 // so these types are not compatible.
5165 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5166 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5167 LHS = RHS = true;
5168 return QualType();
5169 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005170 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5171 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5172 QualType destPointee
5173 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5174 QualType destType = Context.getPointerType(destPointee);
5175 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005176 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005177 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005178 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005179 return destType;
5180 }
5181 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005182 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005183 // ARC forbids the implicit conversion of object pointers to 'void *',
5184 // so these types are not compatible.
5185 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5186 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5187 LHS = RHS = true;
5188 return QualType();
5189 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005190 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5191 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5192 QualType destPointee
5193 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5194 QualType destType = Context.getPointerType(destPointee);
5195 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005196 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005197 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005198 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005199 return destType;
5200 }
5201 return QualType();
5202}
5203
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005204/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005205/// ParenRange in parentheses.
5206static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005207 const PartialDiagnostic &Note,
5208 SourceRange ParenRange) {
5209 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5210 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5211 EndLoc.isValid()) {
5212 Self.Diag(Loc, Note)
5213 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5214 << FixItHint::CreateInsertion(EndLoc, ")");
5215 } else {
5216 // We can't display the parentheses, so just show the bare note.
5217 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005218 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005219}
5220
5221static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5222 return Opc >= BO_Mul && Opc <= BO_Shr;
5223}
5224
Hans Wennborg2f072b42011-06-09 17:06:51 +00005225/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5226/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005227/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5228/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005229static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005230 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005231 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5232 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005233 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005234 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005235
5236 // Built-in binary operator.
5237 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5238 if (IsArithmeticOp(OP->getOpcode())) {
5239 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005240 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005241 return true;
5242 }
5243 }
5244
5245 // Overloaded operator.
5246 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5247 if (Call->getNumArgs() != 2)
5248 return false;
5249
5250 // Make sure this is really a binary operator that is safe to pass into
5251 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5252 OverloadedOperatorKind OO = Call->getOperator();
5253 if (OO < OO_Plus || OO > OO_Arrow)
5254 return false;
5255
5256 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5257 if (IsArithmeticOp(OpKind)) {
5258 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005259 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005260 return true;
5261 }
5262 }
5263
5264 return false;
5265}
5266
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005267static bool IsLogicOp(BinaryOperatorKind Opc) {
5268 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5269}
5270
Hans Wennborg2f072b42011-06-09 17:06:51 +00005271/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5272/// or is a logical expression such as (x==y) which has int type, but is
5273/// commonly interpreted as boolean.
5274static bool ExprLooksBoolean(Expr *E) {
5275 E = E->IgnoreParenImpCasts();
5276
5277 if (E->getType()->isBooleanType())
5278 return true;
5279 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5280 return IsLogicOp(OP->getOpcode());
5281 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5282 return OP->getOpcode() == UO_LNot;
5283
5284 return false;
5285}
5286
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005287/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5288/// and binary operator are mixed in a way that suggests the programmer assumed
5289/// the conditional operator has higher precedence, for example:
5290/// "int x = a + someBinaryCondition ? 1 : 2".
5291static void DiagnoseConditionalPrecedence(Sema &Self,
5292 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005293 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005294 Expr *LHSExpr,
5295 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005296 BinaryOperatorKind CondOpcode;
5297 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005298
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005299 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005300 return;
5301 if (!ExprLooksBoolean(CondRHS))
5302 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005303
Hans Wennborg2f072b42011-06-09 17:06:51 +00005304 // The condition is an arithmetic binary expression, with a right-
5305 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005306
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005307 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005308 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005309 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005310
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005311 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005312 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005313 << BinaryOperator::getOpcodeStr(CondOpcode),
5314 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005315
5316 SuggestParentheses(Self, OpLoc,
5317 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005318 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005319}
5320
Steve Narofff69936d2007-09-16 03:34:24 +00005321/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005322/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005323ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005324 SourceLocation ColonLoc,
5325 Expr *CondExpr, Expr *LHSExpr,
5326 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005327 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5328 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005329 OpaqueValueExpr *opaqueValue = 0;
5330 Expr *commonExpr = 0;
5331 if (LHSExpr == 0) {
5332 commonExpr = CondExpr;
5333
5334 // We usually want to apply unary conversions *before* saving, except
5335 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005336 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005337 && !commonExpr->isTypeDependent()
5338 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5339 && commonExpr->isGLValue()
5340 && commonExpr->isOrdinaryOrBitFieldObject()
5341 && RHSExpr->isOrdinaryOrBitFieldObject()
5342 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005343 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5344 if (commonRes.isInvalid())
5345 return ExprError();
5346 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005347 }
5348
5349 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5350 commonExpr->getType(),
5351 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005352 commonExpr->getObjectKind(),
5353 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005354 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005355 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005356
John McCallf89e55a2010-11-18 06:31:45 +00005357 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005358 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005359 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5360 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005361 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005362 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5363 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005364 return ExprError();
5365
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005366 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5367 RHS.get());
5368
John McCall56ca35d2011-02-17 10:25:35 +00005369 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005370 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5371 LHS.take(), ColonLoc,
5372 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005373
5374 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005375 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005376 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5377 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005378}
5379
John McCalle4be87e2011-01-31 23:13:11 +00005380// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005381// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005382// routine is it effectively iqnores the qualifiers on the top level pointee.
5383// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5384// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005385static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005386checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5387 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5388 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005389
Reid Spencer5f016e22007-07-11 17:01:13 +00005390 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005391 const Type *lhptee, *rhptee;
5392 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005393 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5394 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005395
John McCalle4be87e2011-01-31 23:13:11 +00005396 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005397
5398 // C99 6.5.16.1p1: This following citation is common to constraints
5399 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5400 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005401 Qualifiers lq;
5402
John McCallf85e1932011-06-15 23:02:42 +00005403 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5404 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5405 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5406 // Ignore lifetime for further calculation.
5407 lhq.removeObjCLifetime();
5408 rhq.removeObjCLifetime();
5409 }
5410
John McCall86c05f32011-02-01 00:10:29 +00005411 if (!lhq.compatiblyIncludes(rhq)) {
5412 // Treat address-space mismatches as fatal. TODO: address subspaces
5413 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5414 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5415
John McCallf85e1932011-06-15 23:02:42 +00005416 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005417 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005418 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005419 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005420 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005421 && (lhptee->isVoidType() || rhptee->isVoidType()))
5422 ; // keep old
5423
John McCallf85e1932011-06-15 23:02:42 +00005424 // Treat lifetime mismatches as fatal.
5425 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5426 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5427
John McCall86c05f32011-02-01 00:10:29 +00005428 // For GCC compatibility, other qualifier mismatches are treated
5429 // as still compatible in C.
5430 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5431 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005432
Mike Stumpeed9cac2009-02-19 03:04:26 +00005433 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5434 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005435 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005436 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005437 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005438 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005439
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005440 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005441 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005442 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005443 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005444
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005445 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005446 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005447 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005448
5449 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005450 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005451 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005452 }
John McCall86c05f32011-02-01 00:10:29 +00005453
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005455 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005456 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5457 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005458 // Check if the pointee types are compatible ignoring the sign.
5459 // We explicitly check for char so that we catch "char" vs
5460 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005461 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005462 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005463 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005464 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005465
Chris Lattner6a2b9262009-10-17 20:33:28 +00005466 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005467 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005468 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005469 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005470
John McCall86c05f32011-02-01 00:10:29 +00005471 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005472 // Types are compatible ignoring the sign. Qualifier incompatibility
5473 // takes priority over sign incompatibility because the sign
5474 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005475 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005476 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005477
John McCalle4be87e2011-01-31 23:13:11 +00005478 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005479 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005480
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005481 // If we are a multi-level pointer, it's possible that our issue is simply
5482 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5483 // the eventual target type is the same and the pointers have the same
5484 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005485 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005486 do {
John McCall86c05f32011-02-01 00:10:29 +00005487 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5488 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005489 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005490
John McCall86c05f32011-02-01 00:10:29 +00005491 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005492 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005493 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005494
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005495 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005496 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005497 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005498 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005499 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5500 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005501 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005502}
5503
John McCalle4be87e2011-01-31 23:13:11 +00005504/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005505/// block pointer types are compatible or whether a block and normal pointer
5506/// are compatible. It is more restrict than comparing two function pointer
5507// types.
John McCalle4be87e2011-01-31 23:13:11 +00005508static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005509checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5510 QualType RHSType) {
5511 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5512 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005513
Steve Naroff1c7d0672008-09-04 15:10:53 +00005514 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005515
Steve Naroff1c7d0672008-09-04 15:10:53 +00005516 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005517 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5518 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005519
John McCalle4be87e2011-01-31 23:13:11 +00005520 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005521 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005522 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005523
John McCalle4be87e2011-01-31 23:13:11 +00005524 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005525
Steve Naroff1c7d0672008-09-04 15:10:53 +00005526 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005527 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5528 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005529
Richard Trieu1da27a12011-09-06 20:21:22 +00005530 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005531 return Sema::IncompatibleBlockPointer;
5532
Steve Naroff1c7d0672008-09-04 15:10:53 +00005533 return ConvTy;
5534}
5535
John McCalle4be87e2011-01-31 23:13:11 +00005536/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005537/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005538static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005539checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5540 QualType RHSType) {
5541 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5542 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005543
Richard Trieu1da27a12011-09-06 20:21:22 +00005544 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005545 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005546 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5547 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005548 return Sema::IncompatiblePointer;
5549 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005550 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005551 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005552 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5553 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005554 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005555 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005556 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005557 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5558 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005559
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005560 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5561 // make an exception for id<P>
5562 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005563 return Sema::CompatiblePointerDiscardsQualifiers;
5564
Richard Trieu1da27a12011-09-06 20:21:22 +00005565 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005566 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005567 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005568 return Sema::IncompatibleObjCQualifiedId;
5569 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005570}
5571
John McCall1c23e912010-11-16 02:32:08 +00005572Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005573Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005574 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005575 // Fake up an opaque expression. We don't actually care about what
5576 // cast operations are required, so if CheckAssignmentConstraints
5577 // adds casts to this they'll be wasted, but fortunately that doesn't
5578 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005579 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5580 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005581 CastKind K = CK_Invalid;
5582
Richard Trieu1da27a12011-09-06 20:21:22 +00005583 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005584}
5585
Mike Stumpeed9cac2009-02-19 03:04:26 +00005586/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5587/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005588/// pointers. Here are some objectionable examples that GCC considers warnings:
5589///
5590/// int a, *pint;
5591/// short *pshort;
5592/// struct foo *pfoo;
5593///
5594/// pint = pshort; // warning: assignment from incompatible pointer type
5595/// a = pint; // warning: assignment makes integer from pointer without a cast
5596/// pint = a; // warning: assignment makes pointer from integer without a cast
5597/// pint = pfoo; // warning: assignment from incompatible pointer type
5598///
5599/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005600/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005601///
John McCalldaa8e4e2010-11-15 09:13:47 +00005602/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005603Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005604Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005605 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005606 QualType RHSType = RHS.get()->getType();
5607 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005608
Chris Lattnerfc144e22008-01-04 23:18:45 +00005609 // Get canonical types. We're not formatting these types, just comparing
5610 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005611 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5612 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005613
Eli Friedmanb001de72011-10-06 23:00:33 +00005614
John McCallb6cfa242011-01-31 22:28:28 +00005615 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005616 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005617 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005618 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005619 }
5620
Eli Friedman860a3192012-06-16 02:19:17 +00005621 // If we have an atomic type, try a non-atomic assignment, then just add an
5622 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005623 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005624 Sema::AssignConvertType result =
5625 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5626 if (result != Compatible)
5627 return result;
5628 if (Kind != CK_NoOp)
5629 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5630 Kind = CK_NonAtomicToAtomic;
5631 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005632 }
5633
Douglas Gregor9d293df2008-10-28 00:22:11 +00005634 // If the left-hand side is a reference type, then we are in a
5635 // (rare!) case where we've allowed the use of references in C,
5636 // e.g., as a parameter type in a built-in function. In this case,
5637 // just make sure that the type referenced is compatible with the
5638 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005639 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005640 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005641 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5642 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005643 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005644 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005645 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005646 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005647 }
John McCallb6cfa242011-01-31 22:28:28 +00005648
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005649 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5650 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005651 if (LHSType->isExtVectorType()) {
5652 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005653 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005654 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005655 // CK_VectorSplat does T -> vector T, so first cast to the
5656 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005657 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5658 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005659 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005660 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005661 }
5662 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005663 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005664 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005665 }
Mike Stump1eb44332009-09-09 15:08:12 +00005666
John McCallb6cfa242011-01-31 22:28:28 +00005667 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005668 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5669 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005670 // Allow assignments of an AltiVec vector type to an equivalent GCC
5671 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005672 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005673 Kind = CK_BitCast;
5674 return Compatible;
5675 }
5676
Douglas Gregor255210e2010-08-06 10:14:59 +00005677 // If we are allowing lax vector conversions, and LHS and RHS are both
5678 // vectors, the total size only needs to be the same. This is a bitcast;
5679 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005680 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005681 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005682 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005683 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005684 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005685 }
5686 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005687 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005688
John McCallb6cfa242011-01-31 22:28:28 +00005689 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005690 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005691 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005692 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005693 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005694 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005695
John McCallb6cfa242011-01-31 22:28:28 +00005696 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005697 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005698 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005699 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005700 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005701 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005702 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005703
John McCallb6cfa242011-01-31 22:28:28 +00005704 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005705 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005706 Kind = CK_IntegralToPointer; // FIXME: null?
5707 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005708 }
John McCallb6cfa242011-01-31 22:28:28 +00005709
5710 // C pointers are not compatible with ObjC object pointers,
5711 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005712 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005713 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005714 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005715 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005716 return Compatible;
5717 }
5718
5719 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005720 if (RHSType->isObjCClassType() &&
5721 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005722 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005723 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005724 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005725 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005726
John McCallb6cfa242011-01-31 22:28:28 +00005727 Kind = CK_BitCast;
5728 return IncompatiblePointer;
5729 }
5730
5731 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005732 if (RHSType->getAs<BlockPointerType>()) {
5733 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005734 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005735 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005736 }
Steve Naroffb4406862008-09-29 18:10:17 +00005737 }
John McCallb6cfa242011-01-31 22:28:28 +00005738
Steve Naroff1c7d0672008-09-04 15:10:53 +00005739 return Incompatible;
5740 }
5741
John McCallb6cfa242011-01-31 22:28:28 +00005742 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005743 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005744 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005745 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005746 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005747 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005748 }
5749
5750 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005751 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005752 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005753 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005754 }
5755
John McCallb6cfa242011-01-31 22:28:28 +00005756 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005757 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005758 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005759 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005760 }
Steve Naroffb4406862008-09-29 18:10:17 +00005761
John McCallb6cfa242011-01-31 22:28:28 +00005762 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005763 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005764 if (RHSPT->getPointeeType()->isVoidType()) {
5765 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005766 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005767 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005768
Chris Lattnerfc144e22008-01-04 23:18:45 +00005769 return Incompatible;
5770 }
5771
John McCallb6cfa242011-01-31 22:28:28 +00005772 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005773 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005774 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005775 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005776 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005777 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005778 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005779 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005780 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005781 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005782 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005783 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005784 }
5785
5786 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005787 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005788 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005789 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005790 }
5791
John McCallb6cfa242011-01-31 22:28:28 +00005792 // In general, C pointers are not compatible with ObjC object pointers,
5793 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005794 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005795 Kind = CK_CPointerToObjCPointerCast;
5796
John McCallb6cfa242011-01-31 22:28:28 +00005797 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005798 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005799 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005800 }
5801
5802 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005803 if (LHSType->isObjCClassType() &&
5804 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005805 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005806 return Compatible;
5807 }
5808
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005809 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005810 }
John McCallb6cfa242011-01-31 22:28:28 +00005811
5812 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005813 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005814 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005815 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005816 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005817 }
5818
Steve Naroff14108da2009-07-10 23:34:53 +00005819 return Incompatible;
5820 }
John McCallb6cfa242011-01-31 22:28:28 +00005821
5822 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005823 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005824 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005825 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005826 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005827 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005828 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005829
John McCallb6cfa242011-01-31 22:28:28 +00005830 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005831 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005832 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005833 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005834 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005835
Chris Lattnerfc144e22008-01-04 23:18:45 +00005836 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005837 }
John McCallb6cfa242011-01-31 22:28:28 +00005838
5839 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005840 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005841 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005842 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005843 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005844 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005845 }
Steve Naroff14108da2009-07-10 23:34:53 +00005846
John McCallb6cfa242011-01-31 22:28:28 +00005847 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005848 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005849 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005850 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005851 }
5852
Steve Naroff14108da2009-07-10 23:34:53 +00005853 return Incompatible;
5854 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005855
John McCallb6cfa242011-01-31 22:28:28 +00005856 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005857 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5858 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005859 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005860 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005861 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005862 }
John McCallb6cfa242011-01-31 22:28:28 +00005863
Reid Spencer5f016e22007-07-11 17:01:13 +00005864 return Incompatible;
5865}
5866
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005867/// \brief Constructs a transparent union from an expression that is
5868/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005869static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5870 ExprResult &EResult, QualType UnionType,
5871 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005872 // Build an initializer list that designates the appropriate member
5873 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005874 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005875 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005876 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005877 Initializer->setType(UnionType);
5878 Initializer->setInitializedFieldInUnion(Field);
5879
5880 // Build a compound literal constructing a value of the transparent
5881 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005882 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005883 EResult = S.Owned(
5884 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5885 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005886}
5887
5888Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005889Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005890 ExprResult &RHS) {
5891 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005892
Mike Stump1eb44332009-09-09 15:08:12 +00005893 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005894 // transparent_union GCC extension.
5895 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005896 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005897 return Incompatible;
5898
5899 // The field to initialize within the transparent union.
5900 RecordDecl *UD = UT->getDecl();
5901 FieldDecl *InitField = 0;
5902 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005903 for (RecordDecl::field_iterator it = UD->field_begin(),
5904 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005905 it != itend; ++it) {
5906 if (it->getType()->isPointerType()) {
5907 // If the transparent union contains a pointer type, we allow:
5908 // 1) void pointer
5909 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005910 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005911 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005912 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005913 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005914 break;
5915 }
Mike Stump1eb44332009-09-09 15:08:12 +00005916
Richard Trieuf7720da2011-09-06 20:40:12 +00005917 if (RHS.get()->isNullPointerConstant(Context,
5918 Expr::NPC_ValueDependentIsNull)) {
5919 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5920 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005921 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005922 break;
5923 }
5924 }
5925
John McCalldaa8e4e2010-11-15 09:13:47 +00005926 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005927 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005928 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005929 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005930 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005931 break;
5932 }
5933 }
5934
5935 if (!InitField)
5936 return Incompatible;
5937
Richard Trieuf7720da2011-09-06 20:40:12 +00005938 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005939 return Compatible;
5940}
5941
Chris Lattner5cf216b2008-01-04 18:04:52 +00005942Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005943Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5944 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005945 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005946 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005947 // C++ 5.17p3: If the left operand is not of class type, the
5948 // expression is implicitly converted (C++ 4) to the
5949 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005950 ExprResult Res;
5951 if (Diagnose) {
5952 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5953 AA_Assigning);
5954 } else {
5955 ImplicitConversionSequence ICS =
5956 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5957 /*SuppressUserConversions=*/false,
5958 /*AllowExplicit=*/false,
5959 /*InOverloadResolution=*/false,
5960 /*CStyle=*/false,
5961 /*AllowObjCWritebackConversion=*/false);
5962 if (ICS.isFailure())
5963 return Incompatible;
5964 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5965 ICS, AA_Assigning);
5966 }
John Wiegley429bb272011-04-08 18:41:53 +00005967 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005968 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005969 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005970 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005971 !CheckObjCARCUnavailableWeakConversion(LHSType,
5972 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005973 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005974 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005975 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005976 }
5977
5978 // FIXME: Currently, we fall through and treat C++ classes like C
5979 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005980 // FIXME: We also fall through for atomics; not sure what should
5981 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005982 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005983
Steve Naroff529a4ad2007-11-27 17:58:44 +00005984 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5985 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005986 if ((LHSType->isPointerType() ||
5987 LHSType->isObjCObjectPointerType() ||
5988 LHSType->isBlockPointerType())
5989 && RHS.get()->isNullPointerConstant(Context,
5990 Expr::NPC_ValueDependentIsNull)) {
5991 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005992 return Compatible;
5993 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005994
Chris Lattner943140e2007-10-16 02:55:40 +00005995 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005996 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005997 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005998 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005999 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006000 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006001 if (!LHSType->isReferenceType()) {
6002 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6003 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006004 return Incompatible;
6005 }
Steve Narofff1120de2007-08-24 22:33:52 +00006006
John McCalldaa8e4e2010-11-15 09:13:47 +00006007 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006008 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006009 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006010
Steve Narofff1120de2007-08-24 22:33:52 +00006011 // C99 6.5.16.1p2: The value of the right operand is converted to the
6012 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006013 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6014 // so that we can use references in built-in functions even in C.
6015 // The getNonReferenceType() call makes sure that the resulting expression
6016 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006017 if (result != Incompatible && RHS.get()->getType() != LHSType)
6018 RHS = ImpCastExprToType(RHS.take(),
6019 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006020 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006021}
6022
Richard Trieuf7720da2011-09-06 20:40:12 +00006023QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6024 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006025 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006026 << LHS.get()->getType() << RHS.get()->getType()
6027 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006028 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006029}
6030
Richard Trieu08062aa2011-09-06 21:01:04 +00006031QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006032 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006033 if (!IsCompAssign) {
6034 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6035 if (LHS.isInvalid())
6036 return QualType();
6037 }
6038 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6039 if (RHS.isInvalid())
6040 return QualType();
6041
Mike Stumpeed9cac2009-02-19 03:04:26 +00006042 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006043 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006044 QualType LHSType =
6045 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6046 QualType RHSType =
6047 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006048
Nate Begemanbe2341d2008-07-14 18:02:46 +00006049 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006050 if (LHSType == RHSType)
6051 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006052
Douglas Gregor255210e2010-08-06 10:14:59 +00006053 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006054 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6055 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6056 if (LHSType->isExtVectorType()) {
6057 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6058 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006059 }
6060
Richard Trieuccd891a2011-09-09 01:45:06 +00006061 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006062 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6063 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006064 }
6065
David Blaikie4e4d0842012-03-11 07:00:24 +00006066 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006067 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006068 // If we are allowing lax vector conversions, and LHS and RHS are both
6069 // vectors, the total size only needs to be the same. This is a
6070 // bitcast; no bits are changed but the result type is different.
6071 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006072 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6073 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006074 }
6075
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006076 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6077 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6078 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006079 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006080 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006081 std::swap(RHS, LHS);
6082 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006083 }
Mike Stump1eb44332009-09-09 15:08:12 +00006084
Nate Begemandde25982009-06-28 19:12:57 +00006085 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006086 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006087 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006088 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6089 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006090 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006091 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006092 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006093 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6094 if (swapped) std::swap(RHS, LHS);
6095 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006096 }
6097 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006098 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6099 RHSType->isRealFloatingType()) {
6100 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006101 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006102 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006103 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006104 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6105 if (swapped) std::swap(RHS, LHS);
6106 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006107 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006108 }
6109 }
Mike Stump1eb44332009-09-09 15:08:12 +00006110
Nate Begemandde25982009-06-28 19:12:57 +00006111 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006113 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006114 << LHS.get()->getType() << RHS.get()->getType()
6115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006116 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006117}
6118
Richard Trieu481037f2011-09-16 00:53:10 +00006119// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6120// expression. These are mainly cases where the null pointer is used as an
6121// integer instead of a pointer.
6122static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6123 SourceLocation Loc, bool IsCompare) {
6124 // The canonical way to check for a GNU null is with isNullPointerConstant,
6125 // but we use a bit of a hack here for speed; this is a relatively
6126 // hot path, and isNullPointerConstant is slow.
6127 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6128 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6129
6130 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6131
6132 // Avoid analyzing cases where the result will either be invalid (and
6133 // diagnosed as such) or entirely valid and not something to warn about.
6134 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6135 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6136 return;
6137
6138 // Comparison operations would not make sense with a null pointer no matter
6139 // what the other expression is.
6140 if (!IsCompare) {
6141 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6142 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6143 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6144 return;
6145 }
6146
6147 // The rest of the operations only make sense with a null pointer
6148 // if the other expression is a pointer.
6149 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6150 NonNullType->canDecayToPointerType())
6151 return;
6152
6153 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6154 << LHSNull /* LHS is NULL */ << NonNullType
6155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6156}
6157
Richard Trieu08062aa2011-09-06 21:01:04 +00006158QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006159 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006160 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006161 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6162
Richard Trieu08062aa2011-09-06 21:01:04 +00006163 if (LHS.get()->getType()->isVectorType() ||
6164 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006165 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006166
Richard Trieuccd891a2011-09-09 01:45:06 +00006167 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006168 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006169 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006170
David Chisnall7a7ee302012-01-16 17:27:18 +00006171
Eli Friedman860a3192012-06-16 02:19:17 +00006172 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006173 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006174
Chris Lattner7ef655a2010-01-12 21:23:57 +00006175 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006176 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006177 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006178 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006179 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6180 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006181
Chris Lattner7ef655a2010-01-12 21:23:57 +00006182 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006183}
6184
Chris Lattner7ef655a2010-01-12 21:23:57 +00006185QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006186 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006187 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6188
Richard Trieu08062aa2011-09-06 21:01:04 +00006189 if (LHS.get()->getType()->isVectorType() ||
6190 RHS.get()->getType()->isVectorType()) {
6191 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6192 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006193 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006194 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006195 }
Steve Naroff90045e82007-07-13 23:32:42 +00006196
Richard Trieuccd891a2011-09-09 01:45:06 +00006197 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006198 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006199 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006200
Eli Friedman860a3192012-06-16 02:19:17 +00006201 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006202 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006203
Chris Lattner7ef655a2010-01-12 21:23:57 +00006204 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006205 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006206 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006207 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6208 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006209
Chris Lattner7ef655a2010-01-12 21:23:57 +00006210 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006211}
6212
Chandler Carruth13b21be2011-06-27 08:02:19 +00006213/// \brief Diagnose invalid arithmetic on two void pointers.
6214static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006215 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006216 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006217 ? diag::err_typecheck_pointer_arith_void_type
6218 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006219 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6220 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006221}
6222
6223/// \brief Diagnose invalid arithmetic on a void pointer.
6224static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6225 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006226 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006227 ? diag::err_typecheck_pointer_arith_void_type
6228 : diag::ext_gnu_void_ptr)
6229 << 0 /* one pointer */ << Pointer->getSourceRange();
6230}
6231
6232/// \brief Diagnose invalid arithmetic on two function pointers.
6233static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6234 Expr *LHS, Expr *RHS) {
6235 assert(LHS->getType()->isAnyPointerType());
6236 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006237 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006238 ? diag::err_typecheck_pointer_arith_function_type
6239 : diag::ext_gnu_ptr_func_arith)
6240 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6241 // We only show the second type if it differs from the first.
6242 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6243 RHS->getType())
6244 << RHS->getType()->getPointeeType()
6245 << LHS->getSourceRange() << RHS->getSourceRange();
6246}
6247
6248/// \brief Diagnose invalid arithmetic on a function pointer.
6249static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6250 Expr *Pointer) {
6251 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006252 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006253 ? diag::err_typecheck_pointer_arith_function_type
6254 : diag::ext_gnu_ptr_func_arith)
6255 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6256 << 0 /* one pointer, so only one type */
6257 << Pointer->getSourceRange();
6258}
6259
Richard Trieud9f19342011-09-12 18:08:02 +00006260/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006261///
6262/// \returns True if pointer has incomplete type
6263static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6264 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006265 assert(Operand->getType()->isAnyPointerType() &&
6266 !Operand->getType()->isDependentType());
6267 QualType PointeeTy = Operand->getType()->getPointeeType();
6268 return S.RequireCompleteType(Loc, PointeeTy,
6269 diag::err_typecheck_arithmetic_incomplete_type,
6270 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006271}
6272
Chandler Carruth13b21be2011-06-27 08:02:19 +00006273/// \brief Check the validity of an arithmetic pointer operand.
6274///
6275/// If the operand has pointer type, this code will check for pointer types
6276/// which are invalid in arithmetic operations. These will be diagnosed
6277/// appropriately, including whether or not the use is supported as an
6278/// extension.
6279///
6280/// \returns True when the operand is valid to use (even if as an extension).
6281static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6282 Expr *Operand) {
6283 if (!Operand->getType()->isAnyPointerType()) return true;
6284
6285 QualType PointeeTy = Operand->getType()->getPointeeType();
6286 if (PointeeTy->isVoidType()) {
6287 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006288 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006289 }
6290 if (PointeeTy->isFunctionType()) {
6291 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006292 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006293 }
6294
Richard Trieu097ecd22011-09-02 02:15:37 +00006295 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006296
6297 return true;
6298}
6299
6300/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6301/// operands.
6302///
6303/// This routine will diagnose any invalid arithmetic on pointer operands much
6304/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6305/// for emitting a single diagnostic even for operations where both LHS and RHS
6306/// are (potentially problematic) pointers.
6307///
6308/// \returns True when the operand is valid to use (even if as an extension).
6309static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006310 Expr *LHSExpr, Expr *RHSExpr) {
6311 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6312 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006313 if (!isLHSPointer && !isRHSPointer) return true;
6314
6315 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006316 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6317 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006318
6319 // Check for arithmetic on pointers to incomplete types.
6320 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6321 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6322 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006323 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6324 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6325 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006326
David Blaikie4e4d0842012-03-11 07:00:24 +00006327 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006328 }
6329
6330 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6331 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6332 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006333 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6334 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6335 RHSExpr);
6336 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006337
David Blaikie4e4d0842012-03-11 07:00:24 +00006338 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006339 }
6340
John McCall1503f0d2012-07-31 05:14:30 +00006341 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6342 return false;
6343 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6344 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006345
Chandler Carruth13b21be2011-06-27 08:02:19 +00006346 return true;
6347}
6348
Nico Weber1cb2d742012-03-02 22:01:22 +00006349/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6350/// literal.
6351static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6352 Expr *LHSExpr, Expr *RHSExpr) {
6353 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6354 Expr* IndexExpr = RHSExpr;
6355 if (!StrExpr) {
6356 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6357 IndexExpr = LHSExpr;
6358 }
6359
6360 bool IsStringPlusInt = StrExpr &&
6361 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6362 if (!IsStringPlusInt)
6363 return;
6364
6365 llvm::APSInt index;
6366 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6367 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6368 if (index.isNonNegative() &&
6369 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6370 index.isUnsigned()))
6371 return;
6372 }
6373
6374 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6375 Self.Diag(OpLoc, diag::warn_string_plus_int)
6376 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6377
6378 // Only print a fixit for "str" + int, not for int + "str".
6379 if (IndexExpr == RHSExpr) {
6380 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6381 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6382 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6383 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6384 << FixItHint::CreateInsertion(EndLoc, "]");
6385 } else
6386 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6387}
6388
Richard Trieud9f19342011-09-12 18:08:02 +00006389/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006390static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006391 Expr *LHSExpr, Expr *RHSExpr) {
6392 assert(LHSExpr->getType()->isAnyPointerType());
6393 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006394 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006395 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6396 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006397}
6398
Chris Lattner7ef655a2010-01-12 21:23:57 +00006399QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006400 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6401 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006402 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6403
Richard Trieudef75842011-09-06 21:13:51 +00006404 if (LHS.get()->getType()->isVectorType() ||
6405 RHS.get()->getType()->isVectorType()) {
6406 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006407 if (CompLHSTy) *CompLHSTy = compType;
6408 return compType;
6409 }
Steve Naroff49b45262007-07-13 16:58:59 +00006410
Richard Trieudef75842011-09-06 21:13:51 +00006411 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6412 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006413 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006414
Nico Weber1cb2d742012-03-02 22:01:22 +00006415 // Diagnose "string literal" '+' int.
6416 if (Opc == BO_Add)
6417 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6418
Reid Spencer5f016e22007-07-11 17:01:13 +00006419 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006420 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006421 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006422 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006423 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006424
John McCall1503f0d2012-07-31 05:14:30 +00006425 // Type-checking. Ultimately the pointer's going to be in PExp;
6426 // note that we bias towards the LHS being the pointer.
6427 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006428
John McCall1503f0d2012-07-31 05:14:30 +00006429 bool isObjCPointer;
6430 if (PExp->getType()->isPointerType()) {
6431 isObjCPointer = false;
6432 } else if (PExp->getType()->isObjCObjectPointerType()) {
6433 isObjCPointer = true;
6434 } else {
6435 std::swap(PExp, IExp);
6436 if (PExp->getType()->isPointerType()) {
6437 isObjCPointer = false;
6438 } else if (PExp->getType()->isObjCObjectPointerType()) {
6439 isObjCPointer = true;
6440 } else {
6441 return InvalidOperands(Loc, LHS, RHS);
6442 }
6443 }
6444 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006445
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006446 if (!IExp->getType()->isIntegerType())
6447 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006448
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006449 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6450 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006451
John McCall1503f0d2012-07-31 05:14:30 +00006452 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006453 return QualType();
6454
6455 // Check array bounds for pointer arithemtic
6456 CheckArrayAccess(PExp, IExp);
6457
6458 if (CompLHSTy) {
6459 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6460 if (LHSTy.isNull()) {
6461 LHSTy = LHS.get()->getType();
6462 if (LHSTy->isPromotableIntegerType())
6463 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006464 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006465 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006466 }
6467
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006468 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006469}
6470
Chris Lattnereca7be62008-04-07 05:30:13 +00006471// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006472QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006473 SourceLocation Loc,
6474 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006475 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6476
Richard Trieudef75842011-09-06 21:13:51 +00006477 if (LHS.get()->getType()->isVectorType() ||
6478 RHS.get()->getType()->isVectorType()) {
6479 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006480 if (CompLHSTy) *CompLHSTy = compType;
6481 return compType;
6482 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006483
Richard Trieudef75842011-09-06 21:13:51 +00006484 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6485 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006486 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006487
Chris Lattner6e4ab612007-12-09 21:53:25 +00006488 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006489
Chris Lattner6e4ab612007-12-09 21:53:25 +00006490 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006491 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006492 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006493 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006494 }
Mike Stump1eb44332009-09-09 15:08:12 +00006495
Chris Lattner6e4ab612007-12-09 21:53:25 +00006496 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006497 if (LHS.get()->getType()->isAnyPointerType()) {
6498 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006499
Chris Lattnerb5f15622009-04-24 23:50:08 +00006500 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006501 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6502 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006503 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006504
Chris Lattner6e4ab612007-12-09 21:53:25 +00006505 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006506 if (RHS.get()->getType()->isIntegerType()) {
6507 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006508 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006509
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006510 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006511 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6512 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006513
Richard Trieudef75842011-09-06 21:13:51 +00006514 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6515 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006516 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006517
Chris Lattner6e4ab612007-12-09 21:53:25 +00006518 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006519 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006520 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006521 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006522
David Blaikie4e4d0842012-03-11 07:00:24 +00006523 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006524 // Pointee types must be the same: C++ [expr.add]
6525 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006526 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006527 }
6528 } else {
6529 // Pointee types must be compatible C99 6.5.6p3
6530 if (!Context.typesAreCompatible(
6531 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6532 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006533 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006534 return QualType();
6535 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006536 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006537
Chandler Carruth13b21be2011-06-27 08:02:19 +00006538 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006539 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006540 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006541
Richard Trieudef75842011-09-06 21:13:51 +00006542 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006543 return Context.getPointerDiffType();
6544 }
6545 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006546
Richard Trieudef75842011-09-06 21:13:51 +00006547 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006548}
6549
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006550static bool isScopedEnumerationType(QualType T) {
6551 if (const EnumType *ET = dyn_cast<EnumType>(T))
6552 return ET->getDecl()->isScoped();
6553 return false;
6554}
6555
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006556static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006557 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006558 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006559 llvm::APSInt Right;
6560 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006561 if (RHS.get()->isValueDependent() ||
6562 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006563 return;
6564
6565 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006566 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006567 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006568 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006569 return;
6570 }
6571 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006572 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006573 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006574 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006575 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006576 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006577 return;
6578 }
6579 if (Opc != BO_Shl)
6580 return;
6581
6582 // When left shifting an ICE which is signed, we can check for overflow which
6583 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6584 // integers have defined behavior modulo one more than the maximum value
6585 // representable in the result type, so never warn for those.
6586 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006587 if (LHS.get()->isValueDependent() ||
6588 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6589 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006590 return;
6591 llvm::APInt ResultBits =
6592 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6593 if (LeftBits.uge(ResultBits))
6594 return;
6595 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6596 Result = Result.shl(Right);
6597
Ted Kremenekfa821382011-06-15 00:54:52 +00006598 // Print the bit representation of the signed integer as an unsigned
6599 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006600 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006601 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6602
Chandler Carruth21206d52011-02-23 23:34:11 +00006603 // If we are only missing a sign bit, this is less likely to result in actual
6604 // bugs -- if the result is cast back to an unsigned type, it will have the
6605 // expected value. Thus we place this behind a different warning that can be
6606 // turned off separately if needed.
6607 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006608 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006609 << HexResult.str() << LHSType
6610 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006611 return;
6612 }
6613
6614 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006615 << HexResult.str() << Result.getMinSignedBits() << LHSType
6616 << Left.getBitWidth() << LHS.get()->getSourceRange()
6617 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006618}
6619
Chris Lattnereca7be62008-04-07 05:30:13 +00006620// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006621QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006622 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006623 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006624 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6625
Chris Lattnerca5eede2007-12-12 05:47:28 +00006626 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006627 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6628 !RHS.get()->getType()->hasIntegerRepresentation())
6629 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006630
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006631 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6632 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006633 if (isScopedEnumerationType(LHS.get()->getType()) ||
6634 isScopedEnumerationType(RHS.get()->getType())) {
6635 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006636 }
6637
Nate Begeman2207d792009-10-25 02:26:48 +00006638 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006639 if (LHS.get()->getType()->isVectorType() ||
6640 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006641 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006642
Chris Lattnerca5eede2007-12-12 05:47:28 +00006643 // Shifts don't perform usual arithmetic conversions, they just do integer
6644 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006645
John McCall1bc80af2010-12-16 19:28:59 +00006646 // For the LHS, do usual unary conversions, but then reset them away
6647 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006648 ExprResult OldLHS = LHS;
6649 LHS = UsualUnaryConversions(LHS.take());
6650 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006651 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006652 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006653 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006654
6655 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006656 RHS = UsualUnaryConversions(RHS.take());
6657 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006658 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006659
Ryan Flynnd0439682009-08-07 16:20:20 +00006660 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006661 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006662
Chris Lattnerca5eede2007-12-12 05:47:28 +00006663 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006664 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006665}
6666
Chandler Carruth99919472010-07-10 12:30:03 +00006667static bool IsWithinTemplateSpecialization(Decl *D) {
6668 if (DeclContext *DC = D->getDeclContext()) {
6669 if (isa<ClassTemplateSpecializationDecl>(DC))
6670 return true;
6671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6672 return FD->isFunctionTemplateSpecialization();
6673 }
6674 return false;
6675}
6676
Richard Trieue648ac32011-09-02 03:48:46 +00006677/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006678static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6679 ExprResult &RHS) {
6680 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6681 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006682
6683 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6684 if (!LHSEnumType)
6685 return;
6686 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6687 if (!RHSEnumType)
6688 return;
6689
6690 // Ignore anonymous enums.
6691 if (!LHSEnumType->getDecl()->getIdentifier())
6692 return;
6693 if (!RHSEnumType->getDecl()->getIdentifier())
6694 return;
6695
6696 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6697 return;
6698
6699 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6700 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006702}
6703
Richard Trieu7be1be02011-09-02 02:55:45 +00006704/// \brief Diagnose bad pointer comparisons.
6705static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006706 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006707 bool IsError) {
6708 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006709 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006710 << LHS.get()->getType() << RHS.get()->getType()
6711 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006712}
6713
6714/// \brief Returns false if the pointers are converted to a composite type,
6715/// true otherwise.
6716static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006717 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006718 // C++ [expr.rel]p2:
6719 // [...] Pointer conversions (4.10) and qualification
6720 // conversions (4.4) are performed on pointer operands (or on
6721 // a pointer operand and a null pointer constant) to bring
6722 // them to their composite pointer type. [...]
6723 //
6724 // C++ [expr.eq]p1 uses the same notion for (in)equality
6725 // comparisons of pointers.
6726
6727 // C++ [expr.eq]p2:
6728 // In addition, pointers to members can be compared, or a pointer to
6729 // member and a null pointer constant. Pointer to member conversions
6730 // (4.11) and qualification conversions (4.4) are performed to bring
6731 // them to a common type. If one operand is a null pointer constant,
6732 // the common type is the type of the other operand. Otherwise, the
6733 // common type is a pointer to member type similar (4.4) to the type
6734 // of one of the operands, with a cv-qualification signature (4.4)
6735 // that is the union of the cv-qualification signatures of the operand
6736 // types.
6737
Richard Trieuba261492011-09-06 21:27:33 +00006738 QualType LHSType = LHS.get()->getType();
6739 QualType RHSType = RHS.get()->getType();
6740 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6741 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006742
6743 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006744 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006745 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006746 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006747 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006748 return true;
6749 }
6750
6751 if (NonStandardCompositeType)
6752 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006753 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6754 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006755
Richard Trieuba261492011-09-06 21:27:33 +00006756 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6757 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006758 return false;
6759}
6760
6761static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006762 ExprResult &LHS,
6763 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006764 bool IsError) {
6765 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6766 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006767 << LHS.get()->getType() << RHS.get()->getType()
6768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006769}
6770
Jordan Rose9f63a452012-06-08 21:14:25 +00006771static bool isObjCObjectLiteral(ExprResult &E) {
6772 switch (E.get()->getStmtClass()) {
6773 case Stmt::ObjCArrayLiteralClass:
6774 case Stmt::ObjCDictionaryLiteralClass:
6775 case Stmt::ObjCStringLiteralClass:
6776 case Stmt::ObjCBoxedExprClass:
6777 return true;
6778 default:
6779 // Note that ObjCBoolLiteral is NOT an object literal!
6780 return false;
6781 }
6782}
6783
Jordan Rose8d872ca2012-07-17 17:46:40 +00006784static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6785 // Get the LHS object's interface type.
6786 QualType Type = LHS->getType();
6787 QualType InterfaceType;
6788 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6789 InterfaceType = PTy->getPointeeType();
6790 if (const ObjCObjectType *iQFaceTy =
6791 InterfaceType->getAsObjCQualifiedInterfaceType())
6792 InterfaceType = iQFaceTy->getBaseType();
6793 } else {
6794 // If this is not actually an Objective-C object, bail out.
6795 return false;
6796 }
6797
6798 // If the RHS isn't an Objective-C object, bail out.
6799 if (!RHS->getType()->isObjCObjectPointerType())
6800 return false;
6801
6802 // Try to find the -isEqual: method.
6803 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6804 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6805 InterfaceType,
6806 /*instance=*/true);
6807 if (!Method) {
6808 if (Type->isObjCIdType()) {
6809 // For 'id', just check the global pool.
6810 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6811 /*receiverId=*/true,
6812 /*warn=*/false);
6813 } else {
6814 // Check protocols.
6815 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6816 cast<ObjCObjectPointerType>(Type),
6817 /*instance=*/true);
6818 }
6819 }
6820
6821 if (!Method)
6822 return false;
6823
6824 QualType T = Method->param_begin()[0]->getType();
6825 if (!T->isObjCObjectPointerType())
6826 return false;
6827
6828 QualType R = Method->getResultType();
6829 if (!R->isScalarType())
6830 return false;
6831
6832 return true;
6833}
6834
6835static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6836 ExprResult &LHS, ExprResult &RHS,
6837 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006838 Expr *Literal;
6839 Expr *Other;
6840 if (isObjCObjectLiteral(LHS)) {
6841 Literal = LHS.get();
6842 Other = RHS.get();
6843 } else {
6844 Literal = RHS.get();
6845 Other = LHS.get();
6846 }
6847
6848 // Don't warn on comparisons against nil.
6849 Other = Other->IgnoreParenCasts();
6850 if (Other->isNullPointerConstant(S.getASTContext(),
6851 Expr::NPC_ValueDependentIsNotNull))
6852 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006853
Jordan Roseeec207f2012-07-17 17:46:44 +00006854 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006855 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006856 enum {
6857 LK_Array,
6858 LK_Dictionary,
6859 LK_Numeric,
6860 LK_Boxed,
6861 LK_String
6862 } LiteralKind;
6863
Jordan Rose9f63a452012-06-08 21:14:25 +00006864 switch (Literal->getStmtClass()) {
6865 case Stmt::ObjCStringLiteralClass:
6866 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006867 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006868 break;
6869 case Stmt::ObjCArrayLiteralClass:
6870 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006871 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006872 break;
6873 case Stmt::ObjCDictionaryLiteralClass:
6874 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006875 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006876 break;
6877 case Stmt::ObjCBoxedExprClass: {
6878 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6879 switch (Inner->getStmtClass()) {
6880 case Stmt::IntegerLiteralClass:
6881 case Stmt::FloatingLiteralClass:
6882 case Stmt::CharacterLiteralClass:
6883 case Stmt::ObjCBoolLiteralExprClass:
6884 case Stmt::CXXBoolLiteralExprClass:
6885 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006886 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006887 break;
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) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006892 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006893 break;
6894 }
6895 // FALLTHROUGH
6896 }
6897 default:
6898 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006899 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006900 break;
6901 }
6902 break;
6903 }
6904 default:
6905 llvm_unreachable("Unknown Objective-C object literal kind");
6906 }
6907
Jordan Roseeec207f2012-07-17 17:46:44 +00006908 if (LiteralKind == LK_String)
6909 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6910 << Literal->getSourceRange();
6911 else
6912 S.Diag(Loc, diag::warn_objc_literal_comparison)
6913 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006914
Jordan Rose8d872ca2012-07-17 17:46:40 +00006915 if (BinaryOperator::isEqualityOp(Opc) &&
6916 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6917 SourceLocation Start = LHS.get()->getLocStart();
6918 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6919 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006920
Jordan Rose8d872ca2012-07-17 17:46:40 +00006921 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6922 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6923 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6924 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006925 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006926}
6927
Douglas Gregor0c6db942009-05-04 06:07:12 +00006928// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006929QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006930 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006931 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006932 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6933
John McCall2de56d12010-08-25 11:45:40 +00006934 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006935
Chris Lattner02dd4b12009-12-05 05:40:13 +00006936 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006937 if (LHS.get()->getType()->isVectorType() ||
6938 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006939 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006940
Richard Trieuf1775fb2011-09-06 21:43:51 +00006941 QualType LHSType = LHS.get()->getType();
6942 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006943
Richard Trieuf1775fb2011-09-06 21:43:51 +00006944 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6945 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006946
Richard Trieuf1775fb2011-09-06 21:43:51 +00006947 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006948
Richard Trieuf1775fb2011-09-06 21:43:51 +00006949 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006950 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006951 !LHS.get()->getLocStart().isMacroID() &&
6952 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006953 // For non-floating point types, check for self-comparisons of the form
6954 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6955 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006956 //
6957 // NOTE: Don't warn about comparison expressions resulting from macro
6958 // expansion. Also don't warn about comparisons which are only self
6959 // comparisons within a template specialization. The warnings should catch
6960 // obvious cases in the definition of the template anyways. The idea is to
6961 // warn when the typed comparison operator will always evaluate to the same
6962 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006963 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006964 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006965 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006966 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006967 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006968 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006969 << (Opc == BO_EQ
6970 || Opc == BO_LE
6971 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006972 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006973 !DRL->getDecl()->getType()->isReferenceType() &&
6974 !DRR->getDecl()->getType()->isReferenceType()) {
6975 // what is it always going to eval to?
6976 char always_evals_to;
6977 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006978 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006979 always_evals_to = 0; // false
6980 break;
John McCall2de56d12010-08-25 11:45:40 +00006981 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006982 always_evals_to = 1; // true
6983 break;
6984 default:
6985 // best we can say is 'a constant'
6986 always_evals_to = 2; // e.g. array1 <= array2
6987 break;
6988 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006989 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006990 << 1 // array
6991 << always_evals_to);
6992 }
6993 }
Chandler Carruth99919472010-07-10 12:30:03 +00006994 }
Mike Stump1eb44332009-09-09 15:08:12 +00006995
Chris Lattner55660a72009-03-08 19:39:53 +00006996 if (isa<CastExpr>(LHSStripped))
6997 LHSStripped = LHSStripped->IgnoreParenCasts();
6998 if (isa<CastExpr>(RHSStripped))
6999 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007000
Chris Lattner55660a72009-03-08 19:39:53 +00007001 // Warn about comparisons against a string constant (unless the other
7002 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007003 Expr *literalString = 0;
7004 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007005 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007006 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007007 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007008 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007009 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007010 } else if ((isa<StringLiteral>(RHSStripped) ||
7011 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007012 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007013 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007014 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007015 literalStringStripped = RHSStripped;
7016 }
7017
7018 if (literalString) {
7019 std::string resultComparison;
7020 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007021 case BO_LT: resultComparison = ") < 0"; break;
7022 case BO_GT: resultComparison = ") > 0"; break;
7023 case BO_LE: resultComparison = ") <= 0"; break;
7024 case BO_GE: resultComparison = ") >= 0"; break;
7025 case BO_EQ: resultComparison = ") == 0"; break;
7026 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007027 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007028 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007029
Ted Kremenek351ba912011-02-23 01:52:04 +00007030 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007031 PDiag(diag::warn_stringcompare)
7032 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007033 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007034 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007035 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007036
Douglas Gregord64fdd02010-06-08 19:50:34 +00007037 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007038 if (LHS.get()->getType()->isArithmeticType() &&
7039 RHS.get()->getType()->isArithmeticType()) {
7040 UsualArithmeticConversions(LHS, RHS);
7041 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007042 return QualType();
7043 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007044 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007045 LHS = UsualUnaryConversions(LHS.take());
7046 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007047 return QualType();
7048
Richard Trieuf1775fb2011-09-06 21:43:51 +00007049 RHS = UsualUnaryConversions(RHS.take());
7050 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007051 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007052 }
7053
Richard Trieuf1775fb2011-09-06 21:43:51 +00007054 LHSType = LHS.get()->getType();
7055 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007056
Douglas Gregor447b69e2008-11-19 03:25:36 +00007057 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007058 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007059
Richard Trieuccd891a2011-09-09 01:45:06 +00007060 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007061 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007062 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007063 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007064 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007065 if (LHSType->hasFloatingRepresentation())
7066 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007067
Richard Trieuf1775fb2011-09-06 21:43:51 +00007068 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007069 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007071
Richard Trieuf1775fb2011-09-06 21:43:51 +00007072 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007073 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007074 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007075 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007076
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007077 // All of the following pointer-related warnings are GCC extensions, except
7078 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007079 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007080 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007081 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007082 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007083 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007084
David Blaikie4e4d0842012-03-11 07:00:24 +00007085 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007086 if (LCanPointeeTy == RCanPointeeTy)
7087 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007088 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007089 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7090 // Valid unless comparison between non-null pointer and function pointer
7091 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007092 // In a SFINAE context, we treat this as a hard error to maintain
7093 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007094 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7095 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007096 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007097 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007098
7099 if (isSFINAEContext())
7100 return QualType();
7101
Richard Trieuf1775fb2011-09-06 21:43:51 +00007102 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007103 return ResultTy;
7104 }
7105 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007106
Richard Trieuf1775fb2011-09-06 21:43:51 +00007107 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007108 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007109 else
7110 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007111 }
Eli Friedman3075e762009-08-23 00:27:47 +00007112 // C99 6.5.9p2 and C99 6.5.8p2
7113 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7114 RCanPointeeTy.getUnqualifiedType())) {
7115 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007116 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007117 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007118 << LHSType << RHSType << LHS.get()->getSourceRange()
7119 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007120 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007121 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007122 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7123 // Valid unless comparison between non-null pointer and function pointer
7124 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007125 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007126 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007127 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007128 } else {
7129 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007130 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007131 }
John McCall34d6f932011-03-11 04:25:25 +00007132 if (LCanPointeeTy != RCanPointeeTy) {
7133 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007134 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007135 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007136 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007137 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007138 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007139 }
Mike Stump1eb44332009-09-09 15:08:12 +00007140
David Blaikie4e4d0842012-03-11 07:00:24 +00007141 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007142 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007143 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007144 return ResultTy;
7145
Mike Stump1eb44332009-09-09 15:08:12 +00007146 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007147 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007148 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007149 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007150 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007151 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7152 RHS = ImpCastExprToType(RHS.take(), LHSType,
7153 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007154 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007155 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007156 return ResultTy;
7157 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007158 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007159 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007160 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007161 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7162 LHS = ImpCastExprToType(LHS.take(), RHSType,
7163 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007164 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007165 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007166 return ResultTy;
7167 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007168
7169 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007170 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007171 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7172 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007173 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007174 else
7175 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007176 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007177
7178 // Handle scoped enumeration types specifically, since they don't promote
7179 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007180 if (LHS.get()->getType()->isEnumeralType() &&
7181 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7182 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007183 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007184 }
Mike Stump1eb44332009-09-09 15:08:12 +00007185
Steve Naroff1c7d0672008-09-04 15:10:53 +00007186 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007187 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007188 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007189 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7190 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007191
Steve Naroff1c7d0672008-09-04 15:10:53 +00007192 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007193 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007194 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007195 << LHSType << RHSType << LHS.get()->getSourceRange()
7196 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007197 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007198 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007199 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007200 }
John Wiegley429bb272011-04-08 18:41:53 +00007201
Steve Naroff59f53942008-09-28 01:11:11 +00007202 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007203 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007204 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7205 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007206 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007207 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007208 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007209 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007210 ->getPointeeType()->isVoidType())))
7211 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007212 << LHSType << RHSType << LHS.get()->getSourceRange()
7213 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007214 }
John McCall34d6f932011-03-11 04:25:25 +00007215 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007216 LHS = ImpCastExprToType(LHS.take(), RHSType,
7217 RHSType->isPointerType() ? CK_BitCast
7218 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007219 else
John McCall1d9b3b22011-09-09 05:25:32 +00007220 RHS = ImpCastExprToType(RHS.take(), LHSType,
7221 LHSType->isPointerType() ? CK_BitCast
7222 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007223 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007224 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007225
Richard Trieuf1775fb2011-09-06 21:43:51 +00007226 if (LHSType->isObjCObjectPointerType() ||
7227 RHSType->isObjCObjectPointerType()) {
7228 const PointerType *LPT = LHSType->getAs<PointerType>();
7229 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007230 if (LPT || RPT) {
7231 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7232 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007233
Steve Naroffa8069f12008-11-17 19:49:16 +00007234 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007235 !Context.typesAreCompatible(LHSType, RHSType)) {
7236 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007237 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +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 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007242 else
John McCall1d9b3b22011-09-09 05:25:32 +00007243 RHS = ImpCastExprToType(RHS.take(), LHSType,
7244 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007245 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007246 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007247 if (LHSType->isObjCObjectPointerType() &&
7248 RHSType->isObjCObjectPointerType()) {
7249 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7250 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007251 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007252 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007253 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007254
John McCall34d6f932011-03-11 04:25:25 +00007255 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007256 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007257 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007258 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007259 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007260 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007261 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007262 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7263 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007264 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007265 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007266 if (LangOpts.DebuggerSupport) {
7267 // Under a debugger, allow the comparison of pointers to integers,
7268 // since users tend to want to compare addresses.
7269 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007270 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007271 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007272 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007273 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007274 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007275 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007276 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7277 isError = true;
7278 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007279 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007280
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007281 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007282 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007283 << LHSType << RHSType << LHS.get()->getSourceRange()
7284 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007285 if (isError)
7286 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007287 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007288
Richard Trieuf1775fb2011-09-06 21:43:51 +00007289 if (LHSType->isIntegerType())
7290 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007291 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007292 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007293 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007294 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007295 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007296 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007297
Steve Naroff39218df2008-09-04 16:56:14 +00007298 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007299 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007300 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7301 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007302 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007303 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007304 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007305 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7306 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007307 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007308 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007309
Richard Trieuf1775fb2011-09-06 21:43:51 +00007310 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007311}
7312
Tanya Lattner4f692c22012-01-16 21:02:28 +00007313
7314// Return a signed type that is of identical size and number of elements.
7315// For floating point vectors, return an integer type of identical size
7316// and number of elements.
7317QualType Sema::GetSignedVectorType(QualType V) {
7318 const VectorType *VTy = V->getAs<VectorType>();
7319 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7320 if (TypeSize == Context.getTypeSize(Context.CharTy))
7321 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7322 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7323 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7324 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7325 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7326 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7327 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7328 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7329 "Unhandled vector element size in vector compare");
7330 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7331}
7332
Nate Begemanbe2341d2008-07-14 18:02:46 +00007333/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007334/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007335/// like a scalar comparison, a vector comparison produces a vector of integer
7336/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007337QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007338 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007339 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007340 // Check to make sure we're operating on vectors of the same type and width,
7341 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007342 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007343 if (vType.isNull())
7344 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007345
Richard Trieu9f60dee2011-09-07 01:19:57 +00007346 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007347
Anton Yartsev7870b132011-03-27 15:36:07 +00007348 // If AltiVec, the comparison results in a numeric type, i.e.
7349 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007350 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007351 return Context.getLogicalOperationType();
7352
Nate Begemanbe2341d2008-07-14 18:02:46 +00007353 // For non-floating point types, check for self-comparisons of the form
7354 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7355 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007356 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007357 if (DeclRefExpr* DRL
7358 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7359 if (DeclRefExpr* DRR
7360 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007361 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007362 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007363 PDiag(diag::warn_comparison_always)
7364 << 0 // self-
7365 << 2 // "a constant"
7366 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007367 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007368
Nate Begemanbe2341d2008-07-14 18:02:46 +00007369 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007370 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007371 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007372 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007373 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007374
7375 // Return a signed type for the vector.
7376 return GetSignedVectorType(LHSType);
7377}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007378
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007379QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7380 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007381 // Ensure that either both operands are of the same vector type, or
7382 // one operand is of a vector type and the other is of its element type.
7383 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7384 if (vType.isNull() || vType->isFloatingType())
7385 return InvalidOperands(Loc, LHS, RHS);
7386
7387 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007388}
7389
Reid Spencer5f016e22007-07-11 17:01:13 +00007390inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007391 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007392 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7393
Richard Trieu9f60dee2011-09-07 01:19:57 +00007394 if (LHS.get()->getType()->isVectorType() ||
7395 RHS.get()->getType()->isVectorType()) {
7396 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7397 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007398 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007399
Richard Trieu9f60dee2011-09-07 01:19:57 +00007400 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007401 }
Steve Naroff90045e82007-07-13 23:32:42 +00007402
Richard Trieu9f60dee2011-09-07 01:19:57 +00007403 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7404 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007405 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007406 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007407 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007408 LHS = LHSResult.take();
7409 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007410
Eli Friedman860a3192012-06-16 02:19:17 +00007411 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007412 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007413 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007414}
7415
7416inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007417 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007418
Tanya Lattner4f692c22012-01-16 21:02:28 +00007419 // Check vector operands differently.
7420 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7421 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7422
Chris Lattner90a8f272010-07-13 19:41:32 +00007423 // Diagnose cases where the user write a logical and/or but probably meant a
7424 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7425 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007426 if (LHS.get()->getType()->isIntegerType() &&
7427 !LHS.get()->getType()->isBooleanType() &&
7428 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007429 // Don't warn in macros or template instantiations.
7430 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007431 // If the RHS can be constant folded, and if it constant folds to something
7432 // that isn't 0 or 1 (which indicate a potential logical operation that
7433 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007434 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007435 llvm::APSInt Result;
7436 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007437 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007438 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007439 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007440 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007441 << (Opc == BO_LAnd ? "&&" : "||");
7442 // Suggest replacing the logical operator with the bitwise version
7443 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7444 << (Opc == BO_LAnd ? "&" : "|")
7445 << FixItHint::CreateReplacement(SourceRange(
7446 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007447 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007448 Opc == BO_LAnd ? "&" : "|");
7449 if (Opc == BO_LAnd)
7450 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7451 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7452 << FixItHint::CreateRemoval(
7453 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007454 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007455 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007456 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007457 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007458 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007459 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007460
David Blaikie4e4d0842012-03-11 07:00:24 +00007461 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007462 LHS = UsualUnaryConversions(LHS.take());
7463 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007464 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007465
Richard Trieu9f60dee2011-09-07 01:19:57 +00007466 RHS = UsualUnaryConversions(RHS.take());
7467 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007468 return QualType();
7469
Richard Trieu9f60dee2011-09-07 01:19:57 +00007470 if (!LHS.get()->getType()->isScalarType() ||
7471 !RHS.get()->getType()->isScalarType())
7472 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007473
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007474 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007475 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007476
John McCall75f7c0f2010-06-04 00:29:51 +00007477 // The following is safe because we only use this method for
7478 // non-overloadable operands.
7479
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007480 // C++ [expr.log.and]p1
7481 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007482 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007483 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7484 if (LHSRes.isInvalid())
7485 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007486 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007487
Richard Trieu9f60dee2011-09-07 01:19:57 +00007488 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7489 if (RHSRes.isInvalid())
7490 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007491 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007492
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007493 // C++ [expr.log.and]p2
7494 // C++ [expr.log.or]p2
7495 // The result is a bool.
7496 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007497}
7498
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007499/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7500/// is a read-only property; return true if so. A readonly property expression
7501/// depends on various declarations and thus must be treated specially.
7502///
Mike Stump1eb44332009-09-09 15:08:12 +00007503static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007504 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7505 if (!PropExpr) return false;
7506 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007507
John McCall3c3b7f92011-10-25 17:37:35 +00007508 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7509 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007510 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007511 PropExpr->getBase()->getType();
7512
John McCall3c3b7f92011-10-25 17:37:35 +00007513 if (const ObjCObjectPointerType *OPT =
7514 BaseType->getAsObjCInterfacePointerType())
7515 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7516 if (S.isPropertyReadonly(PDecl, IFace))
7517 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007518 return false;
7519}
7520
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007521static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007522 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7523 if (!ME) return false;
7524 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7525 ObjCMessageExpr *Base =
7526 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7527 if (!Base) return false;
7528 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007529}
7530
John McCall78dae242012-03-13 00:37:01 +00007531/// Is the given expression (which must be 'const') a reference to a
7532/// variable which was originally non-const, but which has become
7533/// 'const' due to being captured within a block?
7534enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7535static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7536 assert(E->isLValue() && E->getType().isConstQualified());
7537 E = E->IgnoreParens();
7538
7539 // Must be a reference to a declaration from an enclosing scope.
7540 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7541 if (!DRE) return NCCK_None;
7542 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7543
7544 // The declaration must be a variable which is not declared 'const'.
7545 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7546 if (!var) return NCCK_None;
7547 if (var->getType().isConstQualified()) return NCCK_None;
7548 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7549
7550 // Decide whether the first capture was for a block or a lambda.
7551 DeclContext *DC = S.CurContext;
7552 while (DC->getParent() != var->getDeclContext())
7553 DC = DC->getParent();
7554 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7555}
7556
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007557/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7558/// emit an error and return true. If so, return false.
7559static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007560 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007561 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007562 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007563 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007564 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7565 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007566 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7567 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007568 if (IsLV == Expr::MLV_Valid)
7569 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007570
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007571 unsigned Diag = 0;
7572 bool NeedType = false;
7573 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007574 case Expr::MLV_ConstQualified:
7575 Diag = diag::err_typecheck_assign_const;
7576
John McCall78dae242012-03-13 00:37:01 +00007577 // Use a specialized diagnostic when we're assigning to an object
7578 // from an enclosing function or block.
7579 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7580 if (NCCK == NCCK_Block)
7581 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7582 else
7583 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7584 break;
7585 }
7586
John McCall7acddac2011-06-17 06:42:21 +00007587 // In ARC, use some specialized diagnostics for occasions where we
7588 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007589 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007590 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7591 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7592 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7593
John McCall7acddac2011-06-17 06:42:21 +00007594 // Use the normal diagnostic if it's pseudo-__strong but the
7595 // user actually wrote 'const'.
7596 if (var->isARCPseudoStrong() &&
7597 (!var->getTypeSourceInfo() ||
7598 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7599 // There are two pseudo-strong cases:
7600 // - self
John McCallf85e1932011-06-15 23:02:42 +00007601 ObjCMethodDecl *method = S.getCurMethodDecl();
7602 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007603 Diag = method->isClassMethod()
7604 ? diag::err_typecheck_arc_assign_self_class_method
7605 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007606
7607 // - fast enumeration variables
7608 else
John McCallf85e1932011-06-15 23:02:42 +00007609 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007610
John McCallf85e1932011-06-15 23:02:42 +00007611 SourceRange Assign;
7612 if (Loc != OrigLoc)
7613 Assign = SourceRange(OrigLoc, OrigLoc);
7614 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7615 // We need to preserve the AST regardless, so migration tool
7616 // can do its job.
7617 return false;
7618 }
7619 }
7620 }
7621
7622 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007623 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007624 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007625 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7626 NeedType = true;
7627 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007628 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007629 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7630 NeedType = true;
7631 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007632 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007633 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7634 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007635 case Expr::MLV_Valid:
7636 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007637 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007638 case Expr::MLV_MemberFunction:
7639 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007640 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7641 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007642 case Expr::MLV_IncompleteType:
7643 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007644 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007645 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007646 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007647 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7648 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007649 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007650 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007651 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007652 case Expr::MLV_InvalidMessageExpression:
7653 Diag = diag::error_readonly_message_assignment;
7654 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007655 case Expr::MLV_SubObjCPropertySetting:
7656 Diag = diag::error_no_subobject_property_setting;
7657 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007658 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007659
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007660 SourceRange Assign;
7661 if (Loc != OrigLoc)
7662 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007663 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007664 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007665 else
Mike Stump1eb44332009-09-09 15:08:12 +00007666 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007667 return true;
7668}
7669
Nico Weber7c81b432012-07-03 02:03:06 +00007670static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7671 SourceLocation Loc,
7672 Sema &Sema) {
7673 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007674 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7675 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7676 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7677 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007678 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007679 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007680
Nico Weber7c81b432012-07-03 02:03:06 +00007681 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007682 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7683 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7684 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7685 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7686 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7687 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007688 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007689 }
7690}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007691
7692// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007693QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007694 SourceLocation Loc,
7695 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007696 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7697
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007698 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007699 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007700 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007701
Richard Trieu268942b2011-09-07 01:33:52 +00007702 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007703 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7704 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007705 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007706 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007707 Expr *RHSCheck = RHS.get();
7708
Nico Weber7c81b432012-07-03 02:03:06 +00007709 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007710
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007711 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007712 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007713 if (RHS.isInvalid())
7714 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007715 // Special case of NSObject attributes on c-style pointer types.
7716 if (ConvTy == IncompatiblePointer &&
7717 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007718 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007719 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007720 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007721 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007722
John McCallf89e55a2010-11-18 06:31:45 +00007723 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007724 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007725 Diag(Loc, diag::err_objc_object_assignment)
7726 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007727
Chris Lattner2c156472008-08-21 18:04:13 +00007728 // If the RHS is a unary plus or minus, check to see if they = and + are
7729 // right next to each other. If so, the user may have typo'd "x =+ 4"
7730 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007731 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7732 RHSCheck = ICE->getSubExpr();
7733 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007734 if ((UO->getOpcode() == UO_Plus ||
7735 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007736 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007737 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007738 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007739 // And there is a space or other character before the subexpr of the
7740 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007741 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007742 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007743 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007744 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007745 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007746 }
Chris Lattner2c156472008-08-21 18:04:13 +00007747 }
John McCallf85e1932011-06-15 23:02:42 +00007748
7749 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007750 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7751 // Warn about retain cycles where a block captures the LHS, but
7752 // not if the LHS is a simple variable into which the block is
7753 // being stored...unless that variable can be captured by reference!
7754 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7755 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7756 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7757 checkRetainCycles(LHSExpr, RHS.get());
7758
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007759 // It is safe to assign a weak reference into a strong variable.
7760 // Although this code can still have problems:
7761 // id x = self.weakProp;
7762 // id y = self.weakProp;
7763 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7764 // paths through the function. This should be revisited if
7765 // -Wrepeated-use-of-weak is made flow-sensitive.
7766 DiagnosticsEngine::Level Level =
7767 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7768 RHS.get()->getLocStart());
7769 if (Level != DiagnosticsEngine::Ignored)
7770 getCurFunction()->markSafeWeakUse(RHS.get());
7771
Jordan Rosee10f4d32012-09-15 02:48:31 +00007772 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007773 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007774 }
John McCallf85e1932011-06-15 23:02:42 +00007775 }
Chris Lattner2c156472008-08-21 18:04:13 +00007776 } else {
7777 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007778 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007779 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007780
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007781 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007782 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007783 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007784
Richard Trieu268942b2011-09-07 01:33:52 +00007785 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007786
Reid Spencer5f016e22007-07-11 17:01:13 +00007787 // C99 6.5.16p3: The type of an assignment expression is the type of the
7788 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007789 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007790 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7791 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007792 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007793 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007794 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007795 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007796}
7797
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007798// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007799static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007800 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007801 LHS = S.CheckPlaceholderExpr(LHS.take());
7802 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007803 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007804 return QualType();
7805
John McCallcf2e5062010-10-12 07:14:40 +00007806 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7807 // operands, but not unary promotions.
7808 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007809
John McCallf6a16482010-12-04 03:47:34 +00007810 // So we treat the LHS as a ignored value, and in C++ we allow the
7811 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007812 LHS = S.IgnoredValueConversions(LHS.take());
7813 if (LHS.isInvalid())
7814 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007815
Eli Friedmana6115062012-05-24 00:47:05 +00007816 S.DiagnoseUnusedExprResult(LHS.get());
7817
David Blaikie4e4d0842012-03-11 07:00:24 +00007818 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007819 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7820 if (RHS.isInvalid())
7821 return QualType();
7822 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007823 S.RequireCompleteType(Loc, RHS.get()->getType(),
7824 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007825 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007826
John Wiegley429bb272011-04-08 18:41:53 +00007827 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007828}
7829
Steve Naroff49b45262007-07-13 16:58:59 +00007830/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7831/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007832static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7833 ExprValueKind &VK,
7834 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007835 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007836 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007837 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007838
Chris Lattner3528d352008-11-21 07:05:48 +00007839 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007840 // Atomic types can be used for increment / decrement where the non-atomic
7841 // versions can, so ignore the _Atomic() specifier for the purpose of
7842 // checking.
7843 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7844 ResType = ResAtomicType->getValueType();
7845
Chris Lattner3528d352008-11-21 07:05:48 +00007846 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007847
David Blaikie4e4d0842012-03-11 07:00:24 +00007848 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007849 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007850 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007851 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007852 return QualType();
7853 }
7854 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007855 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007856 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007857 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007858 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007859 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007860 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007861 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007862 } else if (ResType->isObjCObjectPointerType()) {
7863 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7864 // Otherwise, we just need a complete type.
7865 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7866 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7867 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007868 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007869 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007870 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007871 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007872 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007873 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007874 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007875 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007876 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007877 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007878 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007879 } else {
John McCall09431682010-11-18 19:01:18 +00007880 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007881 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007882 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007883 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007884 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007885 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007886 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007887 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007888 // In C++, a prefix increment is the same type as the operand. Otherwise
7889 // (in C or with postfix), the increment is the unqualified type of the
7890 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007891 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007892 VK = VK_LValue;
7893 return ResType;
7894 } else {
7895 VK = VK_RValue;
7896 return ResType.getUnqualifiedType();
7897 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007898}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007899
7900
Anders Carlsson369dee42008-02-01 07:15:58 +00007901/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007902/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007903/// where the declaration is needed for type checking. We only need to
7904/// handle cases when the expression references a function designator
7905/// or is an lvalue. Here are some examples:
7906/// - &(x) => x
7907/// - &*****f => f for f a function designator.
7908/// - &s.xx => s
7909/// - &s.zz[1].yy -> s, if zz is an array
7910/// - *(x + 1) -> x, if x is an array
7911/// - &"123"[2] -> 0
7912/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007913static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007914 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007915 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007916 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007917 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007918 // If this is an arrow operator, the address is an offset from
7919 // the base's value, so the object the base refers to is
7920 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007921 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007922 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007923 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007924 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007925 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007926 // FIXME: This code shouldn't be necessary! We should catch the implicit
7927 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007928 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7929 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7930 if (ICE->getSubExpr()->getType()->isArrayType())
7931 return getPrimaryDecl(ICE->getSubExpr());
7932 }
7933 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007934 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007935 case Stmt::UnaryOperatorClass: {
7936 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007937
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007938 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007939 case UO_Real:
7940 case UO_Imag:
7941 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007942 return getPrimaryDecl(UO->getSubExpr());
7943 default:
7944 return 0;
7945 }
7946 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007947 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007948 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007949 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007950 // If the result of an implicit cast is an l-value, we care about
7951 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007952 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007953 default:
7954 return 0;
7955 }
7956}
7957
Richard Trieu5520f232011-09-07 21:46:33 +00007958namespace {
7959 enum {
7960 AO_Bit_Field = 0,
7961 AO_Vector_Element = 1,
7962 AO_Property_Expansion = 2,
7963 AO_Register_Variable = 3,
7964 AO_No_Error = 4
7965 };
7966}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007967/// \brief Diagnose invalid operand for address of operations.
7968///
7969/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007970static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7971 Expr *E, unsigned Type) {
7972 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7973}
7974
Reid Spencer5f016e22007-07-11 17:01:13 +00007975/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007976/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007977/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007978/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007979/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007980/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007981/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007982static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007983 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007984 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7985 if (PTy->getKind() == BuiltinType::Overload) {
7986 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7987 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7988 << OrigOp.get()->getSourceRange();
7989 return QualType();
7990 }
7991
7992 return S.Context.OverloadTy;
7993 }
7994
7995 if (PTy->getKind() == BuiltinType::UnknownAny)
7996 return S.Context.UnknownAnyTy;
7997
7998 if (PTy->getKind() == BuiltinType::BoundMember) {
7999 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8000 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008001 return QualType();
8002 }
John McCall3c3b7f92011-10-25 17:37:35 +00008003
8004 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8005 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008006 }
John McCall9c72c602010-08-27 09:08:28 +00008007
John McCall3c3b7f92011-10-25 17:37:35 +00008008 if (OrigOp.get()->isTypeDependent())
8009 return S.Context.DependentTy;
8010
8011 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008012
John McCall9c72c602010-08-27 09:08:28 +00008013 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008014 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008015
David Blaikie4e4d0842012-03-11 07:00:24 +00008016 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008017 // Implement C99-only parts of addressof rules.
8018 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008019 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008020 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8021 // (assuming the deref expression is valid).
8022 return uOp->getSubExpr()->getType();
8023 }
8024 // Technically, there should be a check for array subscript
8025 // expressions here, but the result of one is always an lvalue anyway.
8026 }
John McCall5808ce42011-02-03 08:15:49 +00008027 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008028 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008029 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008030
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008031 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008032 bool sfinae = S.isSFINAEContext();
8033 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8034 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008035 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008036 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008037 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008038 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008039 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008040 } else if (lval == Expr::LV_MemberFunction) {
8041 // If it's an instance method, make a member pointer.
8042 // The expression must have exactly the form &A::foo.
8043
8044 // If the underlying expression isn't a decl ref, give up.
8045 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008046 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008047 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008048 return QualType();
8049 }
8050 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8051 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8052
8053 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008054 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008055 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008056 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008057
8058 // The method was named without a qualifier.
8059 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008060 if (MD->getParent()->getName().empty())
8061 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8062 << op->getSourceRange();
8063 else {
8064 SmallString<32> Str;
8065 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8066 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8067 << op->getSourceRange()
8068 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8069 }
John McCall9c72c602010-08-27 09:08:28 +00008070 }
8071
John McCall09431682010-11-18 19:01:18 +00008072 return S.Context.getMemberPointerType(op->getType(),
8073 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008074 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008075 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008076 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008077 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008078 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008079 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008080 AddressOfError = AO_Property_Expansion;
8081 } else {
8082 // FIXME: emit more specific diag...
8083 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8084 << op->getSourceRange();
8085 return QualType();
8086 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008087 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008088 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008089 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008090 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008091 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008092 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008093 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008094 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008095 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008096 // with the register storage-class specifier.
8097 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008098 // in C++ it is not error to take address of a register
8099 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008100 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008101 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008102 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008103 }
John McCallba135432009-11-21 08:51:07 +00008104 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008105 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008106 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008107 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008108 // Could be a pointer to member, though, if there is an explicit
8109 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008110 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008111 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008112 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008113 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008114 S.Diag(OpLoc,
8115 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008116 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008117 return QualType();
8118 }
Mike Stump1eb44332009-09-09 15:08:12 +00008119
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008120 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8121 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008122 return S.Context.getMemberPointerType(op->getType(),
8123 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008124 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008125 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008126 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008127 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008128 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008129
Richard Trieu5520f232011-09-07 21:46:33 +00008130 if (AddressOfError != AO_No_Error) {
8131 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8132 return QualType();
8133 }
8134
Eli Friedman441cf102009-05-16 23:27:50 +00008135 if (lval == Expr::LV_IncompleteVoidType) {
8136 // Taking the address of a void variable is technically illegal, but we
8137 // allow it in cases which are otherwise valid.
8138 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008139 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008140 }
8141
Reid Spencer5f016e22007-07-11 17:01:13 +00008142 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008143 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008144 return S.Context.getObjCObjectPointerType(op->getType());
8145 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008146}
8147
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008148/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008149static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8150 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008151 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008152 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008153
John Wiegley429bb272011-04-08 18:41:53 +00008154 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8155 if (ConvResult.isInvalid())
8156 return QualType();
8157 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008158 QualType OpTy = Op->getType();
8159 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008160
8161 if (isa<CXXReinterpretCastExpr>(Op)) {
8162 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8163 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8164 Op->getSourceRange());
8165 }
8166
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008167 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8168 // is an incomplete type or void. It would be possible to warn about
8169 // dereferencing a void pointer, but it's completely well-defined, and such a
8170 // warning is unlikely to catch any mistakes.
8171 if (const PointerType *PT = OpTy->getAs<PointerType>())
8172 Result = PT->getPointeeType();
8173 else if (const ObjCObjectPointerType *OPT =
8174 OpTy->getAs<ObjCObjectPointerType>())
8175 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008176 else {
John McCallfb8721c2011-04-10 19:13:55 +00008177 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008178 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008179 if (PR.take() != Op)
8180 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008181 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008182
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008183 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008184 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008185 << OpTy << Op->getSourceRange();
8186 return QualType();
8187 }
John McCall09431682010-11-18 19:01:18 +00008188
8189 // Dereferences are usually l-values...
8190 VK = VK_LValue;
8191
8192 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008193 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008194 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008195
8196 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008197}
8198
John McCall2de56d12010-08-25 11:45:40 +00008199static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008200 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008201 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008202 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008203 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008204 case tok::periodstar: Opc = BO_PtrMemD; break;
8205 case tok::arrowstar: Opc = BO_PtrMemI; break;
8206 case tok::star: Opc = BO_Mul; break;
8207 case tok::slash: Opc = BO_Div; break;
8208 case tok::percent: Opc = BO_Rem; break;
8209 case tok::plus: Opc = BO_Add; break;
8210 case tok::minus: Opc = BO_Sub; break;
8211 case tok::lessless: Opc = BO_Shl; break;
8212 case tok::greatergreater: Opc = BO_Shr; break;
8213 case tok::lessequal: Opc = BO_LE; break;
8214 case tok::less: Opc = BO_LT; break;
8215 case tok::greaterequal: Opc = BO_GE; break;
8216 case tok::greater: Opc = BO_GT; break;
8217 case tok::exclaimequal: Opc = BO_NE; break;
8218 case tok::equalequal: Opc = BO_EQ; break;
8219 case tok::amp: Opc = BO_And; break;
8220 case tok::caret: Opc = BO_Xor; break;
8221 case tok::pipe: Opc = BO_Or; break;
8222 case tok::ampamp: Opc = BO_LAnd; break;
8223 case tok::pipepipe: Opc = BO_LOr; break;
8224 case tok::equal: Opc = BO_Assign; break;
8225 case tok::starequal: Opc = BO_MulAssign; break;
8226 case tok::slashequal: Opc = BO_DivAssign; break;
8227 case tok::percentequal: Opc = BO_RemAssign; break;
8228 case tok::plusequal: Opc = BO_AddAssign; break;
8229 case tok::minusequal: Opc = BO_SubAssign; break;
8230 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8231 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8232 case tok::ampequal: Opc = BO_AndAssign; break;
8233 case tok::caretequal: Opc = BO_XorAssign; break;
8234 case tok::pipeequal: Opc = BO_OrAssign; break;
8235 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008236 }
8237 return Opc;
8238}
8239
John McCall2de56d12010-08-25 11:45:40 +00008240static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008241 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008242 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008243 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008244 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008245 case tok::plusplus: Opc = UO_PreInc; break;
8246 case tok::minusminus: Opc = UO_PreDec; break;
8247 case tok::amp: Opc = UO_AddrOf; break;
8248 case tok::star: Opc = UO_Deref; break;
8249 case tok::plus: Opc = UO_Plus; break;
8250 case tok::minus: Opc = UO_Minus; break;
8251 case tok::tilde: Opc = UO_Not; break;
8252 case tok::exclaim: Opc = UO_LNot; break;
8253 case tok::kw___real: Opc = UO_Real; break;
8254 case tok::kw___imag: Opc = UO_Imag; break;
8255 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008256 }
8257 return Opc;
8258}
8259
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008260/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8261/// This warning is only emitted for builtin assignment operations. It is also
8262/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008263static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008264 SourceLocation OpLoc) {
8265 if (!S.ActiveTemplateInstantiations.empty())
8266 return;
8267 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8268 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008269 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8270 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8271 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8272 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8273 if (!LHSDeclRef || !RHSDeclRef ||
8274 LHSDeclRef->getLocation().isMacroID() ||
8275 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008276 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008277 const ValueDecl *LHSDecl =
8278 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8279 const ValueDecl *RHSDecl =
8280 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8281 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008282 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008283 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008284 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008285 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008286 if (RefTy->getPointeeType().isVolatileQualified())
8287 return;
8288
8289 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008290 << LHSDeclRef->getType()
8291 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008292}
8293
Douglas Gregoreaebc752008-11-06 23:29:22 +00008294/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8295/// operator @p Opc at location @c TokLoc. This routine only supports
8296/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008297ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008298 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008299 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008300 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008301 // The syntax only allows initializer lists on the RHS of assignment,
8302 // so we don't need to worry about accepting invalid code for
8303 // non-assignment operators.
8304 // C++11 5.17p9:
8305 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8306 // of x = {} is x = T().
8307 InitializationKind Kind =
8308 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8309 InitializedEntity Entity =
8310 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8311 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008312 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008313 if (Init.isInvalid())
8314 return Init;
8315 RHSExpr = Init.take();
8316 }
8317
Richard Trieu78ea78b2011-09-07 01:49:20 +00008318 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008319 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008320 // The following two variables are used for compound assignment operators
8321 QualType CompLHSTy; // Type of LHS after promotions for computation
8322 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008323 ExprValueKind VK = VK_RValue;
8324 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008325
8326 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008327 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008328 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008329 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008330 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8331 VK = LHS.get()->getValueKind();
8332 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008333 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008334 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008335 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008336 break;
John McCall2de56d12010-08-25 11:45:40 +00008337 case BO_PtrMemD:
8338 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008339 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008340 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008341 break;
John McCall2de56d12010-08-25 11:45:40 +00008342 case BO_Mul:
8343 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008344 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008345 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008346 break;
John McCall2de56d12010-08-25 11:45:40 +00008347 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008348 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008349 break;
John McCall2de56d12010-08-25 11:45:40 +00008350 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008351 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008352 break;
John McCall2de56d12010-08-25 11:45:40 +00008353 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008354 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008355 break;
John McCall2de56d12010-08-25 11:45:40 +00008356 case BO_Shl:
8357 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008358 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008359 break;
John McCall2de56d12010-08-25 11:45:40 +00008360 case BO_LE:
8361 case BO_LT:
8362 case BO_GE:
8363 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008364 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008365 break;
John McCall2de56d12010-08-25 11:45:40 +00008366 case BO_EQ:
8367 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008368 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008369 break;
John McCall2de56d12010-08-25 11:45:40 +00008370 case BO_And:
8371 case BO_Xor:
8372 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008373 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008374 break;
John McCall2de56d12010-08-25 11:45:40 +00008375 case BO_LAnd:
8376 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008377 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008378 break;
John McCall2de56d12010-08-25 11:45:40 +00008379 case BO_MulAssign:
8380 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008381 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008382 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008383 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008384 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8385 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008386 break;
John McCall2de56d12010-08-25 11:45:40 +00008387 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008388 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008389 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008390 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8391 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008392 break;
John McCall2de56d12010-08-25 11:45:40 +00008393 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008394 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008395 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008397 break;
John McCall2de56d12010-08-25 11:45:40 +00008398 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008399 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8400 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8401 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008402 break;
John McCall2de56d12010-08-25 11:45:40 +00008403 case BO_ShlAssign:
8404 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008405 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008406 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008407 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8408 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008409 break;
John McCall2de56d12010-08-25 11:45:40 +00008410 case BO_AndAssign:
8411 case BO_XorAssign:
8412 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008413 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008414 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8416 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008417 break;
John McCall2de56d12010-08-25 11:45:40 +00008418 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008419 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008420 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008421 VK = RHS.get()->getValueKind();
8422 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008423 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008424 break;
8425 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008426 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008427 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008428
8429 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008430 CheckArrayAccess(LHS.get());
8431 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008432
Eli Friedmanab3a8522009-03-28 01:22:36 +00008433 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008434 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008435 ResultTy, VK, OK, OpLoc,
8436 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008437 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008438 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008439 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008440 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008441 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008442 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008443 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008444 CompResultTy, OpLoc,
8445 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008446}
8447
Sebastian Redlaee3c932009-10-27 12:10:02 +00008448/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8449/// operators are mixed in a way that suggests that the programmer forgot that
8450/// comparison operators have higher precedence. The most typical example of
8451/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008452static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008453 SourceLocation OpLoc, Expr *LHSExpr,
8454 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008455 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008456 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8457 RHSopc = static_cast<BinOp::Opcode>(-1);
8458 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8459 LHSopc = BO->getOpcode();
8460 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8461 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008462
8463 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008464 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008465 return;
8466
8467 // Bitwise operations are sometimes used as eager logical ops.
8468 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008469 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8470 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008471 return;
8472
Richard Trieu78ea78b2011-09-07 01:49:20 +00008473 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8474 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008475 if (!isLeftComp && !isRightComp) return;
8476
Richard Trieu78ea78b2011-09-07 01:49:20 +00008477 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8478 OpLoc)
8479 : SourceRange(OpLoc, RHSExpr->getLocEnd());
David Blaikie0bea8632012-10-08 01:11:04 +00008480 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8481 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008482 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008483 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8484 RHSExpr->getLocEnd())
8485 : SourceRange(LHSExpr->getLocStart(),
8486 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008487
8488 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8489 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8490 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008491 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008492 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008493 SuggestParentheses(Self, OpLoc,
8494 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8495 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008496}
8497
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008498/// \brief It accepts a '&' expr that is inside a '|' one.
8499/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8500/// in parentheses.
8501static void
8502EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8503 BinaryOperator *Bop) {
8504 assert(Bop->getOpcode() == BO_And);
8505 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8506 << Bop->getSourceRange() << OpLoc;
8507 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008508 Self.PDiag(diag::note_precedence_silence)
8509 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008510 Bop->getSourceRange());
8511}
8512
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008513/// \brief It accepts a '&&' expr that is inside a '||' one.
8514/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8515/// in parentheses.
8516static void
8517EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008518 BinaryOperator *Bop) {
8519 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008520 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8521 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008522 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008523 Self.PDiag(diag::note_precedence_silence)
8524 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008525 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008526}
8527
8528/// \brief Returns true if the given expression can be evaluated as a constant
8529/// 'true'.
8530static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8531 bool Res;
8532 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8533}
8534
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008535/// \brief Returns true if the given expression can be evaluated as a constant
8536/// 'false'.
8537static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8538 bool Res;
8539 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8540}
8541
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008542/// \brief Look for '&&' in the left hand of a '||' expr.
8543static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008544 Expr *LHSExpr, Expr *RHSExpr) {
8545 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008546 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008547 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008548 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008549 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008550 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8551 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8552 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8553 } else if (Bop->getOpcode() == BO_LOr) {
8554 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8555 // If it's "a || b && 1 || c" we didn't warn earlier for
8556 // "a || b && 1", but warn now.
8557 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8558 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8559 }
8560 }
8561 }
8562}
8563
8564/// \brief Look for '&&' in the right hand of a '||' expr.
8565static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008566 Expr *LHSExpr, Expr *RHSExpr) {
8567 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008568 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008569 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008570 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008571 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008572 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8573 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008575 }
8576 }
8577}
8578
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008579/// \brief Look for '&' in the left or right hand of a '|' expr.
8580static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8581 Expr *OrArg) {
8582 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8583 if (Bop->getOpcode() == BO_And)
8584 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8585 }
8586}
8587
David Blaikieb3f55c52012-10-05 00:41:03 +00008588static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8589 Expr *SubExpr, StringRef shift) {
8590 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8591 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008592 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008593 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie6b34c172012-10-08 01:19:49 +00008594 << Bop->getSourceRange() << OpLoc << Op << shift;
David Blaikieb3f55c52012-10-05 00:41:03 +00008595 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008596 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008597 Bop->getSourceRange());
8598 }
8599 }
8600}
8601
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008602/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008603/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008604static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008605 SourceLocation OpLoc, Expr *LHSExpr,
8606 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008607 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008608 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008609 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008610
8611 // Diagnose "arg1 & arg2 | arg3"
8612 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008613 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8614 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008615 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008616
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008617 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8618 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008619 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008620 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8621 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008622 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008623
8624 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8625 || Opc == BO_Shr) {
David Blaikie6b34c172012-10-08 01:19:49 +00008626 StringRef shift = BinaryOperator::getOpcodeStr(Opc);
David Blaikieb3f55c52012-10-05 00:41:03 +00008627 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, shift);
8628 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, shift);
8629 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008630}
8631
Reid Spencer5f016e22007-07-11 17:01:13 +00008632// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008633ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008634 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008635 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008636 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008637 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8638 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008639
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008640 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008641 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008642
Richard Trieubefece12011-09-07 02:02:10 +00008643 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008644}
8645
John McCall3c3b7f92011-10-25 17:37:35 +00008646/// Build an overloaded binary operator expression in the given scope.
8647static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8648 BinaryOperatorKind Opc,
8649 Expr *LHS, Expr *RHS) {
8650 // Find all of the overloaded operators visible from this
8651 // point. We perform both an operator-name lookup from the local
8652 // scope and an argument-dependent lookup based on the types of
8653 // the arguments.
8654 UnresolvedSet<16> Functions;
8655 OverloadedOperatorKind OverOp
8656 = BinaryOperator::getOverloadedOperator(Opc);
8657 if (Sc && OverOp != OO_None)
8658 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8659 RHS->getType(), Functions);
8660
8661 // Build the (potentially-overloaded, potentially-dependent)
8662 // binary operation.
8663 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8664}
8665
John McCall60d7b3a2010-08-24 06:29:42 +00008666ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008667 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008668 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008669 // We want to end up calling one of checkPseudoObjectAssignment
8670 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8671 // both expressions are overloadable or either is type-dependent),
8672 // or CreateBuiltinBinOp (in any other case). We also want to get
8673 // any placeholder types out of the way.
8674
John McCall3c3b7f92011-10-25 17:37:35 +00008675 // Handle pseudo-objects in the LHS.
8676 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8677 // Assignments with a pseudo-object l-value need special analysis.
8678 if (pty->getKind() == BuiltinType::PseudoObject &&
8679 BinaryOperator::isAssignmentOp(Opc))
8680 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8681
8682 // Don't resolve overloads if the other type is overloadable.
8683 if (pty->getKind() == BuiltinType::Overload) {
8684 // We can't actually test that if we still have a placeholder,
8685 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008686 // code below are valid when the LHS is an overload set. Note
8687 // that an overload set can be dependently-typed, but it never
8688 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008689 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8690 if (resolvedRHS.isInvalid()) return ExprError();
8691 RHSExpr = resolvedRHS.take();
8692
John McCallac516502011-10-28 01:04:34 +00008693 if (RHSExpr->isTypeDependent() ||
8694 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008695 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8696 }
8697
8698 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8699 if (LHS.isInvalid()) return ExprError();
8700 LHSExpr = LHS.take();
8701 }
8702
8703 // Handle pseudo-objects in the RHS.
8704 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8705 // An overload in the RHS can potentially be resolved by the type
8706 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008707 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8708 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8709 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8710
Eli Friedman87884912012-01-17 21:27:43 +00008711 if (LHSExpr->getType()->isOverloadableType())
8712 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8713
John McCall3c3b7f92011-10-25 17:37:35 +00008714 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008715 }
John McCall3c3b7f92011-10-25 17:37:35 +00008716
8717 // Don't resolve overloads if the other type is overloadable.
8718 if (pty->getKind() == BuiltinType::Overload &&
8719 LHSExpr->getType()->isOverloadableType())
8720 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8721
8722 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8723 if (!resolvedRHS.isUsable()) return ExprError();
8724 RHSExpr = resolvedRHS.take();
8725 }
8726
David Blaikie4e4d0842012-03-11 07:00:24 +00008727 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008728 // If either expression is type-dependent, always build an
8729 // overloaded op.
8730 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8731 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008732
John McCallac516502011-10-28 01:04:34 +00008733 // Otherwise, build an overloaded op if either expression has an
8734 // overloadable type.
8735 if (LHSExpr->getType()->isOverloadableType() ||
8736 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008737 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008738 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008739
Douglas Gregoreaebc752008-11-06 23:29:22 +00008740 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008741 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008742}
8743
John McCall60d7b3a2010-08-24 06:29:42 +00008744ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008745 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008746 Expr *InputExpr) {
8747 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008748 ExprValueKind VK = VK_RValue;
8749 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008750 QualType resultType;
8751 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008752 case UO_PreInc:
8753 case UO_PreDec:
8754 case UO_PostInc:
8755 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008756 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008757 Opc == UO_PreInc ||
8758 Opc == UO_PostInc,
8759 Opc == UO_PreInc ||
8760 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008761 break;
John McCall2de56d12010-08-25 11:45:40 +00008762 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008763 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008764 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008765 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008766 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008767 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008768 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008769 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008770 }
John McCall2de56d12010-08-25 11:45:40 +00008771 case UO_Plus:
8772 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008773 Input = UsualUnaryConversions(Input.take());
8774 if (Input.isInvalid()) return ExprError();
8775 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008776 if (resultType->isDependentType())
8777 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008778 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8779 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008780 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008781 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008782 resultType->isEnumeralType())
8783 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008784 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008785 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008786 resultType->isPointerType())
8787 break;
8788
Sebastian Redl0eb23302009-01-19 00:08:26 +00008789 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008790 << resultType << Input.get()->getSourceRange());
8791
John McCall2de56d12010-08-25 11:45:40 +00008792 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008793 Input = UsualUnaryConversions(Input.take());
8794 if (Input.isInvalid()) return ExprError();
8795 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008796 if (resultType->isDependentType())
8797 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008798 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8799 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8800 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008801 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008802 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008803 else if (resultType->hasIntegerRepresentation())
8804 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008805 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008806 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008807 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008808 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008809 break;
John Wiegley429bb272011-04-08 18:41:53 +00008810
John McCall2de56d12010-08-25 11:45:40 +00008811 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008812 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008813 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8814 if (Input.isInvalid()) return ExprError();
8815 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008816
8817 // Though we still have to promote half FP to float...
8818 if (resultType->isHalfType()) {
8819 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8820 resultType = Context.FloatTy;
8821 }
8822
Sebastian Redl28507842009-02-26 14:39:58 +00008823 if (resultType->isDependentType())
8824 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008825 if (resultType->isScalarType()) {
8826 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008827 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008828 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8829 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008830 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8831 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008832 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008833 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008834 // Vector logical not returns the signed variant of the operand type.
8835 resultType = GetSignedVectorType(resultType);
8836 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008837 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008838 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008839 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008840 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008841
Reid Spencer5f016e22007-07-11 17:01:13 +00008842 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008843 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008844 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008845 break;
John McCall2de56d12010-08-25 11:45:40 +00008846 case UO_Real:
8847 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008848 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008849 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8850 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008851 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008852 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8853 if (Input.get()->getValueKind() != VK_RValue &&
8854 Input.get()->getObjectKind() == OK_Ordinary)
8855 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008856 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008857 // In C, a volatile scalar is read by __imag. In C++, it is not.
8858 Input = DefaultLvalueConversion(Input.take());
8859 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008860 break;
John McCall2de56d12010-08-25 11:45:40 +00008861 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008862 resultType = Input.get()->getType();
8863 VK = Input.get()->getValueKind();
8864 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008865 break;
8866 }
John Wiegley429bb272011-04-08 18:41:53 +00008867 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008868 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008869
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008870 // Check for array bounds violations in the operand of the UnaryOperator,
8871 // except for the '*' and '&' operators that have to be handled specially
8872 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8873 // that are explicitly defined as valid by the standard).
8874 if (Opc != UO_AddrOf && Opc != UO_Deref)
8875 CheckArrayAccess(Input.get());
8876
John Wiegley429bb272011-04-08 18:41:53 +00008877 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008878 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008879}
8880
Douglas Gregord3d08532011-12-14 21:23:13 +00008881/// \brief Determine whether the given expression is a qualified member
8882/// access expression, of a form that could be turned into a pointer to member
8883/// with the address-of operator.
8884static bool isQualifiedMemberAccess(Expr *E) {
8885 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8886 if (!DRE->getQualifier())
8887 return false;
8888
8889 ValueDecl *VD = DRE->getDecl();
8890 if (!VD->isCXXClassMember())
8891 return false;
8892
8893 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8894 return true;
8895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8896 return Method->isInstance();
8897
8898 return false;
8899 }
8900
8901 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8902 if (!ULE->getQualifier())
8903 return false;
8904
8905 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8906 DEnd = ULE->decls_end();
8907 D != DEnd; ++D) {
8908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8909 if (Method->isInstance())
8910 return true;
8911 } else {
8912 // Overload set does not contain methods.
8913 break;
8914 }
8915 }
8916
8917 return false;
8918 }
8919
8920 return false;
8921}
8922
John McCall60d7b3a2010-08-24 06:29:42 +00008923ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008924 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008925 // First things first: handle placeholders so that the
8926 // overloaded-operator check considers the right type.
8927 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8928 // Increment and decrement of pseudo-object references.
8929 if (pty->getKind() == BuiltinType::PseudoObject &&
8930 UnaryOperator::isIncrementDecrementOp(Opc))
8931 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8932
8933 // extension is always a builtin operator.
8934 if (Opc == UO_Extension)
8935 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8936
8937 // & gets special logic for several kinds of placeholder.
8938 // The builtin code knows what to do.
8939 if (Opc == UO_AddrOf &&
8940 (pty->getKind() == BuiltinType::Overload ||
8941 pty->getKind() == BuiltinType::UnknownAny ||
8942 pty->getKind() == BuiltinType::BoundMember))
8943 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8944
8945 // Anything else needs to be handled now.
8946 ExprResult Result = CheckPlaceholderExpr(Input);
8947 if (Result.isInvalid()) return ExprError();
8948 Input = Result.take();
8949 }
8950
David Blaikie4e4d0842012-03-11 07:00:24 +00008951 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008952 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8953 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008954 // Find all of the overloaded operators visible from this
8955 // point. We perform both an operator-name lookup from the local
8956 // scope and an argument-dependent lookup based on the types of
8957 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008958 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008959 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008960 if (S && OverOp != OO_None)
8961 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8962 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008963
John McCall9ae2f072010-08-23 23:25:46 +00008964 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008965 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008966
John McCall9ae2f072010-08-23 23:25:46 +00008967 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008968}
8969
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008970// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008971ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008972 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008973 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008974}
8975
Steve Naroff1b273c42007-09-16 14:56:35 +00008976/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008977ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008978 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008979 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008980 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008981 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008982 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008983}
8984
John McCallf85e1932011-06-15 23:02:42 +00008985/// Given the last statement in a statement-expression, check whether
8986/// the result is a producing expression (like a call to an
8987/// ns_returns_retained function) and, if so, rebuild it to hoist the
8988/// release out of the full-expression. Otherwise, return null.
8989/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008990static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008991 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008992 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008993 if (!cleanups) return 0;
8994
8995 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008996 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008997 return 0;
8998
8999 // Splice out the cast. This shouldn't modify any interesting
9000 // features of the statement.
9001 Expr *producer = cast->getSubExpr();
9002 assert(producer->getType() == cast->getType());
9003 assert(producer->getValueKind() == cast->getValueKind());
9004 cleanups->setSubExpr(producer);
9005 return cleanups;
9006}
9007
John McCall73f428c2012-04-04 01:27:53 +00009008void Sema::ActOnStartStmtExpr() {
9009 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9010}
9011
9012void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009013 // Note that function is also called by TreeTransform when leaving a
9014 // StmtExpr scope without rebuilding anything.
9015
John McCall73f428c2012-04-04 01:27:53 +00009016 DiscardCleanupsInEvaluationContext();
9017 PopExpressionEvaluationContext();
9018}
9019
John McCall60d7b3a2010-08-24 06:29:42 +00009020ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009021Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009022 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009023 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9024 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9025
John McCall73f428c2012-04-04 01:27:53 +00009026 if (hasAnyUnrecoverableErrorsInThisFunction())
9027 DiscardCleanupsInEvaluationContext();
9028 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9029 PopExpressionEvaluationContext();
9030
Douglas Gregordd8f5692010-03-10 04:54:39 +00009031 bool isFileScope
9032 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009033 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009034 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009035
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009036 // FIXME: there are a variety of strange constraints to enforce here, for
9037 // example, it is not possible to goto into a stmt expression apparently.
9038 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009039
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009040 // If there are sub stmts in the compound stmt, take the type of the last one
9041 // as the type of the stmtexpr.
9042 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009043 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009044 if (!Compound->body_empty()) {
9045 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009046 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009047 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009048 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9049 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009050 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009051 }
John McCallf85e1932011-06-15 23:02:42 +00009052
John Wiegley429bb272011-04-08 18:41:53 +00009053 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009054 // Do function/array conversion on the last expression, but not
9055 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009056 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9057 if (LastExpr.isInvalid())
9058 return ExprError();
9059 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009060
John Wiegley429bb272011-04-08 18:41:53 +00009061 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009062 // In ARC, if the final expression ends in a consume, splice
9063 // the consume out and bind it later. In the alternate case
9064 // (when dealing with a retainable type), the result
9065 // initialization will create a produce. In both cases the
9066 // result will be +1, and we'll need to balance that out with
9067 // a bind.
9068 if (Expr *rebuiltLastStmt
9069 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9070 LastExpr = rebuiltLastStmt;
9071 } else {
9072 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009073 InitializedEntity::InitializeResult(LPLoc,
9074 Ty,
9075 false),
9076 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009077 LastExpr);
9078 }
9079
John Wiegley429bb272011-04-08 18:41:53 +00009080 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009081 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009082 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009083 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009084 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009085 else
John Wiegley429bb272011-04-08 18:41:53 +00009086 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009087 StmtExprMayBindToTemp = true;
9088 }
9089 }
9090 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009091 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009092
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009093 // FIXME: Check that expression type is complete/non-abstract; statement
9094 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009095 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9096 if (StmtExprMayBindToTemp)
9097 return MaybeBindToTemporary(ResStmtExpr);
9098 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009099}
Steve Naroffd34e9152007-08-01 22:05:33 +00009100
John McCall60d7b3a2010-08-24 06:29:42 +00009101ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009102 TypeSourceInfo *TInfo,
9103 OffsetOfComponent *CompPtr,
9104 unsigned NumComponents,
9105 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009106 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009107 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009108 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009109
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009110 // We must have at least one component that refers to the type, and the first
9111 // one is known to be a field designator. Verify that the ArgTy represents
9112 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009113 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009114 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9115 << ArgTy << TypeRange);
9116
9117 // Type must be complete per C99 7.17p3 because a declaring a variable
9118 // with an incomplete type would be ill-formed.
9119 if (!Dependent
9120 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009121 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009122 return ExprError();
9123
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009124 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9125 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009126 // FIXME: This diagnostic isn't actually visible because the location is in
9127 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009128 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009129 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9130 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009131
9132 bool DidWarnAboutNonPOD = false;
9133 QualType CurrentType = ArgTy;
9134 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009135 SmallVector<OffsetOfNode, 4> Comps;
9136 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009137 for (unsigned i = 0; i != NumComponents; ++i) {
9138 const OffsetOfComponent &OC = CompPtr[i];
9139 if (OC.isBrackets) {
9140 // Offset of an array sub-field. TODO: Should we allow vector elements?
9141 if (!CurrentType->isDependentType()) {
9142 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9143 if(!AT)
9144 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9145 << CurrentType);
9146 CurrentType = AT->getElementType();
9147 } else
9148 CurrentType = Context.DependentTy;
9149
Richard Smithea011432011-10-17 23:29:39 +00009150 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9151 if (IdxRval.isInvalid())
9152 return ExprError();
9153 Expr *Idx = IdxRval.take();
9154
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009155 // The expression must be an integral expression.
9156 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009157 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9158 !Idx->getType()->isIntegerType())
9159 return ExprError(Diag(Idx->getLocStart(),
9160 diag::err_typecheck_subscript_not_integer)
9161 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009162
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009163 // Record this array index.
9164 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009165 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009166 continue;
9167 }
9168
9169 // Offset of a field.
9170 if (CurrentType->isDependentType()) {
9171 // We have the offset of a field, but we can't look into the dependent
9172 // type. Just record the identifier of the field.
9173 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9174 CurrentType = Context.DependentTy;
9175 continue;
9176 }
9177
9178 // We need to have a complete type to look into.
9179 if (RequireCompleteType(OC.LocStart, CurrentType,
9180 diag::err_offsetof_incomplete_type))
9181 return ExprError();
9182
9183 // Look for the designated field.
9184 const RecordType *RC = CurrentType->getAs<RecordType>();
9185 if (!RC)
9186 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9187 << CurrentType);
9188 RecordDecl *RD = RC->getDecl();
9189
9190 // C++ [lib.support.types]p5:
9191 // The macro offsetof accepts a restricted set of type arguments in this
9192 // International Standard. type shall be a POD structure or a POD union
9193 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009194 // C++11 [support.types]p4:
9195 // If type is not a standard-layout class (Clause 9), the results are
9196 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009197 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009198 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9199 unsigned DiagID =
9200 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9201 : diag::warn_offsetof_non_pod_type;
9202
9203 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009204 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009205 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009206 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9207 << CurrentType))
9208 DidWarnAboutNonPOD = true;
9209 }
9210
9211 // Look for the field.
9212 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9213 LookupQualifiedName(R, RD);
9214 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009215 IndirectFieldDecl *IndirectMemberDecl = 0;
9216 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009217 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009218 MemberDecl = IndirectMemberDecl->getAnonField();
9219 }
9220
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009221 if (!MemberDecl)
9222 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9223 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9224 OC.LocEnd));
9225
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009226 // C99 7.17p3:
9227 // (If the specified member is a bit-field, the behavior is undefined.)
9228 //
9229 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009230 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009231 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9232 << MemberDecl->getDeclName()
9233 << SourceRange(BuiltinLoc, RParenLoc);
9234 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9235 return ExprError();
9236 }
Eli Friedman19410a72010-08-05 10:11:36 +00009237
9238 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009239 if (IndirectMemberDecl)
9240 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009241
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009242 // If the member was found in a base class, introduce OffsetOfNodes for
9243 // the base class indirections.
9244 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9245 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009246 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009247 CXXBasePath &Path = Paths.front();
9248 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9249 B != BEnd; ++B)
9250 Comps.push_back(OffsetOfNode(B->Base));
9251 }
Eli Friedman19410a72010-08-05 10:11:36 +00009252
Francois Pichet87c2e122010-11-21 06:08:52 +00009253 if (IndirectMemberDecl) {
9254 for (IndirectFieldDecl::chain_iterator FI =
9255 IndirectMemberDecl->chain_begin(),
9256 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9257 assert(isa<FieldDecl>(*FI));
9258 Comps.push_back(OffsetOfNode(OC.LocStart,
9259 cast<FieldDecl>(*FI), OC.LocEnd));
9260 }
9261 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009262 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009263
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009264 CurrentType = MemberDecl->getType().getNonReferenceType();
9265 }
9266
9267 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009268 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009269}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009270
John McCall60d7b3a2010-08-24 06:29:42 +00009271ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009272 SourceLocation BuiltinLoc,
9273 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009274 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009275 OffsetOfComponent *CompPtr,
9276 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009277 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009278
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009279 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009280 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009281 if (ArgTy.isNull())
9282 return ExprError();
9283
Eli Friedman5a15dc12010-08-05 10:15:45 +00009284 if (!ArgTInfo)
9285 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9286
9287 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009288 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009289}
9290
9291
John McCall60d7b3a2010-08-24 06:29:42 +00009292ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009293 Expr *CondExpr,
9294 Expr *LHSExpr, Expr *RHSExpr,
9295 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009296 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9297
John McCallf89e55a2010-11-18 06:31:45 +00009298 ExprValueKind VK = VK_RValue;
9299 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009300 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009301 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009302 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009303 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009304 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009305 } else {
9306 // The conditional expression is required to be a constant expression.
9307 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009308 ExprResult CondICE
9309 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9310 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009311 if (CondICE.isInvalid())
9312 return ExprError();
9313 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009314
Sebastian Redl28507842009-02-26 14:39:58 +00009315 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009316 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9317
9318 resType = ActiveExpr->getType();
9319 ValueDependent = ActiveExpr->isValueDependent();
9320 VK = ActiveExpr->getValueKind();
9321 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009322 }
9323
Sebastian Redlf53597f2009-03-15 17:47:39 +00009324 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009325 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009326 resType->isDependentType(),
9327 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009328}
9329
Steve Naroff4eb206b2008-09-03 18:15:37 +00009330//===----------------------------------------------------------------------===//
9331// Clang Extensions.
9332//===----------------------------------------------------------------------===//
9333
9334/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009335void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009336 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009337 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009338 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009339 if (CurScope)
9340 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009341 else
9342 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009343
Eli Friedman84b007f2012-01-26 03:00:14 +00009344 getCurBlock()->HasImplicitReturnType = true;
9345
John McCall538773c2011-11-11 03:19:12 +00009346 // Enter a new evaluation context to insulate the block from any
9347 // cleanups from the enclosing full-expression.
9348 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009349}
9350
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009351void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9352 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009353 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009354 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009355 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009356
John McCallbf1a0282010-06-04 23:28:52 +00009357 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009358 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009359
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009360 // FIXME: We should allow unexpanded parameter packs here, but that would,
9361 // in turn, make the block expression contain unexpanded parameter packs.
9362 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9363 // Drop the parameters.
9364 FunctionProtoType::ExtProtoInfo EPI;
9365 EPI.HasTrailingReturn = false;
9366 EPI.TypeQuals |= DeclSpec::TQ_const;
9367 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9368 EPI);
9369 Sig = Context.getTrivialTypeSourceInfo(T);
9370 }
9371
John McCall711c52b2011-01-05 12:14:39 +00009372 // GetTypeForDeclarator always produces a function type for a block
9373 // literal signature. Furthermore, it is always a FunctionProtoType
9374 // unless the function was written with a typedef.
9375 assert(T->isFunctionType() &&
9376 "GetTypeForDeclarator made a non-function block signature");
9377
9378 // Look for an explicit signature in that function type.
9379 FunctionProtoTypeLoc ExplicitSignature;
9380
9381 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9382 if (isa<FunctionProtoTypeLoc>(tmp)) {
9383 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9384
9385 // Check whether that explicit signature was synthesized by
9386 // GetTypeForDeclarator. If so, don't save that as part of the
9387 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009388 if (ExplicitSignature.getLocalRangeBegin() ==
9389 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009390 // This would be much cheaper if we stored TypeLocs instead of
9391 // TypeSourceInfos.
9392 TypeLoc Result = ExplicitSignature.getResultLoc();
9393 unsigned Size = Result.getFullDataSize();
9394 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9395 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9396
9397 ExplicitSignature = FunctionProtoTypeLoc();
9398 }
John McCall82dc0092010-06-04 11:21:44 +00009399 }
Mike Stump1eb44332009-09-09 15:08:12 +00009400
John McCall711c52b2011-01-05 12:14:39 +00009401 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9402 CurBlock->FunctionType = T;
9403
9404 const FunctionType *Fn = T->getAs<FunctionType>();
9405 QualType RetTy = Fn->getResultType();
9406 bool isVariadic =
9407 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9408
John McCallc71a4912010-06-04 19:02:56 +00009409 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009410
John McCall82dc0092010-06-04 11:21:44 +00009411 // Don't allow returning a objc interface by value.
9412 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009413 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009414 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9415 return;
9416 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009417
John McCall82dc0092010-06-04 11:21:44 +00009418 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009419 // return type. TODO: what should we do with declarators like:
9420 // ^ * { ... }
9421 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009422 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009423 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009424 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009425 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009426 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009427
John McCall82dc0092010-06-04 11:21:44 +00009428 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009429 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009430 if (ExplicitSignature) {
9431 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9432 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009433 if (Param->getIdentifier() == 0 &&
9434 !Param->isImplicit() &&
9435 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009436 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009437 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009438 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009439 }
John McCall82dc0092010-06-04 11:21:44 +00009440
9441 // Fake up parameter variables if we have a typedef, like
9442 // ^ fntype { ... }
9443 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9444 for (FunctionProtoType::arg_type_iterator
9445 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9446 ParmVarDecl *Param =
9447 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009448 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009449 *I);
John McCallc71a4912010-06-04 19:02:56 +00009450 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009451 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009452 }
John McCall82dc0092010-06-04 11:21:44 +00009453
John McCallc71a4912010-06-04 19:02:56 +00009454 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009455 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009456 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009457 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9458 CurBlock->TheDecl->param_end(),
9459 /*CheckParameterNames=*/false);
9460 }
9461
John McCall82dc0092010-06-04 11:21:44 +00009462 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009463 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009464
John McCall82dc0092010-06-04 11:21:44 +00009465 // Put the parameter variables in scope. We can bail out immediately
9466 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009467 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009468 return;
9469
Steve Naroff090276f2008-10-10 01:28:17 +00009470 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009471 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9472 (*AI)->setOwningFunction(CurBlock->TheDecl);
9473
Steve Naroff090276f2008-10-10 01:28:17 +00009474 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009475 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009476 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009477
Steve Naroff090276f2008-10-10 01:28:17 +00009478 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009479 }
John McCall7a9813c2010-01-22 00:28:27 +00009480 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009481}
9482
9483/// ActOnBlockError - If there is an error parsing a block, this callback
9484/// is invoked to pop the information about the block from the action impl.
9485void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009486 // Leave the expression-evaluation context.
9487 DiscardCleanupsInEvaluationContext();
9488 PopExpressionEvaluationContext();
9489
Steve Naroff4eb206b2008-09-03 18:15:37 +00009490 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009491 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009492 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009493}
9494
9495/// ActOnBlockStmtExpr - This is called when the body of a block statement
9496/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009497ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009498 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009499 // If blocks are disabled, emit an error.
9500 if (!LangOpts.Blocks)
9501 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009502
John McCall538773c2011-11-11 03:19:12 +00009503 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009504 if (hasAnyUnrecoverableErrorsInThisFunction())
9505 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009506 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9507 PopExpressionEvaluationContext();
9508
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009509 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009510
9511 if (BSI->HasImplicitReturnType)
9512 deduceClosureReturnType(*BSI);
9513
Steve Naroff090276f2008-10-10 01:28:17 +00009514 PopDeclContext();
9515
Steve Naroff4eb206b2008-09-03 18:15:37 +00009516 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009517 if (!BSI->ReturnType.isNull())
9518 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009519
Mike Stump56925862009-07-28 22:04:01 +00009520 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009521 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009522
John McCall469a1eb2011-02-02 13:00:07 +00009523 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009524 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9525 SmallVector<BlockDecl::Capture, 4> Captures;
9526 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9527 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9528 if (Cap.isThisCapture())
9529 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009530 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009531 Cap.isNested(), Cap.getCopyExpr());
9532 Captures.push_back(NewCap);
9533 }
9534 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9535 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009536
John McCallc71a4912010-06-04 19:02:56 +00009537 // If the user wrote a function type in some form, try to use that.
9538 if (!BSI->FunctionType.isNull()) {
9539 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9540
9541 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9542 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9543
9544 // Turn protoless block types into nullary block types.
9545 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009546 FunctionProtoType::ExtProtoInfo EPI;
9547 EPI.ExtInfo = Ext;
9548 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009549
9550 // Otherwise, if we don't need to change anything about the function type,
9551 // preserve its sugar structure.
9552 } else if (FTy->getResultType() == RetTy &&
9553 (!NoReturn || FTy->getNoReturnAttr())) {
9554 BlockTy = BSI->FunctionType;
9555
9556 // Otherwise, make the minimal modifications to the function type.
9557 } else {
9558 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9560 EPI.TypeQuals = 0; // FIXME: silently?
9561 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009562 BlockTy = Context.getFunctionType(RetTy,
9563 FPT->arg_type_begin(),
9564 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009565 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009566 }
9567
9568 // If we don't have a function type, just build one from nothing.
9569 } else {
John McCalle23cf432010-12-14 08:05:40 +00009570 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009571 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009572 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009573 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009574
John McCallc71a4912010-06-04 19:02:56 +00009575 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9576 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009577 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009578
Chris Lattner17a78302009-04-19 05:28:12 +00009579 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009580 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009581 !hasAnyUnrecoverableErrorsInThisFunction() &&
9582 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009583 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009584
Chris Lattnere476bdc2011-02-17 23:58:47 +00009585 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009586
Jordan Rose7dd900e2012-07-02 21:19:23 +00009587 // Try to apply the named return value optimization. We have to check again
9588 // if we can do this, though, because blocks keep return statements around
9589 // to deduce an implicit return type.
9590 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9591 !BSI->TheDecl->isDependentContext())
9592 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009593
Benjamin Kramerd2486192011-07-12 14:11:05 +00009594 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9595 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009596 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009597
John McCall80ee6e82011-11-10 05:35:25 +00009598 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009599 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009600 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009601 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009602 ExprCleanupObjects.push_back(Result->getBlockDecl());
9603 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009604
9605 // It also gets a branch-protected scope if any of the captured
9606 // variables needs destruction.
9607 for (BlockDecl::capture_const_iterator
9608 ci = Result->getBlockDecl()->capture_begin(),
9609 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9610 const VarDecl *var = ci->getVariable();
9611 if (var->getType().isDestructedType() != QualType::DK_none) {
9612 getCurFunction()->setHasBranchProtectedScope();
9613 break;
9614 }
9615 }
John McCall80ee6e82011-11-10 05:35:25 +00009616 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009617
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009618 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009619}
9620
John McCall60d7b3a2010-08-24 06:29:42 +00009621ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009622 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009623 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009624 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009625 GetTypeFromParser(Ty, &TInfo);
9626 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009627}
9628
John McCall60d7b3a2010-08-24 06:29:42 +00009629ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009630 Expr *E, TypeSourceInfo *TInfo,
9631 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009632 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009633
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009634 // Get the va_list type
9635 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009636 if (VaListType->isArrayType()) {
9637 // Deal with implicit array decay; for example, on x86-64,
9638 // va_list is an array, but it's supposed to decay to
9639 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009640 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009641 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009642 ExprResult Result = UsualUnaryConversions(E);
9643 if (Result.isInvalid())
9644 return ExprError();
9645 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009646 } else {
9647 // Otherwise, the va_list argument must be an l-value because
9648 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009649 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009650 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009651 return ExprError();
9652 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009653
Douglas Gregordd027302009-05-19 23:10:31 +00009654 if (!E->isTypeDependent() &&
9655 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009656 return ExprError(Diag(E->getLocStart(),
9657 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009658 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009659 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009660
David Majnemer0adde122011-06-14 05:17:32 +00009661 if (!TInfo->getType()->isDependentType()) {
9662 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009663 diag::err_second_parameter_to_va_arg_incomplete,
9664 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009665 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009666
David Majnemer0adde122011-06-14 05:17:32 +00009667 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009668 TInfo->getType(),
9669 diag::err_second_parameter_to_va_arg_abstract,
9670 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009671 return ExprError();
9672
Douglas Gregor4eb75222011-07-30 06:45:27 +00009673 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009674 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009675 TInfo->getType()->isObjCLifetimeType()
9676 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9677 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009678 << TInfo->getType()
9679 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009680 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009681
9682 // Check for va_arg where arguments of the given type will be promoted
9683 // (i.e. this va_arg is guaranteed to have undefined behavior).
9684 QualType PromoteType;
9685 if (TInfo->getType()->isPromotableIntegerType()) {
9686 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9687 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9688 PromoteType = QualType();
9689 }
9690 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9691 PromoteType = Context.DoubleTy;
9692 if (!PromoteType.isNull())
9693 Diag(TInfo->getTypeLoc().getBeginLoc(),
9694 diag::warn_second_parameter_to_va_arg_never_compatible)
9695 << TInfo->getType()
9696 << PromoteType
9697 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009698 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009699
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009700 QualType T = TInfo->getType().getNonLValueExprType(Context);
9701 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009702}
9703
John McCall60d7b3a2010-08-24 06:29:42 +00009704ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009705 // The type of __null will be int or long, depending on the size of
9706 // pointers on the target.
9707 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009708 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9709 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009710 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009711 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009712 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009713 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009714 Ty = Context.LongLongTy;
9715 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009716 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009717 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009718
Sebastian Redlf53597f2009-03-15 17:47:39 +00009719 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009720}
9721
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009722static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009723 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009724 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009725 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009726
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009727 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9728 if (!PT)
9729 return;
9730
9731 // Check if the destination is of type 'id'.
9732 if (!PT->isObjCIdType()) {
9733 // Check if the destination is the 'NSString' interface.
9734 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9735 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9736 return;
9737 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009738
John McCall4b9c2d22011-11-06 09:01:30 +00009739 // Ignore any parens, implicit casts (should only be
9740 // array-to-pointer decays), and not-so-opaque values. The last is
9741 // important for making this trigger for property assignments.
9742 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9743 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9744 if (OV->getSourceExpr())
9745 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9746
9747 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009748 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009749 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009750
Douglas Gregor849b2432010-03-31 17:46:05 +00009751 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009752}
9753
Chris Lattner5cf216b2008-01-04 18:04:52 +00009754bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9755 SourceLocation Loc,
9756 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009757 Expr *SrcExpr, AssignmentAction Action,
9758 bool *Complained) {
9759 if (Complained)
9760 *Complained = false;
9761
Chris Lattner5cf216b2008-01-04 18:04:52 +00009762 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009763 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009764 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009765 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009766 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009767 ConversionFixItGenerator ConvHints;
9768 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009769 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009770
Chris Lattner5cf216b2008-01-04 18:04:52 +00009771 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009772 case Compatible:
9773 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9774 return false;
9775
Chris Lattnerb7b61152008-01-04 18:22:42 +00009776 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009777 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009778 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9779 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009780 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009781 case IntToPointer:
9782 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009783 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9784 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009785 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009786 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009787 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009788 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009789 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9790 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009791 if (Hint.isNull() && !CheckInferredResultType) {
9792 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9793 }
9794 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009795 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009796 case IncompatiblePointerSign:
9797 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9798 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009799 case FunctionVoidPointer:
9800 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9801 break;
John McCall86c05f32011-02-01 00:10:29 +00009802 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009803 // Perform array-to-pointer decay if necessary.
9804 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9805
John McCall86c05f32011-02-01 00:10:29 +00009806 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9807 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9808 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9809 DiagKind = diag::err_typecheck_incompatible_address_space;
9810 break;
John McCallf85e1932011-06-15 23:02:42 +00009811
9812
9813 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009814 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009815 break;
John McCall86c05f32011-02-01 00:10:29 +00009816 }
9817
9818 llvm_unreachable("unknown error case for discarding qualifiers!");
9819 // fallthrough
9820 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009821 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009822 // If the qualifiers lost were because we were applying the
9823 // (deprecated) C++ conversion from a string literal to a char*
9824 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9825 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009826 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009827 // bit of refactoring (so that the second argument is an
9828 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009829 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009830 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009831 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009832 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9833 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009834 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9835 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009836 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009837 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009838 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009839 case IntToBlockPointer:
9840 DiagKind = diag::err_int_to_block_pointer;
9841 break;
9842 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009843 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009844 break;
Steve Naroff39579072008-10-14 22:18:38 +00009845 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009846 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009847 // it can give a more specific diagnostic.
9848 DiagKind = diag::warn_incompatible_qualified_id;
9849 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009850 case IncompatibleVectors:
9851 DiagKind = diag::warn_incompatible_vectors;
9852 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009853 case IncompatibleObjCWeakRef:
9854 DiagKind = diag::err_arc_weak_unavailable_assign;
9855 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009856 case Incompatible:
9857 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9859 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009860 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009861 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009862 break;
9863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009864
Douglas Gregord4eea832010-04-09 00:35:39 +00009865 QualType FirstType, SecondType;
9866 switch (Action) {
9867 case AA_Assigning:
9868 case AA_Initializing:
9869 // The destination type comes first.
9870 FirstType = DstType;
9871 SecondType = SrcType;
9872 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009873
Douglas Gregord4eea832010-04-09 00:35:39 +00009874 case AA_Returning:
9875 case AA_Passing:
9876 case AA_Converting:
9877 case AA_Sending:
9878 case AA_Casting:
9879 // The source type comes first.
9880 FirstType = SrcType;
9881 SecondType = DstType;
9882 break;
9883 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009884
Anna Zaks67221552011-07-28 19:51:27 +00009885 PartialDiagnostic FDiag = PDiag(DiagKind);
9886 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9887
9888 // If we can fix the conversion, suggest the FixIts.
9889 assert(ConvHints.isNull() || Hint.isNull());
9890 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009891 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9892 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009893 FDiag << *HI;
9894 } else {
9895 FDiag << Hint;
9896 }
9897 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9898
Richard Trieu6efd4c52011-11-23 22:32:32 +00009899 if (MayHaveFunctionDiff)
9900 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9901
Anna Zaks67221552011-07-28 19:51:27 +00009902 Diag(Loc, FDiag);
9903
Richard Trieu6efd4c52011-11-23 22:32:32 +00009904 if (SecondType == Context.OverloadTy)
9905 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9906 FirstType);
9907
Douglas Gregor926df6c2011-06-11 01:09:30 +00009908 if (CheckInferredResultType)
9909 EmitRelatedResultTypeNote(SrcExpr);
9910
Douglas Gregora41a8c52010-04-22 00:20:18 +00009911 if (Complained)
9912 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009913 return isInvalid;
9914}
Anders Carlssone21555e2008-11-30 19:50:32 +00009915
Richard Smith282e7e62012-02-04 09:53:13 +00009916ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9917 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009918 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9919 public:
9920 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9921 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9922 }
9923 } Diagnoser;
9924
9925 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9926}
9927
9928ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9929 llvm::APSInt *Result,
9930 unsigned DiagID,
9931 bool AllowFold) {
9932 class IDDiagnoser : public VerifyICEDiagnoser {
9933 unsigned DiagID;
9934
9935 public:
9936 IDDiagnoser(unsigned DiagID)
9937 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9938
9939 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9940 S.Diag(Loc, DiagID) << SR;
9941 }
9942 } Diagnoser(DiagID);
9943
9944 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9945}
9946
9947void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9948 SourceRange SR) {
9949 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009950}
9951
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009952ExprResult
9953Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009954 VerifyICEDiagnoser &Diagnoser,
9955 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009956 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009957
David Blaikie4e4d0842012-03-11 07:00:24 +00009958 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009959 // C++11 [expr.const]p5:
9960 // If an expression of literal class type is used in a context where an
9961 // integral constant expression is required, then that class type shall
9962 // have a single non-explicit conversion function to an integral or
9963 // unscoped enumeration type
9964 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009965 if (!Diagnoser.Suppress) {
9966 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9967 public:
9968 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9969
9970 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9971 QualType T) {
9972 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9973 }
9974
9975 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9976 SourceLocation Loc,
9977 QualType T) {
9978 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9979 }
9980
9981 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9982 SourceLocation Loc,
9983 QualType T,
9984 QualType ConvTy) {
9985 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9986 }
9987
9988 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9989 CXXConversionDecl *Conv,
9990 QualType ConvTy) {
9991 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9992 << ConvTy->isEnumeralType() << ConvTy;
9993 }
9994
9995 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9996 QualType T) {
9997 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9998 }
9999
10000 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10001 CXXConversionDecl *Conv,
10002 QualType ConvTy) {
10003 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10004 << ConvTy->isEnumeralType() << ConvTy;
10005 }
10006
10007 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10008 SourceLocation Loc,
10009 QualType T,
10010 QualType ConvTy) {
10011 return DiagnosticBuilder::getEmpty();
10012 }
10013 } ConvertDiagnoser;
10014
10015 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10016 ConvertDiagnoser,
10017 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010018 } else {
10019 // The caller wants to silently enquire whether this is an ICE. Don't
10020 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010021 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10022 public:
10023 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10024
10025 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10026 QualType T) {
10027 return DiagnosticBuilder::getEmpty();
10028 }
10029
10030 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10031 SourceLocation Loc,
10032 QualType T) {
10033 return DiagnosticBuilder::getEmpty();
10034 }
10035
10036 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10037 SourceLocation Loc,
10038 QualType T,
10039 QualType ConvTy) {
10040 return DiagnosticBuilder::getEmpty();
10041 }
10042
10043 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10044 CXXConversionDecl *Conv,
10045 QualType ConvTy) {
10046 return DiagnosticBuilder::getEmpty();
10047 }
10048
10049 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10050 QualType T) {
10051 return DiagnosticBuilder::getEmpty();
10052 }
10053
10054 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10055 CXXConversionDecl *Conv,
10056 QualType ConvTy) {
10057 return DiagnosticBuilder::getEmpty();
10058 }
10059
10060 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10061 SourceLocation Loc,
10062 QualType T,
10063 QualType ConvTy) {
10064 return DiagnosticBuilder::getEmpty();
10065 }
10066 } ConvertDiagnoser;
10067
10068 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10069 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010070 }
10071 if (Converted.isInvalid())
10072 return Converted;
10073 E = Converted.take();
10074 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10075 return ExprError();
10076 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10077 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010078 if (!Diagnoser.Suppress)
10079 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010080 return ExprError();
10081 }
10082
Richard Smithdaaefc52011-12-14 23:32:26 +000010083 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10084 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +000010085 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010086 if (Result)
10087 *Result = E->EvaluateKnownConstInt(Context);
10088 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010089 }
10090
Anders Carlssone21555e2008-11-30 19:50:32 +000010091 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010092 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10093 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010094
Richard Smithdaaefc52011-12-14 23:32:26 +000010095 // Try to evaluate the expression, and produce diagnostics explaining why it's
10096 // not a constant expression as a side-effect.
10097 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10098 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10099
10100 // In C++11, we can rely on diagnostics being produced for any expression
10101 // which is not a constant expression. If no diagnostics were produced, then
10102 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010103 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010104 if (Result)
10105 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010106 return Owned(E);
10107 }
10108
10109 // If our only note is the usual "invalid subexpression" note, just point
10110 // the caret at its location rather than producing an essentially
10111 // redundant note.
10112 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10113 diag::note_invalid_subexpr_in_const_expr) {
10114 DiagLoc = Notes[0].first;
10115 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010116 }
10117
10118 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010119 if (!Diagnoser.Suppress) {
10120 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010121 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10122 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010123 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010124
Richard Smith282e7e62012-02-04 09:53:13 +000010125 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010126 }
10127
Douglas Gregorab41fe92012-05-04 22:38:52 +000010128 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010129 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10130 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010131
Anders Carlssone21555e2008-11-30 19:50:32 +000010132 if (Result)
10133 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010134 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010135}
Douglas Gregore0762c92009-06-19 23:52:42 +000010136
Eli Friedmanef331b72012-01-20 01:26:23 +000010137namespace {
10138 // Handle the case where we conclude a expression which we speculatively
10139 // considered to be unevaluated is actually evaluated.
10140 class TransformToPE : public TreeTransform<TransformToPE> {
10141 typedef TreeTransform<TransformToPE> BaseTransform;
10142
10143 public:
10144 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10145
10146 // Make sure we redo semantic analysis
10147 bool AlwaysRebuild() { return true; }
10148
Eli Friedman56ff2832012-02-06 23:29:57 +000010149 // Make sure we handle LabelStmts correctly.
10150 // FIXME: This does the right thing, but maybe we need a more general
10151 // fix to TreeTransform?
10152 StmtResult TransformLabelStmt(LabelStmt *S) {
10153 S->getDecl()->setStmt(0);
10154 return BaseTransform::TransformLabelStmt(S);
10155 }
10156
Eli Friedmanef331b72012-01-20 01:26:23 +000010157 // We need to special-case DeclRefExprs referring to FieldDecls which
10158 // are not part of a member pointer formation; normal TreeTransforming
10159 // doesn't catch this case because of the way we represent them in the AST.
10160 // FIXME: This is a bit ugly; is it really the best way to handle this
10161 // case?
10162 //
10163 // Error on DeclRefExprs referring to FieldDecls.
10164 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10165 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010166 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010167 return SemaRef.Diag(E->getLocation(),
10168 diag::err_invalid_non_static_member_use)
10169 << E->getDecl() << E->getSourceRange();
10170
10171 return BaseTransform::TransformDeclRefExpr(E);
10172 }
10173
10174 // Exception: filter out member pointer formation
10175 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10176 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10177 return E;
10178
10179 return BaseTransform::TransformUnaryOperator(E);
10180 }
10181
Douglas Gregore2c59132012-02-09 08:14:43 +000010182 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10183 // Lambdas never need to be transformed.
10184 return E;
10185 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010186 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010187}
10188
Eli Friedmanef331b72012-01-20 01:26:23 +000010189ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010190 assert(ExprEvalContexts.back().Context == Unevaluated &&
10191 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010192 ExprEvalContexts.back().Context =
10193 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10194 if (ExprEvalContexts.back().Context == Unevaluated)
10195 return E;
10196 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010197}
10198
Douglas Gregor2afce722009-11-26 00:44:06 +000010199void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010200Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010201 Decl *LambdaContextDecl,
10202 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010203 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010204 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010205 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010206 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010207 LambdaContextDecl,
10208 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010209 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010210 if (!MaybeODRUseExprs.empty())
10211 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010212}
10213
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010214void
10215Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10216 ReuseLambdaContextDecl_t,
10217 bool IsDecltype) {
10218 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10219 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10220}
10221
Richard Trieu67e29332011-08-02 04:35:43 +000010222void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010223 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010224
Douglas Gregore2c59132012-02-09 08:14:43 +000010225 if (!Rec.Lambdas.empty()) {
10226 if (Rec.Context == Unevaluated) {
10227 // C++11 [expr.prim.lambda]p2:
10228 // A lambda-expression shall not appear in an unevaluated operand
10229 // (Clause 5).
10230 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10231 Diag(Rec.Lambdas[I]->getLocStart(),
10232 diag::err_lambda_unevaluated_operand);
10233 } else {
10234 // Mark the capture expressions odr-used. This was deferred
10235 // during lambda expression creation.
10236 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10237 LambdaExpr *Lambda = Rec.Lambdas[I];
10238 for (LambdaExpr::capture_init_iterator
10239 C = Lambda->capture_init_begin(),
10240 CEnd = Lambda->capture_init_end();
10241 C != CEnd; ++C) {
10242 MarkDeclarationsReferencedInExpr(*C);
10243 }
10244 }
10245 }
10246 }
10247
Douglas Gregor2afce722009-11-26 00:44:06 +000010248 // When are coming out of an unevaluated context, clear out any
10249 // temporaries that we may have created as part of the evaluation of
10250 // the expression in that context: they aren't relevant because they
10251 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010252 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010253 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10254 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010255 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010256 CleanupVarDeclMarking();
10257 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010258 // Otherwise, merge the contexts together.
10259 } else {
10260 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010261 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10262 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010263 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010264
10265 // Pop the current expression evaluation context off the stack.
10266 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010267}
Douglas Gregore0762c92009-06-19 23:52:42 +000010268
John McCallf85e1932011-06-15 23:02:42 +000010269void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010270 ExprCleanupObjects.erase(
10271 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10272 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010273 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010274 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010275}
10276
Eli Friedman71b8fb52012-01-21 01:01:51 +000010277ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10278 if (!E->getType()->isVariablyModifiedType())
10279 return E;
10280 return TranformToPotentiallyEvaluated(E);
10281}
10282
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010283static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010284 // Do not mark anything as "used" within a dependent context; wait for
10285 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010286 if (SemaRef.CurContext->isDependentContext())
10287 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010288
Eli Friedman5f2987c2012-02-02 03:46:19 +000010289 switch (SemaRef.ExprEvalContexts.back().Context) {
10290 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010291 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010292 // (Depending on how you read the standard, we actually do need to do
10293 // something here for null pointer constants, but the standard's
10294 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010295 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010296
Eli Friedman5f2987c2012-02-02 03:46:19 +000010297 case Sema::ConstantEvaluated:
10298 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010299 // We are in a potentially evaluated expression (or a constant-expression
10300 // in C++03); we need to do implicit template instantiation, implicitly
10301 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010302 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010303
Eli Friedman5f2987c2012-02-02 03:46:19 +000010304 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010305 // Referenced declarations will only be used if the construct in the
10306 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010307 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010308 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010309 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010310}
10311
10312/// \brief Mark a function referenced, and check whether it is odr-used
10313/// (C++ [basic.def.odr]p2, C99 6.9p3)
10314void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10315 assert(Func && "No function?");
10316
10317 Func->setReferenced();
10318
Richard Smith57b9c4e2012-02-14 22:25:15 +000010319 // Don't mark this function as used multiple times, unless it's a constexpr
10320 // function which we need to instantiate.
10321 if (Func->isUsed(false) &&
10322 !(Func->isConstexpr() && !Func->getBody() &&
10323 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010324 return;
10325
10326 if (!IsPotentiallyEvaluatedContext(*this))
10327 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010328
Douglas Gregore0762c92009-06-19 23:52:42 +000010329 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010330 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010331 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010332 if (Constructor->isDefaultConstructor()) {
10333 if (Constructor->isTrivial())
10334 return;
10335 if (!Constructor->isUsed(false))
10336 DefineImplicitDefaultConstructor(Loc, Constructor);
10337 } else if (Constructor->isCopyConstructor()) {
10338 if (!Constructor->isUsed(false))
10339 DefineImplicitCopyConstructor(Loc, Constructor);
10340 } else if (Constructor->isMoveConstructor()) {
10341 if (!Constructor->isUsed(false))
10342 DefineImplicitMoveConstructor(Loc, Constructor);
10343 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010344 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010345
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010346 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010347 } else if (CXXDestructorDecl *Destructor =
10348 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010349 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10350 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010351 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010352 if (Destructor->isVirtual())
10353 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010354 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010355 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10356 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010357 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010358 if (!MethodDecl->isUsed(false)) {
10359 if (MethodDecl->isCopyAssignmentOperator())
10360 DefineImplicitCopyAssignment(Loc, MethodDecl);
10361 else
10362 DefineImplicitMoveAssignment(Loc, MethodDecl);
10363 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010364 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10365 MethodDecl->getParent()->isLambda()) {
10366 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10367 if (Conversion->isLambdaToBlockPointerConversion())
10368 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10369 else
10370 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010371 } else if (MethodDecl->isVirtual())
10372 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010373 }
John McCall15e310a2011-02-19 02:53:41 +000010374
Eli Friedman5f2987c2012-02-02 03:46:19 +000010375 // Recursive functions should be marked when used from another function.
10376 // FIXME: Is this really right?
10377 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010378
Richard Smithb9d0b762012-07-27 04:22:15 +000010379 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010380 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010381 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010382 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10383 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010384
Eli Friedman5f2987c2012-02-02 03:46:19 +000010385 // Implicit instantiation of function templates and member functions of
10386 // class templates.
10387 if (Func->isImplicitlyInstantiable()) {
10388 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010389 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010390 if (FunctionTemplateSpecializationInfo *SpecInfo
10391 = Func->getTemplateSpecializationInfo()) {
10392 if (SpecInfo->getPointOfInstantiation().isInvalid())
10393 SpecInfo->setPointOfInstantiation(Loc);
10394 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010395 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010396 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010397 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10398 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010399 } else if (MemberSpecializationInfo *MSInfo
10400 = Func->getMemberSpecializationInfo()) {
10401 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010402 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010403 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010404 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010405 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010406 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10407 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010408 }
Mike Stump1eb44332009-09-09 15:08:12 +000010409
Richard Smith57b9c4e2012-02-14 22:25:15 +000010410 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010411 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10412 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010413 PendingLocalImplicitInstantiations.push_back(
10414 std::make_pair(Func, PointOfInstantiation));
10415 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010416 // Do not defer instantiations of constexpr functions, to avoid the
10417 // expression evaluator needing to call back into Sema if it sees a
10418 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010419 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010420 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010421 PendingInstantiations.push_back(std::make_pair(Func,
10422 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010423 // Notify the consumer that a function was implicitly instantiated.
10424 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10425 }
John McCall15e310a2011-02-19 02:53:41 +000010426 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010427 } else {
10428 // Walk redefinitions, as some of them may be instantiable.
10429 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10430 e(Func->redecls_end()); i != e; ++i) {
10431 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10432 MarkFunctionReferenced(Loc, *i);
10433 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010434 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010435
10436 // Keep track of used but undefined functions.
10437 if (!Func->isPure() && !Func->hasBody() &&
10438 Func->getLinkage() != ExternalLinkage) {
10439 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10440 if (old.isInvalid()) old = Loc;
10441 }
10442
10443 Func->setUsed(true);
10444}
10445
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010446static void
10447diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10448 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010449 DeclContext *VarDC = var->getDeclContext();
10450
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010451 // If the parameter still belongs to the translation unit, then
10452 // we're actually just using one parameter in the declaration of
10453 // the next.
10454 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010455 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010456 return;
10457
Eli Friedman0a294222012-02-07 00:15:00 +000010458 // For C code, don't diagnose about capture if we're not actually in code
10459 // right now; it's impossible to write a non-constant expression outside of
10460 // function context, so we'll get other (more useful) diagnostics later.
10461 //
10462 // For C++, things get a bit more nasty... it would be nice to suppress this
10463 // diagnostic for certain cases like using a local variable in an array bound
10464 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010465 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010466 return;
10467
Eli Friedman0a294222012-02-07 00:15:00 +000010468 if (isa<CXXMethodDecl>(VarDC) &&
10469 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10470 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10471 << var->getIdentifier();
10472 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10473 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10474 << var->getIdentifier() << fn->getDeclName();
10475 } else if (isa<BlockDecl>(VarDC)) {
10476 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10477 << var->getIdentifier();
10478 } else {
10479 // FIXME: Is there any other context where a local variable can be
10480 // declared?
10481 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10482 << var->getIdentifier();
10483 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010484
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010485 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10486 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010487
10488 // FIXME: Add additional diagnostic info about class etc. which prevents
10489 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010490}
10491
Douglas Gregorf8af9822012-02-12 18:42:33 +000010492/// \brief Capture the given variable in the given lambda expression.
10493static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010494 VarDecl *Var, QualType FieldType,
10495 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010496 SourceLocation Loc,
10497 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010498 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010499
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010500 // Build the non-static data member.
10501 FieldDecl *Field
10502 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10503 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010504 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010505 Field->setImplicit(true);
10506 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010507 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010508
10509 // C++11 [expr.prim.lambda]p21:
10510 // When the lambda-expression is evaluated, the entities that
10511 // are captured by copy are used to direct-initialize each
10512 // corresponding non-static data member of the resulting closure
10513 // object. (For array members, the array elements are
10514 // direct-initialized in increasing subscript order.) These
10515 // initializations are performed in the (unspecified) order in
10516 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010517
Douglas Gregore2c59132012-02-09 08:14:43 +000010518 // Introduce a new evaluation context for the initialization, so
10519 // that temporaries introduced as part of the capture are retained
10520 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010521 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10522
Douglas Gregor73d90922012-02-10 09:26:04 +000010523 // C++ [expr.prim.labda]p12:
10524 // An entity captured by a lambda-expression is odr-used (3.2) in
10525 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010526 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10527 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010528 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010529 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010530
10531 // When the field has array type, create index variables for each
10532 // dimension of the array. We use these index variables to subscript
10533 // the source array, and other clients (e.g., CodeGen) will perform
10534 // the necessary iteration with these index variables.
10535 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010536 QualType BaseType = FieldType;
10537 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010538 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010539 while (const ConstantArrayType *Array
10540 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010541 // Create the iteration variable for this array index.
10542 IdentifierInfo *IterationVarName = 0;
10543 {
10544 SmallString<8> Str;
10545 llvm::raw_svector_ostream OS(Str);
10546 OS << "__i" << IndexVariables.size();
10547 IterationVarName = &S.Context.Idents.get(OS.str());
10548 }
10549 VarDecl *IterationVar
10550 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10551 IterationVarName, SizeType,
10552 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10553 SC_None, SC_None);
10554 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010555 LSI->ArrayIndexVars.push_back(IterationVar);
10556
Douglas Gregor18fe0842012-02-09 02:45:47 +000010557 // Create a reference to the iteration variable.
10558 ExprResult IterationVarRef
10559 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10560 assert(!IterationVarRef.isInvalid() &&
10561 "Reference to invented variable cannot fail!");
10562 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10563 assert(!IterationVarRef.isInvalid() &&
10564 "Conversion of invented variable cannot fail!");
10565
10566 // Subscript the array with this iteration variable.
10567 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10568 Ref, Loc, IterationVarRef.take(), Loc);
10569 if (Subscript.isInvalid()) {
10570 S.CleanupVarDeclMarking();
10571 S.DiscardCleanupsInEvaluationContext();
10572 S.PopExpressionEvaluationContext();
10573 return ExprError();
10574 }
10575
10576 Ref = Subscript.take();
10577 BaseType = Array->getElementType();
10578 }
10579
10580 // Construct the entity that we will be initializing. For an array, this
10581 // will be first element in the array, which may require several levels
10582 // of array-subscript entities.
10583 SmallVector<InitializedEntity, 4> Entities;
10584 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010585 Entities.push_back(
10586 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010587 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10588 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10589 0,
10590 Entities.back()));
10591
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010592 InitializationKind InitKind
10593 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010594 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010595 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010596 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010597 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010598
10599 // If this initialization requires any cleanups (e.g., due to a
10600 // default argument to a copy constructor), note that for the
10601 // lambda.
10602 if (S.ExprNeedsCleanups)
10603 LSI->ExprNeedsCleanups = true;
10604
10605 // Exit the expression evaluation context used for the capture.
10606 S.CleanupVarDeclMarking();
10607 S.DiscardCleanupsInEvaluationContext();
10608 S.PopExpressionEvaluationContext();
10609 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010610}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010611
Douglas Gregor999713e2012-02-18 09:37:24 +000010612bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10613 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10614 bool BuildAndDiagnose,
10615 QualType &CaptureType,
10616 QualType &DeclRefType) {
10617 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010618
Eli Friedmanb942cb22012-02-03 22:47:37 +000010619 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010620 if (Var->getDeclContext() == DC) return true;
10621 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010622
Douglas Gregorf8af9822012-02-12 18:42:33 +000010623 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010624
Douglas Gregor999713e2012-02-18 09:37:24 +000010625 // Walk up the stack to determine whether we can capture the variable,
10626 // performing the "simple" checks that don't depend on type. We stop when
10627 // we've either hit the declared scope of the variable or find an existing
10628 // capture of that variable.
10629 CaptureType = Var->getType();
10630 DeclRefType = CaptureType.getNonReferenceType();
10631 bool Explicit = (Kind != TryCapture_Implicit);
10632 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010633 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010634 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010635 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010636 DeclContext *ParentDC;
10637 if (isa<BlockDecl>(DC))
10638 ParentDC = DC->getParent();
10639 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010640 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010641 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10642 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010643 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010644 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010645 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010646 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010647 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010648
Eli Friedmanb942cb22012-02-03 22:47:37 +000010649 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010650 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010651
Eli Friedmanb942cb22012-02-03 22:47:37 +000010652 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010653 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010654 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010655 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010656
10657 // Retrieve the capture type for this variable.
10658 CaptureType = CSI->getCapture(Var).getCaptureType();
10659
10660 // Compute the type of an expression that refers to this variable.
10661 DeclRefType = CaptureType.getNonReferenceType();
10662
10663 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10664 if (Cap.isCopyCapture() &&
10665 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10666 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010667 break;
10668 }
10669
Douglas Gregorf8af9822012-02-12 18:42:33 +000010670 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010671 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010672
10673 // Lambdas are not allowed to capture unnamed variables
10674 // (e.g. anonymous unions).
10675 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10676 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010677 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010678 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010679 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10680 Diag(Var->getLocation(), diag::note_declared_at);
10681 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010682 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010683 }
10684
10685 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010686 if (Var->getType()->isVariablyModifiedType()) {
10687 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010688 if (IsBlock)
10689 Diag(Loc, diag::err_ref_vm_type);
10690 else
10691 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10692 Diag(Var->getLocation(), diag::note_previous_decl)
10693 << Var->getDeclName();
10694 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010695 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010696 }
10697
Eli Friedmanb942cb22012-02-03 22:47:37 +000010698 // Lambdas are not allowed to capture __block variables; they don't
10699 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010700 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010701 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010702 Diag(Loc, diag::err_lambda_capture_block)
10703 << Var->getDeclName();
10704 Diag(Var->getLocation(), diag::note_previous_decl)
10705 << Var->getDeclName();
10706 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010707 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010708 }
10709
Douglas Gregorf8af9822012-02-12 18:42:33 +000010710 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10711 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010712 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010713 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10714 Diag(Var->getLocation(), diag::note_previous_decl)
10715 << Var->getDeclName();
10716 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10717 diag::note_lambda_decl);
10718 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010719 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010720 }
10721
10722 FunctionScopesIndex--;
10723 DC = ParentDC;
10724 Explicit = false;
10725 } while (!Var->getDeclContext()->Equals(DC));
10726
Douglas Gregor999713e2012-02-18 09:37:24 +000010727 // Walk back down the scope stack, computing the type of the capture at
10728 // each step, checking type-specific requirements, and adding captures if
10729 // requested.
10730 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10731 ++I) {
10732 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010733
Douglas Gregor999713e2012-02-18 09:37:24 +000010734 // Compute the type of the capture and of a reference to the capture within
10735 // this scope.
10736 if (isa<BlockScopeInfo>(CSI)) {
10737 Expr *CopyExpr = 0;
10738 bool ByRef = false;
10739
10740 // Blocks are not allowed to capture arrays.
10741 if (CaptureType->isArrayType()) {
10742 if (BuildAndDiagnose) {
10743 Diag(Loc, diag::err_ref_array_type);
10744 Diag(Var->getLocation(), diag::note_previous_decl)
10745 << Var->getDeclName();
10746 }
10747 return true;
10748 }
10749
John McCall100c6492012-03-30 05:23:48 +000010750 // Forbid the block-capture of autoreleasing variables.
10751 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10752 if (BuildAndDiagnose) {
10753 Diag(Loc, diag::err_arc_autoreleasing_capture)
10754 << /*block*/ 0;
10755 Diag(Var->getLocation(), diag::note_previous_decl)
10756 << Var->getDeclName();
10757 }
10758 return true;
10759 }
10760
Douglas Gregor999713e2012-02-18 09:37:24 +000010761 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10762 // Block capture by reference does not change the capture or
10763 // declaration reference types.
10764 ByRef = true;
10765 } else {
10766 // Block capture by copy introduces 'const'.
10767 CaptureType = CaptureType.getNonReferenceType().withConst();
10768 DeclRefType = CaptureType;
10769
David Blaikie4e4d0842012-03-11 07:00:24 +000010770 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010771 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10772 // The capture logic needs the destructor, so make sure we mark it.
10773 // Usually this is unnecessary because most local variables have
10774 // their destructors marked at declaration time, but parameters are
10775 // an exception because it's technically only the call site that
10776 // actually requires the destructor.
10777 if (isa<ParmVarDecl>(Var))
10778 FinalizeVarWithDestructor(Var, Record);
10779
10780 // According to the blocks spec, the capture of a variable from
10781 // the stack requires a const copy constructor. This is not true
10782 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010783 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010784 DeclRefType.withConst(),
10785 VK_LValue, Loc);
10786 ExprResult Result
10787 = PerformCopyInitialization(
10788 InitializedEntity::InitializeBlock(Var->getLocation(),
10789 CaptureType, false),
10790 Loc, Owned(DeclRef));
10791
10792 // Build a full-expression copy expression if initialization
10793 // succeeded and used a non-trivial constructor. Recover from
10794 // errors by pretending that the copy isn't necessary.
10795 if (!Result.isInvalid() &&
10796 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10797 ->isTrivial()) {
10798 Result = MaybeCreateExprWithCleanups(Result);
10799 CopyExpr = Result.take();
10800 }
10801 }
10802 }
10803 }
10804
10805 // Actually capture the variable.
10806 if (BuildAndDiagnose)
10807 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10808 SourceLocation(), CaptureType, CopyExpr);
10809 Nested = true;
10810 continue;
10811 }
Douglas Gregor68932842012-02-18 05:51:20 +000010812
Douglas Gregor999713e2012-02-18 09:37:24 +000010813 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10814
10815 // Determine whether we are capturing by reference or by value.
10816 bool ByRef = false;
10817 if (I == N - 1 && Kind != TryCapture_Implicit) {
10818 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010819 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010820 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010821 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010822
10823 // Compute the type of the field that will capture this variable.
10824 if (ByRef) {
10825 // C++11 [expr.prim.lambda]p15:
10826 // An entity is captured by reference if it is implicitly or
10827 // explicitly captured but not captured by copy. It is
10828 // unspecified whether additional unnamed non-static data
10829 // members are declared in the closure type for entities
10830 // captured by reference.
10831 //
10832 // FIXME: It is not clear whether we want to build an lvalue reference
10833 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10834 // to do the former, while EDG does the latter. Core issue 1249 will
10835 // clarify, but for now we follow GCC because it's a more permissive and
10836 // easily defensible position.
10837 CaptureType = Context.getLValueReferenceType(DeclRefType);
10838 } else {
10839 // C++11 [expr.prim.lambda]p14:
10840 // For each entity captured by copy, an unnamed non-static
10841 // data member is declared in the closure type. The
10842 // declaration order of these members is unspecified. The type
10843 // of such a data member is the type of the corresponding
10844 // captured entity if the entity is not a reference to an
10845 // object, or the referenced type otherwise. [Note: If the
10846 // captured entity is a reference to a function, the
10847 // corresponding data member is also a reference to a
10848 // function. - end note ]
10849 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10850 if (!RefType->getPointeeType()->isFunctionType())
10851 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010852 }
John McCall100c6492012-03-30 05:23:48 +000010853
10854 // Forbid the lambda copy-capture of autoreleasing variables.
10855 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10856 if (BuildAndDiagnose) {
10857 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10858 Diag(Var->getLocation(), diag::note_previous_decl)
10859 << Var->getDeclName();
10860 }
10861 return true;
10862 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010863 }
10864
Douglas Gregor999713e2012-02-18 09:37:24 +000010865 // Capture this variable in the lambda.
10866 Expr *CopyExpr = 0;
10867 if (BuildAndDiagnose) {
10868 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010869 DeclRefType, Loc,
10870 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010871 if (!Result.isInvalid())
10872 CopyExpr = Result.take();
10873 }
10874
10875 // Compute the type of a reference to this captured variable.
10876 if (ByRef)
10877 DeclRefType = CaptureType.getNonReferenceType();
10878 else {
10879 // C++ [expr.prim.lambda]p5:
10880 // The closure type for a lambda-expression has a public inline
10881 // function call operator [...]. This function call operator is
10882 // declared const (9.3.1) if and only if the lambda-expression’s
10883 // parameter-declaration-clause is not followed by mutable.
10884 DeclRefType = CaptureType.getNonReferenceType();
10885 if (!LSI->Mutable && !CaptureType->isReferenceType())
10886 DeclRefType.addConst();
10887 }
10888
10889 // Add the capture.
10890 if (BuildAndDiagnose)
10891 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10892 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010893 Nested = true;
10894 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010895
10896 return false;
10897}
10898
10899bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10900 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10901 QualType CaptureType;
10902 QualType DeclRefType;
10903 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10904 /*BuildAndDiagnose=*/true, CaptureType,
10905 DeclRefType);
10906}
10907
10908QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10909 QualType CaptureType;
10910 QualType DeclRefType;
10911
10912 // Determine whether we can capture this variable.
10913 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10914 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10915 return QualType();
10916
10917 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010918}
10919
Eli Friedmand2cce132012-02-02 23:15:15 +000010920static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10921 SourceLocation Loc) {
10922 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010923 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010924 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010925 Var->getLinkage() != ExternalLinkage &&
10926 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010927 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10928 if (old.isInvalid()) old = Loc;
10929 }
10930
Douglas Gregor999713e2012-02-18 09:37:24 +000010931 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010932
Eli Friedmand2cce132012-02-02 23:15:15 +000010933 Var->setUsed(true);
10934}
10935
10936void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10937 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10938 // an object that satisfies the requirements for appearing in a
10939 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10940 // is immediately applied." This function handles the lvalue-to-rvalue
10941 // conversion part.
10942 MaybeODRUseExprs.erase(E->IgnoreParens());
10943}
10944
Eli Friedmanac626012012-02-29 03:16:56 +000010945ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10946 if (!Res.isUsable())
10947 return Res;
10948
10949 // If a constant-expression is a reference to a variable where we delay
10950 // deciding whether it is an odr-use, just assume we will apply the
10951 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10952 // (a non-type template argument), we have special handling anyway.
10953 UpdateMarkingForLValueToRValue(Res.get());
10954 return Res;
10955}
10956
Eli Friedmand2cce132012-02-02 23:15:15 +000010957void Sema::CleanupVarDeclMarking() {
10958 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10959 e = MaybeODRUseExprs.end();
10960 i != e; ++i) {
10961 VarDecl *Var;
10962 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010963 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010964 Var = cast<VarDecl>(DRE->getDecl());
10965 Loc = DRE->getLocation();
10966 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10967 Var = cast<VarDecl>(ME->getMemberDecl());
10968 Loc = ME->getMemberLoc();
10969 } else {
10970 llvm_unreachable("Unexpcted expression");
10971 }
10972
10973 MarkVarDeclODRUsed(*this, Var, Loc);
10974 }
10975
10976 MaybeODRUseExprs.clear();
10977}
10978
10979// Mark a VarDecl referenced, and perform the necessary handling to compute
10980// odr-uses.
10981static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10982 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010983 Var->setReferenced();
10984
Eli Friedmand2cce132012-02-02 23:15:15 +000010985 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010986 return;
10987
10988 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010989 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010990 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10991 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010992 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10993 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010994 (!AlreadyInstantiated ||
10995 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010996 if (!AlreadyInstantiated) {
10997 // This is a modification of an existing AST node. Notify listeners.
10998 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10999 L->StaticDataMemberInstantiated(Var);
11000 MSInfo->setPointOfInstantiation(Loc);
11001 }
11002 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011003 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011004 // Do not defer instantiations of variables which could be used in a
11005 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011006 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011007 else
Richard Smith37ce0102012-02-15 02:42:50 +000011008 SemaRef.PendingInstantiations.push_back(
11009 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011010 }
11011 }
11012
Eli Friedmand2cce132012-02-02 23:15:15 +000011013 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11014 // an object that satisfies the requirements for appearing in a
11015 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11016 // is immediately applied." We check the first part here, and
11017 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11018 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000011019 // C++03 depends on whether we get the C++03 version correct. This does not
11020 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011021 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000011022 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011023 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000011024 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
11025 SemaRef.MaybeODRUseExprs.insert(E);
11026 else
11027 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11028}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011029
Eli Friedmand2cce132012-02-02 23:15:15 +000011030/// \brief Mark a variable referenced, and check whether it is odr-used
11031/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11032/// used directly for normal expressions referring to VarDecl.
11033void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11034 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011035}
11036
11037static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11038 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011039 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11040 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11041 return;
11042 }
11043
Eli Friedman5f2987c2012-02-02 03:46:19 +000011044 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011045
11046 // If this is a call to a method via a cast, also mark the method in the
11047 // derived class used in case codegen can devirtualize the call.
11048 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11049 if (!ME)
11050 return;
11051 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11052 if (!MD)
11053 return;
11054 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011055 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011056 if (!MostDerivedClassDecl)
11057 return;
11058 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011059 if (!DM)
11060 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011061 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011062}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011063
Eli Friedman5f2987c2012-02-02 03:46:19 +000011064/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11065void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11066 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11067}
11068
11069/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11070void Sema::MarkMemberReferenced(MemberExpr *E) {
11071 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11072}
11073
Douglas Gregor73d90922012-02-10 09:26:04 +000011074/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011075/// marks the declaration referenced, and performs odr-use checking for functions
11076/// and variables. This method should not be used when building an normal
11077/// expression which refers to a variable.
11078void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11079 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11080 MarkVariableReferenced(Loc, VD);
11081 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11082 MarkFunctionReferenced(Loc, FD);
11083 else
11084 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011085}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011086
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011087namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011088 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011089 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011090 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011091 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11092 Sema &S;
11093 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011094
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011095 public:
11096 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011097
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011098 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011099
11100 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11101 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011102 };
11103}
11104
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011105bool MarkReferencedDecls::TraverseTemplateArgument(
11106 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011107 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011108 if (Decl *D = Arg.getAsDecl())
11109 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011110 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011111
11112 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011113}
11114
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011115bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011116 if (ClassTemplateSpecializationDecl *Spec
11117 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11118 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011119 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011120 }
11121
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011122 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011123}
11124
11125void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11126 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011127 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011128}
11129
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011130namespace {
11131 /// \brief Helper class that marks all of the declarations referenced by
11132 /// potentially-evaluated subexpressions as "referenced".
11133 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11134 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011135 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011136
11137 public:
11138 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11139
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011140 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11141 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011142
11143 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011144 // If we were asked not to visit local variables, don't.
11145 if (SkipLocalVariables) {
11146 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11147 if (VD->hasLocalStorage())
11148 return;
11149 }
11150
Eli Friedman5f2987c2012-02-02 03:46:19 +000011151 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011152 }
11153
11154 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011155 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011156 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011157 }
11158
John McCall80ee6e82011-11-10 05:35:25 +000011159 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011160 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011161 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11162 Visit(E->getSubExpr());
11163 }
11164
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011165 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011166 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011167 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011168 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011169 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011170 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011171 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011172
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011173 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11174 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011175 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011176 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11177 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11178 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011179 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011180 S.LookupDestructor(Record));
11181 }
11182
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011183 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011184 }
11185
11186 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011187 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011188 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011189 }
11190
Douglas Gregor102ff972010-10-19 17:17:35 +000011191 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11192 Visit(E->getExpr());
11193 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011194
11195 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11196 Inherited::VisitImplicitCastExpr(E);
11197
11198 if (E->getCastKind() == CK_LValueToRValue)
11199 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11200 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011201 };
11202}
11203
11204/// \brief Mark any declarations that appear within this expression or any
11205/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011206///
11207/// \param SkipLocalVariables If true, don't mark local variables as
11208/// 'referenced'.
11209void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11210 bool SkipLocalVariables) {
11211 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011212}
11213
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011214/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11215/// of the program being compiled.
11216///
11217/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011218/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011219/// possibility that the code will actually be executable. Code in sizeof()
11220/// expressions, code used only during overload resolution, etc., are not
11221/// potentially evaluated. This routine will suppress such diagnostics or,
11222/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011223/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011224/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011225///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011226/// This routine should be used for all diagnostics that describe the run-time
11227/// behavior of a program, such as passing a non-POD value through an ellipsis.
11228/// Failure to do so will likely result in spurious diagnostics or failures
11229/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011230bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011231 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011232 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011233 case Unevaluated:
11234 // The argument will never be evaluated, so don't complain.
11235 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011236
Richard Smithf6702a32011-12-20 02:08:33 +000011237 case ConstantEvaluated:
11238 // Relevant diagnostics should be produced by constant evaluation.
11239 break;
11240
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011241 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011242 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011243 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011244 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011245 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011246 }
11247 else
11248 Diag(Loc, PD);
11249
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011250 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011251 }
11252
11253 return false;
11254}
11255
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011256bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11257 CallExpr *CE, FunctionDecl *FD) {
11258 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11259 return false;
11260
Richard Smith76f3f692012-02-22 02:04:18 +000011261 // If we're inside a decltype's expression, don't check for a valid return
11262 // type or construct temporaries until we know whether this is the last call.
11263 if (ExprEvalContexts.back().IsDecltype) {
11264 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11265 return false;
11266 }
11267
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011268 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011269 FunctionDecl *FD;
11270 CallExpr *CE;
11271
11272 public:
11273 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11274 : FD(FD), CE(CE) { }
11275
11276 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11277 if (!FD) {
11278 S.Diag(Loc, diag::err_call_incomplete_return)
11279 << T << CE->getSourceRange();
11280 return;
11281 }
11282
11283 S.Diag(Loc, diag::err_call_function_incomplete_return)
11284 << CE->getSourceRange() << FD->getDeclName() << T;
11285 S.Diag(FD->getLocation(),
11286 diag::note_function_with_incomplete_return_type_declared_here)
11287 << FD->getDeclName();
11288 }
11289 } Diagnoser(FD, CE);
11290
11291 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011292 return true;
11293
11294 return false;
11295}
11296
Douglas Gregor92c3a042011-01-19 16:50:08 +000011297// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011298// will prevent this condition from triggering, which is what we want.
11299void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11300 SourceLocation Loc;
11301
John McCalla52ef082009-11-11 02:41:58 +000011302 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011303 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011304
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011305 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011306 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011307 return;
11308
Douglas Gregor92c3a042011-01-19 16:50:08 +000011309 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11310
John McCallc8d8ac52009-11-12 00:06:05 +000011311 // Greylist some idioms by putting them into a warning subcategory.
11312 if (ObjCMessageExpr *ME
11313 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11314 Selector Sel = ME->getSelector();
11315
John McCallc8d8ac52009-11-12 00:06:05 +000011316 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011317 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011318 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11319
11320 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011321 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011322 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11323 }
John McCalla52ef082009-11-11 02:41:58 +000011324
John McCall5a881bb2009-10-12 21:59:07 +000011325 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011326 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011327 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011328 return;
11329
Douglas Gregor92c3a042011-01-19 16:50:08 +000011330 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011331 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011332 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11333 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11334 else {
John McCall5a881bb2009-10-12 21:59:07 +000011335 // Not an assignment.
11336 return;
11337 }
11338
Douglas Gregor55b38842010-04-14 16:09:52 +000011339 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011340
Daniel Dunbar96a00142012-03-09 18:35:03 +000011341 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011342 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11343 Diag(Loc, diag::note_condition_assign_silence)
11344 << FixItHint::CreateInsertion(Open, "(")
11345 << FixItHint::CreateInsertion(Close, ")");
11346
Douglas Gregor92c3a042011-01-19 16:50:08 +000011347 if (IsOrAssign)
11348 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11349 << FixItHint::CreateReplacement(Loc, "!=");
11350 else
11351 Diag(Loc, diag::note_condition_assign_to_comparison)
11352 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011353}
11354
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011355/// \brief Redundant parentheses over an equality comparison can indicate
11356/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011357void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011358 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011359 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011360 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11361 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011362 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011363 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011364 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011365
Richard Trieuccd891a2011-09-09 01:45:06 +000011366 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011367
11368 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011369 if (opE->getOpcode() == BO_EQ &&
11370 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11371 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011372 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011373
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011374 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011375 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011376 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011377 << FixItHint::CreateRemoval(ParenERange.getBegin())
11378 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011379 Diag(Loc, diag::note_equality_comparison_to_assign)
11380 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011381 }
11382}
11383
John Wiegley429bb272011-04-08 18:41:53 +000011384ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011385 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011386 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11387 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011388
John McCall864c0412011-04-26 20:42:42 +000011389 ExprResult result = CheckPlaceholderExpr(E);
11390 if (result.isInvalid()) return ExprError();
11391 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011392
John McCall864c0412011-04-26 20:42:42 +000011393 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011394 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011395 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11396
John Wiegley429bb272011-04-08 18:41:53 +000011397 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11398 if (ERes.isInvalid())
11399 return ExprError();
11400 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011401
11402 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011403 if (!T->isScalarType()) { // C99 6.8.4.1p1
11404 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11405 << T << E->getSourceRange();
11406 return ExprError();
11407 }
John McCall5a881bb2009-10-12 21:59:07 +000011408 }
11409
John Wiegley429bb272011-04-08 18:41:53 +000011410 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011411}
Douglas Gregor586596f2010-05-06 17:25:47 +000011412
John McCall60d7b3a2010-08-24 06:29:42 +000011413ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011414 Expr *SubExpr) {
11415 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011416 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011417
Richard Trieuccd891a2011-09-09 01:45:06 +000011418 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011419}
John McCall2a984ca2010-10-12 00:20:44 +000011420
John McCall1de4d4e2011-04-07 08:22:57 +000011421namespace {
John McCall755d8492011-04-12 00:42:48 +000011422 /// A visitor for rebuilding a call to an __unknown_any expression
11423 /// to have an appropriate type.
11424 struct RebuildUnknownAnyFunction
11425 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11426
11427 Sema &S;
11428
11429 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11430
11431 ExprResult VisitStmt(Stmt *S) {
11432 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011433 }
11434
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011435 ExprResult VisitExpr(Expr *E) {
11436 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11437 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011438 return ExprError();
11439 }
11440
11441 /// Rebuild an expression which simply semantically wraps another
11442 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011443 template <class T> ExprResult rebuildSugarExpr(T *E) {
11444 ExprResult SubResult = Visit(E->getSubExpr());
11445 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011446
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011447 Expr *SubExpr = SubResult.take();
11448 E->setSubExpr(SubExpr);
11449 E->setType(SubExpr->getType());
11450 E->setValueKind(SubExpr->getValueKind());
11451 assert(E->getObjectKind() == OK_Ordinary);
11452 return E;
John McCall755d8492011-04-12 00:42:48 +000011453 }
11454
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011455 ExprResult VisitParenExpr(ParenExpr *E) {
11456 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011457 }
11458
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011459 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11460 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011461 }
11462
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011463 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11464 ExprResult SubResult = Visit(E->getSubExpr());
11465 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011466
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011467 Expr *SubExpr = SubResult.take();
11468 E->setSubExpr(SubExpr);
11469 E->setType(S.Context.getPointerType(SubExpr->getType()));
11470 assert(E->getValueKind() == VK_RValue);
11471 assert(E->getObjectKind() == OK_Ordinary);
11472 return E;
John McCall755d8492011-04-12 00:42:48 +000011473 }
11474
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011475 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11476 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011477
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011478 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011479
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011480 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011481 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011482 !(isa<CXXMethodDecl>(VD) &&
11483 cast<CXXMethodDecl>(VD)->isInstance()))
11484 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011485
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011486 return E;
John McCall755d8492011-04-12 00:42:48 +000011487 }
11488
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011489 ExprResult VisitMemberExpr(MemberExpr *E) {
11490 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011491 }
11492
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011493 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11494 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011495 }
11496 };
11497}
11498
11499/// Given a function expression of unknown-any type, try to rebuild it
11500/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011501static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11502 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11503 if (Result.isInvalid()) return ExprError();
11504 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011505}
11506
11507namespace {
John McCall379b5152011-04-11 07:02:50 +000011508 /// A visitor for rebuilding an expression of type __unknown_anytype
11509 /// into one which resolves the type directly on the referring
11510 /// expression. Strict preservation of the original source
11511 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011512 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011513 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011514
11515 Sema &S;
11516
11517 /// The current destination type.
11518 QualType DestType;
11519
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011520 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11521 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011522
John McCalla5fc4722011-04-09 22:50:59 +000011523 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011524 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011525 }
11526
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011527 ExprResult VisitExpr(Expr *E) {
11528 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11529 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011530 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011531 }
11532
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011533 ExprResult VisitCallExpr(CallExpr *E);
11534 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011535
John McCalla5fc4722011-04-09 22:50:59 +000011536 /// Rebuild an expression which simply semantically wraps another
11537 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011538 template <class T> ExprResult rebuildSugarExpr(T *E) {
11539 ExprResult SubResult = Visit(E->getSubExpr());
11540 if (SubResult.isInvalid()) return ExprError();
11541 Expr *SubExpr = SubResult.take();
11542 E->setSubExpr(SubExpr);
11543 E->setType(SubExpr->getType());
11544 E->setValueKind(SubExpr->getValueKind());
11545 assert(E->getObjectKind() == OK_Ordinary);
11546 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011547 }
John McCall1de4d4e2011-04-07 08:22:57 +000011548
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011549 ExprResult VisitParenExpr(ParenExpr *E) {
11550 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011551 }
11552
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011553 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11554 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011555 }
11556
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011557 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11558 const PointerType *Ptr = DestType->getAs<PointerType>();
11559 if (!Ptr) {
11560 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11561 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011562 return ExprError();
11563 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011564 assert(E->getValueKind() == VK_RValue);
11565 assert(E->getObjectKind() == OK_Ordinary);
11566 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011567
11568 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011569 DestType = Ptr->getPointeeType();
11570 ExprResult SubResult = Visit(E->getSubExpr());
11571 if (SubResult.isInvalid()) return ExprError();
11572 E->setSubExpr(SubResult.take());
11573 return E;
John McCall755d8492011-04-12 00:42:48 +000011574 }
11575
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011576 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011577
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011578 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011579
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011580 ExprResult VisitMemberExpr(MemberExpr *E) {
11581 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011582 }
John McCalla5fc4722011-04-09 22:50:59 +000011583
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011584 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11585 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011586 }
11587 };
11588}
11589
John McCall379b5152011-04-11 07:02:50 +000011590/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011591ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11592 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011593
11594 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011595 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011596 FK_FunctionPointer,
11597 FK_BlockPointer
11598 };
11599
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011600 FnKind Kind;
11601 QualType CalleeType = CalleeExpr->getType();
11602 if (CalleeType == S.Context.BoundMemberTy) {
11603 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11604 Kind = FK_MemberFunction;
11605 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11606 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11607 CalleeType = Ptr->getPointeeType();
11608 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011609 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011610 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11611 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011612 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011613 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011614
11615 // Verify that this is a legal result type of a function.
11616 if (DestType->isArrayType() || DestType->isFunctionType()) {
11617 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011618 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011619 diagID = diag::err_block_returning_array_function;
11620
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011621 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011622 << DestType->isFunctionType() << DestType;
11623 return ExprError();
11624 }
11625
11626 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011627 E->setType(DestType.getNonLValueExprType(S.Context));
11628 E->setValueKind(Expr::getValueKindForType(DestType));
11629 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011630
11631 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011632 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011633 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011634 Proto->arg_type_begin(),
11635 Proto->getNumArgs(),
11636 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011637 else
11638 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011639 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011640
11641 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011642 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011643 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011644 // Nothing to do.
11645 break;
11646
11647 case FK_FunctionPointer:
11648 DestType = S.Context.getPointerType(DestType);
11649 break;
11650
11651 case FK_BlockPointer:
11652 DestType = S.Context.getBlockPointerType(DestType);
11653 break;
11654 }
11655
11656 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011657 ExprResult CalleeResult = Visit(CalleeExpr);
11658 if (!CalleeResult.isUsable()) return ExprError();
11659 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011660
11661 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011662 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011663}
11664
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011665ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011666 // Verify that this is a legal result type of a call.
11667 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011668 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011669 << DestType->isFunctionType() << DestType;
11670 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011671 }
11672
John McCall48218c62011-07-13 17:56:40 +000011673 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011674 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11675 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11676 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011677 }
John McCall755d8492011-04-12 00:42:48 +000011678
John McCall379b5152011-04-11 07:02:50 +000011679 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011680 E->setType(DestType.getNonReferenceType());
11681 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011682
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011683 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011684}
11685
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011686ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011687 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011688 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011689 assert(E->getValueKind() == VK_RValue);
11690 assert(E->getObjectKind() == OK_Ordinary);
11691
11692 E->setType(DestType);
11693
11694 // Rebuild the sub-expression as the pointee (function) type.
11695 DestType = DestType->castAs<PointerType>()->getPointeeType();
11696
11697 ExprResult Result = Visit(E->getSubExpr());
11698 if (!Result.isUsable()) return ExprError();
11699
11700 E->setSubExpr(Result.take());
11701 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011702 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011703 assert(E->getValueKind() == VK_RValue);
11704 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011705
Sean Callanance9c8312012-03-06 21:34:12 +000011706 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011707
Sean Callanance9c8312012-03-06 21:34:12 +000011708 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011709
Sean Callanance9c8312012-03-06 21:34:12 +000011710 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11711 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011712
Sean Callanance9c8312012-03-06 21:34:12 +000011713 ExprResult Result = Visit(E->getSubExpr());
11714 if (!Result.isUsable()) return ExprError();
11715
11716 E->setSubExpr(Result.take());
11717 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011718 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011719 llvm_unreachable("Unhandled cast type!");
11720 }
John McCall379b5152011-04-11 07:02:50 +000011721}
11722
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011723ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11724 ExprValueKind ValueKind = VK_LValue;
11725 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011726
11727 // We know how to make this work for certain kinds of decls:
11728
11729 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11731 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11732 DestType = Ptr->getPointeeType();
11733 ExprResult Result = resolveDecl(E, VD);
11734 if (Result.isInvalid()) return ExprError();
11735 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011736 CK_FunctionToPointerDecay, VK_RValue);
11737 }
11738
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011739 if (!Type->isFunctionType()) {
11740 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11741 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011742 return ExprError();
11743 }
John McCall379b5152011-04-11 07:02:50 +000011744
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011745 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11746 if (MD->isInstance()) {
11747 ValueKind = VK_RValue;
11748 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011749 }
11750
John McCall379b5152011-04-11 07:02:50 +000011751 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011752 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011753 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011754
11755 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011756 } else if (isa<VarDecl>(VD)) {
11757 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11758 Type = RefTy->getPointeeType();
11759 } else if (Type->isFunctionType()) {
11760 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11761 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011762 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011763 }
11764
11765 // - nothing else
11766 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011767 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11768 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011769 return ExprError();
11770 }
11771
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011772 VD->setType(DestType);
11773 E->setType(Type);
11774 E->setValueKind(ValueKind);
11775 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011776}
11777
John McCall1de4d4e2011-04-07 08:22:57 +000011778/// Check a cast of an unknown-any type. We intentionally only
11779/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011780ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11781 Expr *CastExpr, CastKind &CastKind,
11782 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011783 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011784 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011785 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011786
Richard Trieuccd891a2011-09-09 01:45:06 +000011787 CastExpr = result.take();
11788 VK = CastExpr->getValueKind();
11789 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011790
Richard Trieuccd891a2011-09-09 01:45:06 +000011791 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011792}
11793
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011794ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11795 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11796}
11797
Richard Trieuccd891a2011-09-09 01:45:06 +000011798static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11799 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011800 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011801 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011802 E = E->IgnoreParenImpCasts();
11803 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11804 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011805 diagID = diag::err_uncasted_call_of_unknown_any;
11806 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011807 break;
John McCall379b5152011-04-11 07:02:50 +000011808 }
John McCall1de4d4e2011-04-07 08:22:57 +000011809 }
11810
John McCall379b5152011-04-11 07:02:50 +000011811 SourceLocation loc;
11812 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011813 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011814 loc = ref->getLocation();
11815 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011816 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011817 loc = mem->getMemberLoc();
11818 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011819 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011820 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011821 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011822 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011823 if (!d) {
11824 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11825 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11826 << orig->getSourceRange();
11827 return ExprError();
11828 }
John McCall379b5152011-04-11 07:02:50 +000011829 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011830 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11831 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011832 return ExprError();
11833 }
11834
11835 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011836
11837 // Never recoverable.
11838 return ExprError();
11839}
11840
John McCall2a984ca2010-10-12 00:20:44 +000011841/// Check for operands with placeholder types and complain if found.
11842/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011843ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011844 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11845 if (!placeholderType) return Owned(E);
11846
11847 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011848
John McCall1de4d4e2011-04-07 08:22:57 +000011849 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011850 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011851 // Try to resolve a single function template specialization.
11852 // This is obligatory.
11853 ExprResult result = Owned(E);
11854 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11855 return result;
11856
11857 // If that failed, try to recover with a call.
11858 } else {
11859 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11860 /*complain*/ true);
11861 return result;
11862 }
11863 }
John McCall1de4d4e2011-04-07 08:22:57 +000011864
John McCall864c0412011-04-26 20:42:42 +000011865 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011866 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011867 ExprResult result = Owned(E);
11868 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11869 /*complain*/ true);
11870 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011871 }
11872
11873 // ARC unbridged casts.
11874 case BuiltinType::ARCUnbridgedCast: {
11875 Expr *realCast = stripARCUnbridgedCast(E);
11876 diagnoseARCUnbridgedCast(realCast);
11877 return Owned(realCast);
11878 }
John McCall864c0412011-04-26 20:42:42 +000011879
John McCall1de4d4e2011-04-07 08:22:57 +000011880 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011881 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011882 return diagnoseUnknownAnyExpr(*this, E);
11883
John McCall3c3b7f92011-10-25 17:37:35 +000011884 // Pseudo-objects.
11885 case BuiltinType::PseudoObject:
11886 return checkPseudoObjectRValue(E);
11887
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011888 case BuiltinType::BuiltinFn:
11889 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11890 return ExprError();
11891
John McCalle0a22d02011-10-18 21:02:43 +000011892 // Everything else should be impossible.
11893#define BUILTIN_TYPE(Id, SingletonId) \
11894 case BuiltinType::Id:
11895#define PLACEHOLDER_TYPE(Id, SingletonId)
11896#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011897 break;
11898 }
11899
11900 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011901}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011902
Richard Trieuccd891a2011-09-09 01:45:06 +000011903bool Sema::CheckCaseExpression(Expr *E) {
11904 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011905 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011906 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11907 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011908 return false;
11909}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011910
11911/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11912ExprResult
11913Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11914 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11915 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011916 QualType BoolT = Context.ObjCBuiltinBoolTy;
11917 if (!Context.getBOOLDecl()) {
11918 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11919 Sema::LookupOrdinaryName);
11920 if (LookupName(Result, getCurScope())) {
11921 NamedDecl *ND = Result.getFoundDecl();
11922 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11923 Context.setBOOLDecl(TD);
11924 }
11925 }
11926 if (Context.getBOOLDecl())
11927 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011928 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011929 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011930}