blob: e419ba5a3f01233e2beb387a0ffa6b6e8e5bcd5f [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,
Richard Smithefeeccf2012-10-21 03:28:35 +00001898 const DeclarationNameInfo &NameInfo,
1899 bool IsAddressOfOperand) {
Richard Smith713c2872012-10-23 19:56:01 +00001900 DeclContext *DC = computeDeclContext(SS, false);
1901 if (!DC)
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001902 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1903 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001904
John McCall77bb1aa2010-05-01 00:40:08 +00001905 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001906 return ExprError();
1907
Abramo Bagnara25777432010-08-11 22:01:17 +00001908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001909 LookupQualifiedName(R, DC);
1910
1911 if (R.isAmbiguous())
1912 return ExprError();
1913
Richard Smith713c2872012-10-23 19:56:01 +00001914 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1915 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1916 NameInfo, /*TemplateArgs=*/0);
1917
John McCallf7a1a742009-11-24 19:00:30 +00001918 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001919 Diag(NameInfo.getLoc(), diag::err_no_member)
1920 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001921 return ExprError();
1922 }
1923
Richard Smithefeeccf2012-10-21 03:28:35 +00001924 // Defend against this resolving to an implicit member access. We usually
1925 // won't get here if this might be a legitimate a class member (we end up in
1926 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1927 // a pointer-to-member or in an unevaluated context in C++11.
1928 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1929 return BuildPossibleImplicitMemberExpr(SS,
1930 /*TemplateKWLoc=*/SourceLocation(),
1931 R, /*TemplateArgs=*/0);
1932
1933 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00001934}
1935
1936/// LookupInObjCMethod - The parser has read a name in, and Sema has
1937/// detected that we're currently inside an ObjC method. Perform some
1938/// additional lookup.
1939///
1940/// Ideally, most of this would be done by lookup, but there's
1941/// actually quite a lot of extra work involved.
1942///
1943/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001944ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001945Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001946 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001947 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001948 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001949
John McCallf7a1a742009-11-24 19:00:30 +00001950 // There are two cases to handle here. 1) scoped lookup could have failed,
1951 // in which case we should look for an ivar. 2) scoped lookup could have
1952 // found a decl, but that decl is outside the current instance method (i.e.
1953 // a global variable). In these two cases, we do a lookup for an ivar with
1954 // this name, if the lookup sucedes, we replace it our current decl.
1955
1956 // If we're in a class method, we don't normally want to look for
1957 // ivars. But if we don't find anything else, and there's an
1958 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001959 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001960
1961 bool LookForIvars;
1962 if (Lookup.empty())
1963 LookForIvars = true;
1964 else if (IsClassMethod)
1965 LookForIvars = false;
1966 else
1967 LookForIvars = (Lookup.isSingleResult() &&
1968 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001969 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001970 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001971 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001972 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001973 ObjCIvarDecl *IV = 0;
1974 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001975 // Diagnose using an ivar in a class method.
1976 if (IsClassMethod)
1977 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1978 << IV->getDeclName());
1979
1980 // If we're referencing an invalid decl, just return this as a silent
1981 // error node. The error diagnostic was already emitted on the decl.
1982 if (IV->isInvalidDecl())
1983 return ExprError();
1984
1985 // Check if referencing a field with __attribute__((deprecated)).
1986 if (DiagnoseUseOfDecl(IV, Loc))
1987 return ExprError();
1988
1989 // Diagnose the use of an ivar outside of the declaring class.
1990 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001991 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001992 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001993 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1994
1995 // FIXME: This should use a new expr for a direct reference, don't
1996 // turn this into Self->ivar, just return a BareIVarExpr or something.
1997 IdentifierInfo &II = Context.Idents.get("self");
1998 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001999 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00002000 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00002001 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002002 SourceLocation TemplateKWLoc;
2003 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002004 SelfName, false, false);
2005 if (SelfExpr.isInvalid())
2006 return ExprError();
2007
John Wiegley429bb272011-04-08 18:41:53 +00002008 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2009 if (SelfExpr.isInvalid())
2010 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002011
Eli Friedman5f2987c2012-02-02 03:46:19 +00002012 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002013
2014 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2015 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2016 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002017
2018 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2019 Loc,
2020 SelfExpr.take(),
2021 true, true);
2022
2023 if (getLangOpts().ObjCAutoRefCount) {
2024 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2025 DiagnosticsEngine::Level Level =
2026 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2027 if (Level != DiagnosticsEngine::Ignored)
2028 getCurFunction()->recordUseOfWeak(Result);
2029 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002030 if (CurContext->isClosure())
2031 Diag(Loc, diag::warn_implicitly_retains_self)
2032 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002033 }
2034
2035 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002036 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002037 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002038 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002039 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2040 ObjCInterfaceDecl *ClassDeclared;
2041 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2042 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002043 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002044 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2045 }
John McCallf7a1a742009-11-24 19:00:30 +00002046 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002047 } else if (Lookup.isSingleResult() &&
2048 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2049 // If accessing a stand-alone ivar in a class method, this is an error.
2050 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2051 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2052 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002053 }
2054
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002055 if (Lookup.empty() && II && AllowBuiltinCreation) {
2056 // FIXME. Consolidate this with similar code in LookupName.
2057 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002058 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002059 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2060 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2061 S, Lookup.isForRedeclaration(),
2062 Lookup.getNameLoc());
2063 if (D) Lookup.addDecl(D);
2064 }
2065 }
2066 }
John McCallf7a1a742009-11-24 19:00:30 +00002067 // Sentinel value saying that we didn't do anything special.
2068 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002069}
John McCallba135432009-11-21 08:51:07 +00002070
John McCall6bb80172010-03-30 21:47:33 +00002071/// \brief Cast a base object to a member's actual type.
2072///
2073/// Logically this happens in three phases:
2074///
2075/// * First we cast from the base type to the naming class.
2076/// The naming class is the class into which we were looking
2077/// when we found the member; it's the qualifier type if a
2078/// qualifier was provided, and otherwise it's the base type.
2079///
2080/// * Next we cast from the naming class to the declaring class.
2081/// If the member we found was brought into a class's scope by
2082/// a using declaration, this is that class; otherwise it's
2083/// the class declaring the member.
2084///
2085/// * Finally we cast from the declaring class to the "true"
2086/// declaring class of the member. This conversion does not
2087/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002088ExprResult
2089Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002090 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002091 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002092 NamedDecl *Member) {
2093 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2094 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002095 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002096
Douglas Gregor5fccd362010-03-03 23:55:11 +00002097 QualType DestRecordType;
2098 QualType DestType;
2099 QualType FromRecordType;
2100 QualType FromType = From->getType();
2101 bool PointerConversions = false;
2102 if (isa<FieldDecl>(Member)) {
2103 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002104
Douglas Gregor5fccd362010-03-03 23:55:11 +00002105 if (FromType->getAs<PointerType>()) {
2106 DestType = Context.getPointerType(DestRecordType);
2107 FromRecordType = FromType->getPointeeType();
2108 PointerConversions = true;
2109 } else {
2110 DestType = DestRecordType;
2111 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002112 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002113 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2114 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002115 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002116
Douglas Gregor5fccd362010-03-03 23:55:11 +00002117 DestType = Method->getThisType(Context);
2118 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002119
Douglas Gregor5fccd362010-03-03 23:55:11 +00002120 if (FromType->getAs<PointerType>()) {
2121 FromRecordType = FromType->getPointeeType();
2122 PointerConversions = true;
2123 } else {
2124 FromRecordType = FromType;
2125 DestType = DestRecordType;
2126 }
2127 } else {
2128 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002129 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002130 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002131
Douglas Gregor5fccd362010-03-03 23:55:11 +00002132 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002133 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002134
Douglas Gregor5fccd362010-03-03 23:55:11 +00002135 // If the unqualified types are the same, no conversion is necessary.
2136 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002137 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002138
John McCall6bb80172010-03-30 21:47:33 +00002139 SourceRange FromRange = From->getSourceRange();
2140 SourceLocation FromLoc = FromRange.getBegin();
2141
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002142 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002143
Douglas Gregor5fccd362010-03-03 23:55:11 +00002144 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002145 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002146 // class name.
2147 //
2148 // If the member was a qualified name and the qualified referred to a
2149 // specific base subobject type, we'll cast to that intermediate type
2150 // first and then to the object in which the member is declared. That allows
2151 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2152 //
2153 // class Base { public: int x; };
2154 // class Derived1 : public Base { };
2155 // class Derived2 : public Base { };
2156 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2157 //
2158 // void VeryDerived::f() {
2159 // x = 17; // error: ambiguous base subobjects
2160 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2161 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002162 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002163 QualType QType = QualType(Qualifier->getAsType(), 0);
2164 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2165 assert(QType->isRecordType() && "lookup done with non-record type");
2166
2167 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2168
2169 // In C++98, the qualifier type doesn't actually have to be a base
2170 // type of the object type, in which case we just ignore it.
2171 // Otherwise build the appropriate casts.
2172 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002173 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002174 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002175 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002176 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002177
Douglas Gregor5fccd362010-03-03 23:55:11 +00002178 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002179 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002180 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2181 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002182
2183 FromType = QType;
2184 FromRecordType = QRecordType;
2185
2186 // If the qualifier type was the same as the destination type,
2187 // we're done.
2188 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002189 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002190 }
2191 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002192
John McCall6bb80172010-03-30 21:47:33 +00002193 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002194
John McCall6bb80172010-03-30 21:47:33 +00002195 // If we actually found the member through a using declaration, cast
2196 // down to the using declaration's type.
2197 //
2198 // Pointer equality is fine here because only one declaration of a
2199 // class ever has member declarations.
2200 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2201 assert(isa<UsingShadowDecl>(FoundDecl));
2202 QualType URecordType = Context.getTypeDeclType(
2203 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2204
2205 // We only need to do this if the naming-class to declaring-class
2206 // conversion is non-trivial.
2207 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2208 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002209 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002210 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002211 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002212 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002213
John McCall6bb80172010-03-30 21:47:33 +00002214 QualType UType = URecordType;
2215 if (PointerConversions)
2216 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002217 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2218 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002219 FromType = UType;
2220 FromRecordType = URecordType;
2221 }
2222
2223 // We don't do access control for the conversion from the
2224 // declaring class to the true declaring class.
2225 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002226 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002227
John McCallf871d0c2010-08-07 06:22:56 +00002228 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002229 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2230 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002231 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002232 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002233
John Wiegley429bb272011-04-08 18:41:53 +00002234 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2235 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002236}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002237
John McCallf7a1a742009-11-24 19:00:30 +00002238bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002239 const LookupResult &R,
2240 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002241 // Only when used directly as the postfix-expression of a call.
2242 if (!HasTrailingLParen)
2243 return false;
2244
2245 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002246 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002247 return false;
2248
2249 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002250 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002251 return false;
2252
2253 // Turn off ADL when we find certain kinds of declarations during
2254 // normal lookup:
2255 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2256 NamedDecl *D = *I;
2257
2258 // C++0x [basic.lookup.argdep]p3:
2259 // -- a declaration of a class member
2260 // Since using decls preserve this property, we check this on the
2261 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002262 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002263 return false;
2264
2265 // C++0x [basic.lookup.argdep]p3:
2266 // -- a block-scope function declaration that is not a
2267 // using-declaration
2268 // NOTE: we also trigger this for function templates (in fact, we
2269 // don't check the decl type at all, since all other decl types
2270 // turn off ADL anyway).
2271 if (isa<UsingShadowDecl>(D))
2272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2273 else if (D->getDeclContext()->isFunctionOrMethod())
2274 return false;
2275
2276 // C++0x [basic.lookup.argdep]p3:
2277 // -- a declaration that is neither a function or a function
2278 // template
2279 // And also for builtin functions.
2280 if (isa<FunctionDecl>(D)) {
2281 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2282
2283 // But also builtin functions.
2284 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2285 return false;
2286 } else if (!isa<FunctionTemplateDecl>(D))
2287 return false;
2288 }
2289
2290 return true;
2291}
2292
2293
John McCallba135432009-11-21 08:51:07 +00002294/// Diagnoses obvious problems with the use of the given declaration
2295/// as an expression. This is only actually called for lookups that
2296/// were not overloaded, and it doesn't promise that the declaration
2297/// will in fact be used.
2298static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002299 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002300 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2301 return true;
2302 }
2303
2304 if (isa<ObjCInterfaceDecl>(D)) {
2305 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2306 return true;
2307 }
2308
2309 if (isa<NamespaceDecl>(D)) {
2310 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2311 return true;
2312 }
2313
2314 return false;
2315}
2316
John McCall60d7b3a2010-08-24 06:29:42 +00002317ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002318Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002319 LookupResult &R,
2320 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002321 // If this is a single, fully-resolved result and we don't need ADL,
2322 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002323 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002324 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2325 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002326
2327 // We only need to check the declaration if there's exactly one
2328 // result, because in the overloaded case the results can only be
2329 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002330 if (R.isSingleResult() &&
2331 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002332 return ExprError();
2333
John McCallc373d482010-01-27 01:50:18 +00002334 // Otherwise, just build an unresolved lookup expression. Suppress
2335 // any lookup-related diagnostics; we'll hash these out later, when
2336 // we've picked a target.
2337 R.suppressDiagnostics();
2338
John McCallba135432009-11-21 08:51:07 +00002339 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002340 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002341 SS.getWithLocInContext(Context),
2342 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002343 NeedsADL, R.isOverloadedResult(),
2344 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002345
2346 return Owned(ULE);
2347}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002348
John McCallba135432009-11-21 08:51:07 +00002349/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002350ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002351Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002352 const DeclarationNameInfo &NameInfo,
2353 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002354 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002355 assert(!isa<FunctionTemplateDecl>(D) &&
2356 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002357
Abramo Bagnara25777432010-08-11 22:01:17 +00002358 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002359 if (CheckDeclInExpr(*this, Loc, D))
2360 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002361
Douglas Gregor9af2f522009-12-01 16:58:18 +00002362 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2363 // Specifically diagnose references to class templates that are missing
2364 // a template argument list.
2365 Diag(Loc, diag::err_template_decl_ref)
2366 << Template << SS.getRange();
2367 Diag(Template->getLocation(), diag::note_template_decl_here);
2368 return ExprError();
2369 }
2370
2371 // Make sure that we're referring to a value.
2372 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2373 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002374 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002375 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002376 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002377 return ExprError();
2378 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002379
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002380 // Check whether this declaration can be used. Note that we suppress
2381 // this check when we're going to perform argument-dependent lookup
2382 // on this function name, because this might not be the function
2383 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002384 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002385 return ExprError();
2386
Steve Naroffdd972f22008-09-05 22:11:13 +00002387 // Only create DeclRefExpr's for valid Decl's.
2388 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002389 return ExprError();
2390
John McCall5808ce42011-02-03 08:15:49 +00002391 // Handle members of anonymous structs and unions. If we got here,
2392 // and the reference is to a class member indirect field, then this
2393 // must be the subject of a pointer-to-member expression.
2394 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2395 if (!indirectField->isCXXClassMember())
2396 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2397 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002398
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002399 {
John McCall76a40212011-02-09 01:13:10 +00002400 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002401 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002402
2403 switch (D->getKind()) {
2404 // Ignore all the non-ValueDecl kinds.
2405#define ABSTRACT_DECL(kind)
2406#define VALUE(type, base)
2407#define DECL(type, base) \
2408 case Decl::type:
2409#include "clang/AST/DeclNodes.inc"
2410 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002411
2412 // These shouldn't make it here.
2413 case Decl::ObjCAtDefsField:
2414 case Decl::ObjCIvar:
2415 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002416
2417 // Enum constants are always r-values and never references.
2418 // Unresolved using declarations are dependent.
2419 case Decl::EnumConstant:
2420 case Decl::UnresolvedUsingValue:
2421 valueKind = VK_RValue;
2422 break;
2423
2424 // Fields and indirect fields that got here must be for
2425 // pointer-to-member expressions; we just call them l-values for
2426 // internal consistency, because this subexpression doesn't really
2427 // exist in the high-level semantics.
2428 case Decl::Field:
2429 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002430 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002431 "building reference to field in C?");
2432
2433 // These can't have reference type in well-formed programs, but
2434 // for internal consistency we do this anyway.
2435 type = type.getNonReferenceType();
2436 valueKind = VK_LValue;
2437 break;
2438
2439 // Non-type template parameters are either l-values or r-values
2440 // depending on the type.
2441 case Decl::NonTypeTemplateParm: {
2442 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2443 type = reftype->getPointeeType();
2444 valueKind = VK_LValue; // even if the parameter is an r-value reference
2445 break;
2446 }
2447
2448 // For non-references, we need to strip qualifiers just in case
2449 // the template parameter was declared as 'const int' or whatever.
2450 valueKind = VK_RValue;
2451 type = type.getUnqualifiedType();
2452 break;
2453 }
2454
2455 case Decl::Var:
2456 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002457 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002458 !type.hasQualifiers() &&
2459 type->isVoidType()) {
2460 valueKind = VK_RValue;
2461 break;
2462 }
2463 // fallthrough
2464
2465 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002466 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002467 // These are always l-values.
2468 valueKind = VK_LValue;
2469 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002470
Douglas Gregor68932842012-02-18 05:51:20 +00002471 // FIXME: Does the addition of const really only apply in
2472 // potentially-evaluated contexts? Since the variable isn't actually
2473 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002474 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002475 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2476 if (!CapturedType.isNull())
2477 type = CapturedType;
2478 }
2479
John McCall76a40212011-02-09 01:13:10 +00002480 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002481 }
2482
John McCall76a40212011-02-09 01:13:10 +00002483 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002484 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2485 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2486 type = Context.BuiltinFnTy;
2487 valueKind = VK_RValue;
2488 break;
2489 }
2490 }
2491
John McCall755d8492011-04-12 00:42:48 +00002492 const FunctionType *fty = type->castAs<FunctionType>();
2493
2494 // If we're referring to a function with an __unknown_anytype
2495 // result type, make the entire expression __unknown_anytype.
2496 if (fty->getResultType() == Context.UnknownAnyTy) {
2497 type = Context.UnknownAnyTy;
2498 valueKind = VK_RValue;
2499 break;
2500 }
2501
John McCall76a40212011-02-09 01:13:10 +00002502 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002503 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002504 valueKind = VK_LValue;
2505 break;
2506 }
2507
2508 // C99 DR 316 says that, if a function type comes from a
2509 // function definition (without a prototype), that type is only
2510 // used for checking compatibility. Therefore, when referencing
2511 // the function, we pretend that we don't have the full function
2512 // type.
John McCall755d8492011-04-12 00:42:48 +00002513 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2514 isa<FunctionProtoType>(fty))
2515 type = Context.getFunctionNoProtoType(fty->getResultType(),
2516 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002517
2518 // Functions are r-values in C.
2519 valueKind = VK_RValue;
2520 break;
2521 }
2522
2523 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002524 // If we're referring to a method with an __unknown_anytype
2525 // result type, make the entire expression __unknown_anytype.
2526 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002527 if (const FunctionProtoType *proto
2528 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002529 if (proto->getResultType() == Context.UnknownAnyTy) {
2530 type = Context.UnknownAnyTy;
2531 valueKind = VK_RValue;
2532 break;
2533 }
2534
John McCall76a40212011-02-09 01:13:10 +00002535 // C++ methods are l-values if static, r-values if non-static.
2536 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2537 valueKind = VK_LValue;
2538 break;
2539 }
2540 // fallthrough
2541
2542 case Decl::CXXConversion:
2543 case Decl::CXXDestructor:
2544 case Decl::CXXConstructor:
2545 valueKind = VK_RValue;
2546 break;
2547 }
2548
2549 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2550 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002551}
2552
John McCall755d8492011-04-12 00:42:48 +00002553ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002554 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002555
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002557 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002558 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2559 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002560 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002561 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002563
Chris Lattnerfa28b302008-01-12 08:14:25 +00002564 // Pre-defined identifiers are of type char[x], where x is the length of the
2565 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Anders Carlsson3a082d82009-09-08 18:24:21 +00002567 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002568 if (!currentDecl && getCurBlock())
2569 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002570 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002571 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002572 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002573 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002574
Anders Carlsson773f3972009-09-11 01:22:35 +00002575 QualType ResTy;
2576 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2577 ResTy = Context.DependentTy;
2578 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002579 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580
Anders Carlsson773f3972009-09-11 01:22:35 +00002581 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002582 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002583 ResTy = Context.WCharTy.withConst();
2584 else
2585 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002586 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2587 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002588 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002589}
2590
Richard Smith36f5cfe2012-03-09 08:00:36 +00002591ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002592 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002593 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002594 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002595 if (Invalid)
2596 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002597
Benjamin Kramerddeea562010-02-27 13:44:12 +00002598 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002599 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002601 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002602
Chris Lattnere8337df2009-12-30 21:19:39 +00002603 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002604 if (Literal.isWide())
2605 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002606 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002607 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002608 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002609 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002610 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002611 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002612 else
2613 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002614
Douglas Gregor5cee1192011-07-27 05:40:30 +00002615 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2616 if (Literal.isWide())
2617 Kind = CharacterLiteral::Wide;
2618 else if (Literal.isUTF16())
2619 Kind = CharacterLiteral::UTF16;
2620 else if (Literal.isUTF32())
2621 Kind = CharacterLiteral::UTF32;
2622
Richard Smithdd66be72012-03-08 01:34:56 +00002623 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2624 Tok.getLocation());
2625
2626 if (Literal.getUDSuffix().empty())
2627 return Owned(Lit);
2628
2629 // We're building a user-defined literal.
2630 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2631 SourceLocation UDSuffixLoc =
2632 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2633
Richard Smith36f5cfe2012-03-09 08:00:36 +00002634 // Make sure we're allowed user-defined literals here.
2635 if (!UDLScope)
2636 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2637
Richard Smithdd66be72012-03-08 01:34:56 +00002638 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2639 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002640 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2641 llvm::makeArrayRef(&Lit, 1),
2642 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002643}
2644
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002645ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2646 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2647 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2648 Context.IntTy, Loc));
2649}
2650
Richard Smithb453ad32012-03-08 08:45:32 +00002651static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2652 QualType Ty, SourceLocation Loc) {
2653 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2654
2655 using llvm::APFloat;
2656 APFloat Val(Format);
2657
2658 APFloat::opStatus result = Literal.GetFloatValue(Val);
2659
2660 // Overflow is always an error, but underflow is only an error if
2661 // we underflowed to zero (APFloat reports denormals as underflow).
2662 if ((result & APFloat::opOverflow) ||
2663 ((result & APFloat::opUnderflow) && Val.isZero())) {
2664 unsigned diagnostic;
2665 SmallString<20> buffer;
2666 if (result & APFloat::opOverflow) {
2667 diagnostic = diag::warn_float_overflow;
2668 APFloat::getLargest(Format).toString(buffer);
2669 } else {
2670 diagnostic = diag::warn_float_underflow;
2671 APFloat::getSmallest(Format).toString(buffer);
2672 }
2673
2674 S.Diag(Loc, diagnostic)
2675 << Ty
2676 << StringRef(buffer.data(), buffer.size());
2677 }
2678
2679 bool isExact = (result == APFloat::opOK);
2680 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2681}
2682
Richard Smith36f5cfe2012-03-09 08:00:36 +00002683ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002684 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002685 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002687 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002688 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 }
Ted Kremenek28396602009-01-13 23:19:12 +00002690
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002691 SmallString<128> SpellingBuffer;
2692 // NumericLiteralParser wants to overread by one character. Add padding to
2693 // the buffer in case the token is copied to the buffer. If getSpelling()
2694 // returns a StringRef to the memory buffer, it should have a null char at
2695 // the EOF, so it is also safe.
2696 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002697
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002699 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002700 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002701 if (Invalid)
2702 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002703
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002704 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002706 return ExprError();
2707
Richard Smithb453ad32012-03-08 08:45:32 +00002708 if (Literal.hasUDSuffix()) {
2709 // We're building a user-defined literal.
2710 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2711 SourceLocation UDSuffixLoc =
2712 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2713
Richard Smith36f5cfe2012-03-09 08:00:36 +00002714 // Make sure we're allowed user-defined literals here.
2715 if (!UDLScope)
2716 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002717
Richard Smith36f5cfe2012-03-09 08:00:36 +00002718 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002719 if (Literal.isFloatingLiteral()) {
2720 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2721 // long double, the literal is treated as a call of the form
2722 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002723 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002724 } else {
2725 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2726 // unsigned long long, the literal is treated as a call of the form
2727 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002728 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002729 }
2730
Richard Smith36f5cfe2012-03-09 08:00:36 +00002731 DeclarationName OpName =
2732 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2733 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2734 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2735
2736 // Perform literal operator lookup to determine if we're building a raw
2737 // literal or a cooked one.
2738 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2739 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2740 /*AllowRawAndTemplate*/true)) {
2741 case LOLR_Error:
2742 return ExprError();
2743
2744 case LOLR_Cooked: {
2745 Expr *Lit;
2746 if (Literal.isFloatingLiteral()) {
2747 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2748 } else {
2749 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2750 if (Literal.GetIntegerValue(ResultVal))
2751 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2752 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2753 Tok.getLocation());
2754 }
2755 return BuildLiteralOperatorCall(R, OpNameInfo,
2756 llvm::makeArrayRef(&Lit, 1),
2757 Tok.getLocation());
2758 }
2759
2760 case LOLR_Raw: {
2761 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2762 // literal is treated as a call of the form
2763 // operator "" X ("n")
2764 SourceLocation TokLoc = Tok.getLocation();
2765 unsigned Length = Literal.getUDSuffixOffset();
2766 QualType StrTy = Context.getConstantArrayType(
2767 Context.CharTy, llvm::APInt(32, Length + 1),
2768 ArrayType::Normal, 0);
2769 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002770 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002771 /*Pascal*/false, StrTy, &TokLoc, 1);
2772 return BuildLiteralOperatorCall(R, OpNameInfo,
2773 llvm::makeArrayRef(&Lit, 1), TokLoc);
2774 }
2775
2776 case LOLR_Template:
2777 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2778 // template), L is treated as a call fo the form
2779 // operator "" X <'c1', 'c2', ... 'ck'>()
2780 // where n is the source character sequence c1 c2 ... ck.
2781 TemplateArgumentListInfo ExplicitArgs;
2782 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2783 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2784 llvm::APSInt Value(CharBits, CharIsUnsigned);
2785 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002786 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002787 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002788 TemplateArgumentLocInfo ArgInfo;
2789 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2790 }
2791 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2792 Tok.getLocation(), &ExplicitArgs);
2793 }
2794
2795 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002796 }
2797
Chris Lattner5d661452007-08-26 03:42:43 +00002798 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002799
Chris Lattner5d661452007-08-26 03:42:43 +00002800 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002801 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002802 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002803 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002804 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002805 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002806 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002807 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002808
Richard Smithb453ad32012-03-08 08:45:32 +00002809 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002810
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002811 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002812 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002813 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002814 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002815 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002816 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002817 }
2818 }
Chris Lattner5d661452007-08-26 03:42:43 +00002819 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002820 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002821 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002822 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002823
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002824 // 'long long' is a C99 or C++11 feature.
2825 if (!getLangOpts().C99 && Literal.isLongLong) {
2826 if (getLangOpts().CPlusPlus)
2827 Diag(Tok.getLocation(),
2828 getLangOpts().CPlusPlus0x ?
2829 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2830 else
2831 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2832 }
Neil Boothb9449512007-08-29 22:00:19 +00002833
Reid Spencer5f016e22007-07-11 17:01:13 +00002834 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002835 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2836 // The microsoft literal suffix extensions support 128-bit literals, which
2837 // may be wider than [u]intmax_t.
2838 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2839 MaxWidth = 128;
2840 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002841
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 if (Literal.GetIntegerValue(ResultVal)) {
2843 // If this value didn't fit into uintmax_t, warn and force to ull.
2844 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002845 Ty = Context.UnsignedLongLongTy;
2846 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002847 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 } else {
2849 // If this value fits into a ULL, try to figure out what else it fits into
2850 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002851
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2853 // be an unsigned int.
2854 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2855
2856 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002857 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002858 if (!Literal.isLong && !Literal.isLongLong) {
2859 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002860 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002861
Reid Spencer5f016e22007-07-11 17:01:13 +00002862 // Does it fit in a unsigned int?
2863 if (ResultVal.isIntN(IntSize)) {
2864 // Does it fit in a signed int?
2865 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002866 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002868 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002869 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002872
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002874 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002875 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002876
Reid Spencer5f016e22007-07-11 17:01:13 +00002877 // Does it fit in a unsigned long?
2878 if (ResultVal.isIntN(LongSize)) {
2879 // Does it fit in a signed long?
2880 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002881 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002883 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002884 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002886 }
2887
Stephen Canonb9e05f12012-05-03 22:49:43 +00002888 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002889 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002890 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002891
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 // Does it fit in a unsigned long long?
2893 if (ResultVal.isIntN(LongLongSize)) {
2894 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002895 // To be compatible with MSVC, hex integer literals ending with the
2896 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002897 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002898 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002899 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002901 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002902 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 }
2904 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002905
2906 // If it doesn't fit in unsigned long long, and we're using Microsoft
2907 // extensions, then its a 128-bit integer literal.
2908 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2909 if (Literal.isUnsigned)
2910 Ty = Context.UnsignedInt128Ty;
2911 else
2912 Ty = Context.Int128Ty;
2913 Width = 128;
2914 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002915
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 // If we still couldn't decide a type, we probably have something that
2917 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002918 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002920 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002921 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002923
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002924 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002925 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002926 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002927 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002929
Chris Lattner5d661452007-08-26 03:42:43 +00002930 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2931 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002932 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002933 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002934
2935 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002936}
2937
Richard Trieuccd891a2011-09-09 01:45:06 +00002938ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002939 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002940 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002941}
2942
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002943static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2944 SourceLocation Loc,
2945 SourceRange ArgRange) {
2946 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2947 // scalar or vector data type argument..."
2948 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2949 // type (C99 6.2.5p18) or void.
2950 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2951 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2952 << T << ArgRange;
2953 return true;
2954 }
2955
2956 assert((T->isVoidType() || !T->isIncompleteType()) &&
2957 "Scalar types should always be complete");
2958 return false;
2959}
2960
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002961static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2962 SourceLocation Loc,
2963 SourceRange ArgRange,
2964 UnaryExprOrTypeTrait TraitKind) {
2965 // C99 6.5.3.4p1:
2966 if (T->isFunctionType()) {
2967 // alignof(function) is allowed as an extension.
2968 if (TraitKind == UETT_SizeOf)
2969 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2970 return false;
2971 }
2972
2973 // Allow sizeof(void)/alignof(void) as an extension.
2974 if (T->isVoidType()) {
2975 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2976 return false;
2977 }
2978
2979 return true;
2980}
2981
2982static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2983 SourceLocation Loc,
2984 SourceRange ArgRange,
2985 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002986 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2987 // runtime doesn't allow it.
2988 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002989 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2990 << T << (TraitKind == UETT_SizeOf)
2991 << ArgRange;
2992 return true;
2993 }
2994
2995 return false;
2996}
2997
Chandler Carruth9d342d02011-05-26 08:53:10 +00002998/// \brief Check the constrains on expression operands to unary type expression
2999/// and type traits.
3000///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003001/// Completes any types necessary and validates the constraints on the operand
3002/// expression. The logic mostly mirrors the type-based overload, but may modify
3003/// the expression as it completes the type for that expression through template
3004/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003005bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003006 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003007 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003008
3009 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3010 // the result is the size of the referenced type."
3011 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3012 // result shall be the alignment of the referenced type."
3013 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3014 ExprTy = Ref->getPointeeType();
3015
3016 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003017 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3018 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003019
3020 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003021 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3022 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003023 return false;
3024
Richard Trieuccd891a2011-09-09 01:45:06 +00003025 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003026 diag::err_sizeof_alignof_incomplete_type,
3027 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003028 return true;
3029
3030 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003031 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003032 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3033 ExprTy = Ref->getPointeeType();
3034
Richard Trieuccd891a2011-09-09 01:45:06 +00003035 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3036 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003037 return true;
3038
Nico Webercf739922011-06-15 02:47:03 +00003039 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003040 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003041 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3042 QualType OType = PVD->getOriginalType();
3043 QualType Type = PVD->getType();
3044 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003045 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003046 << Type << OType;
3047 Diag(PVD->getLocation(), diag::note_declared_at);
3048 }
3049 }
3050 }
3051 }
3052
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003053 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003054}
3055
3056/// \brief Check the constraints on operands to unary expression and type
3057/// traits.
3058///
3059/// This will complete any types necessary, and validate the various constraints
3060/// on those operands.
3061///
Reid Spencer5f016e22007-07-11 17:01:13 +00003062/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003063/// C99 6.3.2.1p[2-4] all state:
3064/// Except when it is the operand of the sizeof operator ...
3065///
3066/// C++ [expr.sizeof]p4
3067/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3068/// standard conversions are not applied to the operand of sizeof.
3069///
3070/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003071bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003072 SourceLocation OpLoc,
3073 SourceRange ExprRange,
3074 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003075 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003076 return false;
3077
Sebastian Redl5d484e82009-11-23 17:18:46 +00003078 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3079 // the result is the size of the referenced type."
3080 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3081 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003082 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3083 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003084
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003085 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003086 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003087
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003088 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003089 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003090 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003091 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Richard Trieuccd891a2011-09-09 01:45:06 +00003093 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003094 diag::err_sizeof_alignof_incomplete_type,
3095 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003096 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Richard Trieuccd891a2011-09-09 01:45:06 +00003098 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003099 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003100 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Chris Lattner1efaa952009-04-24 00:30:45 +00003102 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003103}
3104
Chandler Carruth9d342d02011-05-26 08:53:10 +00003105static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003106 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003107
Mike Stump1eb44332009-09-09 15:08:12 +00003108 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003109 if (isa<DeclRefExpr>(E))
3110 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003111
3112 // Cannot know anything else if the expression is dependent.
3113 if (E->isTypeDependent())
3114 return false;
3115
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003116 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003117 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3118 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003119 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003120 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003121
3122 // Alignment of a field access is always okay, so long as it isn't a
3123 // bit-field.
3124 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003125 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003126 return false;
3127
Chandler Carruth9d342d02011-05-26 08:53:10 +00003128 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129}
3130
Chandler Carruth9d342d02011-05-26 08:53:10 +00003131bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003132 E = E->IgnoreParens();
3133
3134 // Cannot know anything else if the expression is dependent.
3135 if (E->isTypeDependent())
3136 return false;
3137
Chandler Carruth9d342d02011-05-26 08:53:10 +00003138 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003139}
3140
Douglas Gregorba498172009-03-13 21:01:28 +00003141/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003142ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003143Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3144 SourceLocation OpLoc,
3145 UnaryExprOrTypeTrait ExprKind,
3146 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003147 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003148 return ExprError();
3149
John McCalla93c9342009-12-07 02:54:59 +00003150 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003151
Douglas Gregorba498172009-03-13 21:01:28 +00003152 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003153 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003154 return ExprError();
3155
3156 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003157 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3158 Context.getSizeType(),
3159 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003160}
3161
3162/// \brief Build a sizeof or alignof expression given an expression
3163/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003164ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003165Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3166 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003167 ExprResult PE = CheckPlaceholderExpr(E);
3168 if (PE.isInvalid())
3169 return ExprError();
3170
3171 E = PE.get();
3172
Douglas Gregorba498172009-03-13 21:01:28 +00003173 // Verify that the operand is valid.
3174 bool isInvalid = false;
3175 if (E->isTypeDependent()) {
3176 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003177 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003178 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003179 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003180 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003181 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003182 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003183 isInvalid = true;
3184 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003185 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003186 }
3187
3188 if (isInvalid)
3189 return ExprError();
3190
Eli Friedman71b8fb52012-01-21 01:01:51 +00003191 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Krameraccaf192012-11-14 15:08:31 +00003192 PE = TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +00003193 if (PE.isInvalid()) return ExprError();
3194 E = PE.take();
3195 }
3196
Douglas Gregorba498172009-03-13 21:01:28 +00003197 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003198 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003199 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003200 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003201}
3202
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003203/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3204/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003205/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003206ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003207Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003208 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003209 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003211 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003212
Richard Trieuccd891a2011-09-09 01:45:06 +00003213 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003214 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003215 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003216 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003217 }
Sebastian Redl05189992008-11-11 17:56:53 +00003218
Douglas Gregorba498172009-03-13 21:01:28 +00003219 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003220 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003221 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003222}
3223
John Wiegley429bb272011-04-08 18:41:53 +00003224static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003225 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003226 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003227 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003228
John McCallf6a16482010-12-04 03:47:34 +00003229 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003230 if (V.get()->getObjectKind() != OK_Ordinary) {
3231 V = S.DefaultLvalueConversion(V.take());
3232 if (V.isInvalid())
3233 return QualType();
3234 }
John McCallf6a16482010-12-04 03:47:34 +00003235
Chris Lattnercc26ed72007-08-26 05:39:26 +00003236 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003237 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003238 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Chris Lattnercc26ed72007-08-26 05:39:26 +00003240 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003241 if (V.get()->getType()->isArithmeticType())
3242 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003243
John McCall2cd11fe2010-10-12 02:09:17 +00003244 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003245 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003246 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003247 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003248 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003249 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003250 }
3251
Chris Lattnercc26ed72007-08-26 05:39:26 +00003252 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003253 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003254 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003255 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003256}
3257
3258
Reid Spencer5f016e22007-07-11 17:01:13 +00003259
John McCall60d7b3a2010-08-24 06:29:42 +00003260ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003261Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003262 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003263 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003265 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003266 case tok::plusplus: Opc = UO_PostInc; break;
3267 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003268 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003269
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003270 // Since this might is a postfix expression, get rid of ParenListExprs.
3271 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3272 if (Result.isInvalid()) return ExprError();
3273 Input = Result.take();
3274
John McCall9ae2f072010-08-23 23:25:46 +00003275 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003276}
3277
John McCall1503f0d2012-07-31 05:14:30 +00003278/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3279///
3280/// \return true on error
3281static bool checkArithmeticOnObjCPointer(Sema &S,
3282 SourceLocation opLoc,
3283 Expr *op) {
3284 assert(op->getType()->isObjCObjectPointerType());
3285 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3286 return false;
3287
3288 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3289 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3290 << op->getSourceRange();
3291 return true;
3292}
3293
John McCall60d7b3a2010-08-24 06:29:42 +00003294ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003295Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3296 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003297 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003298 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003299 if (Result.isInvalid()) return ExprError();
3300 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003301
John McCall9ae2f072010-08-23 23:25:46 +00003302 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003303
David Blaikie4e4d0842012-03-11 07:00:24 +00003304 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003305 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003306 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003307 Context.DependentTy,
3308 VK_LValue, OK_Ordinary,
3309 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003310 }
3311
David Blaikie4e4d0842012-03-11 07:00:24 +00003312 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003313 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003314 LHSExp->getType()->isEnumeralType() ||
3315 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003316 RHSExp->getType()->isEnumeralType()) &&
3317 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003318 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003319 }
3320
John McCall9ae2f072010-08-23 23:25:46 +00003321 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003322}
3323
John McCall60d7b3a2010-08-24 06:29:42 +00003324ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003325Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003326 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003327 Expr *LHSExp = Base;
3328 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003329
Chris Lattner12d9ff62007-07-16 00:14:47 +00003330 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003331 if (!LHSExp->getType()->getAs<VectorType>()) {
3332 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3333 if (Result.isInvalid())
3334 return ExprError();
3335 LHSExp = Result.take();
3336 }
3337 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3338 if (Result.isInvalid())
3339 return ExprError();
3340 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003341
Chris Lattner12d9ff62007-07-16 00:14:47 +00003342 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003343 ExprValueKind VK = VK_LValue;
3344 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003345
Reid Spencer5f016e22007-07-11 17:01:13 +00003346 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003347 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003348 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003349 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003350 Expr *BaseExpr, *IndexExpr;
3351 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003352 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3353 BaseExpr = LHSExp;
3354 IndexExpr = RHSExp;
3355 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003356 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003357 BaseExpr = LHSExp;
3358 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003359 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003360 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003361 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003362 BaseExpr = LHSExp;
3363 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003364
3365 // Use custom logic if this should be the pseudo-object subscript
3366 // expression.
3367 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3368 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3369
Steve Naroff14108da2009-07-10 23:34:53 +00003370 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003371 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3372 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3373 << ResultType << BaseExpr->getSourceRange();
3374 return ExprError();
3375 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003376 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3377 // Handle the uncommon case of "123[Ptr]".
3378 BaseExpr = RHSExp;
3379 IndexExpr = LHSExp;
3380 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003381 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003382 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003383 // Handle the uncommon case of "123[Ptr]".
3384 BaseExpr = RHSExp;
3385 IndexExpr = LHSExp;
3386 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003387 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3388 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3389 << ResultType << BaseExpr->getSourceRange();
3390 return ExprError();
3391 }
John McCall183700f2009-09-21 23:43:11 +00003392 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003393 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003394 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003395 VK = LHSExp->getValueKind();
3396 if (VK != VK_RValue)
3397 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003398
Chris Lattner12d9ff62007-07-16 00:14:47 +00003399 // FIXME: need to deal with const...
3400 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003401 } else if (LHSTy->isArrayType()) {
3402 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003403 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003404 // wasn't promoted because of the C90 rule that doesn't
3405 // allow promoting non-lvalue arrays. Warn, then
3406 // force the promotion here.
3407 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3408 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003409 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3410 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003411 LHSTy = LHSExp->getType();
3412
3413 BaseExpr = LHSExp;
3414 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003415 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003416 } else if (RHSTy->isArrayType()) {
3417 // Same as previous, except for 123[f().a] case
3418 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3419 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003420 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3421 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003422 RHSTy = RHSExp->getType();
3423
3424 BaseExpr = RHSExp;
3425 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003426 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003428 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3429 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003431 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003432 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003433 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3434 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003435
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003436 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003437 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3438 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003439 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3440
Douglas Gregore7450f52009-03-24 19:52:54 +00003441 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003442 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3443 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003444 // incomplete types are not object types.
3445 if (ResultType->isFunctionType()) {
3446 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3447 << ResultType << BaseExpr->getSourceRange();
3448 return ExprError();
3449 }
Mike Stump1eb44332009-09-09 15:08:12 +00003450
David Blaikie4e4d0842012-03-11 07:00:24 +00003451 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003452 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003453 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3454 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003455
3456 // C forbids expressions of unqualified void type from being l-values.
3457 // See IsCForbiddenLValueType.
3458 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003459 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003460 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003461 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003462 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003463
John McCall09431682010-11-18 19:01:18 +00003464 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003465 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003466
Mike Stumpeed9cac2009-02-19 03:04:26 +00003467 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003468 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003469}
3470
John McCall60d7b3a2010-08-24 06:29:42 +00003471ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003472 FunctionDecl *FD,
3473 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003474 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003475 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003476 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003477 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003478 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003479 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003480 return ExprError();
3481 }
3482
3483 if (Param->hasUninstantiatedDefaultArg()) {
3484 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003485
Richard Smithadb1d4c2012-07-22 23:45:10 +00003486 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3487 Param);
3488
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003489 // Instantiate the expression.
3490 MultiLevelTemplateArgumentList ArgList
3491 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003492
Nico Weber08e41a62010-11-29 18:19:25 +00003493 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003494 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003495 InstantiatingTemplate Inst(*this, CallLoc, Param,
3496 ArrayRef<TemplateArgument>(Innermost.first,
3497 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003498 if (Inst)
3499 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003500
Nico Weber08e41a62010-11-29 18:19:25 +00003501 ExprResult Result;
3502 {
3503 // C++ [dcl.fct.default]p5:
3504 // The names in the [default argument] expression are bound, and
3505 // the semantic constraints are checked, at the point where the
3506 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003507 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003508 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003509 Result = SubstExpr(UninstExpr, ArgList);
3510 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003511 if (Result.isInvalid())
3512 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003514 // Check the expression as an initializer for the parameter.
3515 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003516 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003517 InitializationKind Kind
3518 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003519 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003520 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003521
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003522 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003523 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003524 if (Result.isInvalid())
3525 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003526
David Blaikiec1c07252012-04-30 18:21:31 +00003527 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003528 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003529 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003530 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003531 }
3532
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003533 // If the default expression creates temporaries, we need to
3534 // push them to the current stack of expression temporaries so they'll
3535 // be properly destroyed.
3536 // FIXME: We should really be rebuilding the default argument with new
3537 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003538 // We don't need to do that with block decls, though, because
3539 // blocks in default argument expression can never capture anything.
3540 if (isa<ExprWithCleanups>(Param->getInit())) {
3541 // Set the "needs cleanups" bit regardless of whether there are
3542 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003543 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003544
3545 // Append all the objects to the cleanup list. Right now, this
3546 // should always be a no-op, because blocks in default argument
3547 // expressions should never be able to capture anything.
3548 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3549 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003550 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003551
3552 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003553 // Just mark all of the declarations in this potentially-evaluated expression
3554 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003555 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3556 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003557 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003558}
3559
Richard Smith831421f2012-06-25 20:30:08 +00003560
3561Sema::VariadicCallType
3562Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3563 Expr *Fn) {
3564 if (Proto && Proto->isVariadic()) {
3565 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3566 return VariadicConstructor;
3567 else if (Fn && Fn->getType()->isBlockPointerType())
3568 return VariadicBlock;
3569 else if (FDecl) {
3570 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3571 if (Method->isInstance())
3572 return VariadicMethod;
3573 }
3574 return VariadicFunction;
3575 }
3576 return VariadicDoesNotApply;
3577}
3578
Douglas Gregor88a35142008-12-22 05:46:06 +00003579/// ConvertArgumentsForCall - Converts the arguments specified in
3580/// Args/NumArgs to the parameter types of the function FDecl with
3581/// function prototype Proto. Call is the call expression itself, and
3582/// Fn is the function expression. For a C++ member function, this
3583/// routine does not attempt to convert the object argument. Returns
3584/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003585bool
3586Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003588 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003589 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003590 SourceLocation RParenLoc,
3591 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003592 // Bail out early if calling a builtin with custom typechecking.
3593 // We don't need to do this in the
3594 if (FDecl)
3595 if (unsigned ID = FDecl->getBuiltinID())
3596 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3597 return false;
3598
Mike Stumpeed9cac2009-02-19 03:04:26 +00003599 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003600 // assignment, to the types of the corresponding parameter, ...
3601 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003602 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003603 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003604 unsigned FnKind = Fn->getType()->isBlockPointerType()
3605 ? 1 /* block */
3606 : (IsExecConfig ? 3 /* kernel function (exec config) */
3607 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003608
Douglas Gregor88a35142008-12-22 05:46:06 +00003609 // If too few arguments are available (and we don't have default
3610 // arguments for the remaining parameters), don't make the call.
3611 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003612 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003613 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3614 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3615 ? diag::err_typecheck_call_too_few_args_one
3616 : diag::err_typecheck_call_too_few_args_at_least_one)
3617 << FnKind
3618 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3619 else
3620 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3621 ? diag::err_typecheck_call_too_few_args
3622 : diag::err_typecheck_call_too_few_args_at_least)
3623 << FnKind
3624 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003625
3626 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003627 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003628 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3629 << FDecl;
3630
3631 return true;
3632 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003633 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003634 }
3635
3636 // If too many are passed and not variadic, error on the extras and drop
3637 // them.
3638 if (NumArgs > NumArgsInProto) {
3639 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003640 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3641 Diag(Args[NumArgsInProto]->getLocStart(),
3642 MinArgs == NumArgsInProto
3643 ? diag::err_typecheck_call_too_many_args_one
3644 : diag::err_typecheck_call_too_many_args_at_most_one)
3645 << FnKind
3646 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3647 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3648 Args[NumArgs-1]->getLocEnd());
3649 else
3650 Diag(Args[NumArgsInProto]->getLocStart(),
3651 MinArgs == NumArgsInProto
3652 ? diag::err_typecheck_call_too_many_args
3653 : diag::err_typecheck_call_too_many_args_at_most)
3654 << FnKind
3655 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3656 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3657 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003658
3659 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003660 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003661 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3662 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003663
Douglas Gregor88a35142008-12-22 05:46:06 +00003664 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003665 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003666 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003667 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003668 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003669 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003670 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3671
Daniel Dunbar96a00142012-03-09 18:35:03 +00003672 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003673 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003674 if (Invalid)
3675 return true;
3676 unsigned TotalNumArgs = AllArgs.size();
3677 for (unsigned i = 0; i < TotalNumArgs; ++i)
3678 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003679
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003680 return false;
3681}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003682
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003683bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3684 FunctionDecl *FDecl,
3685 const FunctionProtoType *Proto,
3686 unsigned FirstProtoArg,
3687 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003688 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003689 VariadicCallType CallType,
3690 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003691 unsigned NumArgsInProto = Proto->getNumArgs();
3692 unsigned NumArgsToCheck = NumArgs;
3693 bool Invalid = false;
3694 if (NumArgs != NumArgsInProto)
3695 // Use default arguments for missing arguments
3696 NumArgsToCheck = NumArgsInProto;
3697 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003698 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003699 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003700 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003701
Douglas Gregor88a35142008-12-22 05:46:06 +00003702 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003703 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003704 if (ArgIx < NumArgs) {
3705 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003706
Daniel Dunbar96a00142012-03-09 18:35:03 +00003707 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003708 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003709 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003710 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003711
Douglas Gregora188ff22009-12-22 16:09:06 +00003712 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003713 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003714 if (FDecl && i < FDecl->getNumParams())
3715 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003716
John McCall5acb0c92011-10-17 18:40:02 +00003717 // Strip the unbridged-cast placeholder expression off, if applicable.
3718 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3719 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3720 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3721 Arg = stripARCUnbridgedCast(Arg);
3722
Douglas Gregora188ff22009-12-22 16:09:06 +00003723 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003724 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003725 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3726 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003727 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003728 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003729 Owned(Arg),
3730 /*TopLevelOfInitList=*/false,
3731 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003732 if (ArgE.isInvalid())
3733 return true;
3734
3735 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003736 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003737 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003738
John McCall60d7b3a2010-08-24 06:29:42 +00003739 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003740 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003741 if (ArgExpr.isInvalid())
3742 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003743
Anders Carlsson56c5e332009-08-25 03:49:14 +00003744 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003745 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003746
3747 // Check for array bounds violations for each argument to the call. This
3748 // check only triggers warnings when the argument isn't a more complex Expr
3749 // with its own checking, such as a BinaryOperator.
3750 CheckArrayAccess(Arg);
3751
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003752 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3753 CheckStaticArrayArgument(CallLoc, Param, Arg);
3754
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003755 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003756 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003757
Douglas Gregor88a35142008-12-22 05:46:06 +00003758 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003759 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003760 // Assume that extern "C" functions with variadic arguments that
3761 // return __unknown_anytype aren't *really* variadic.
3762 if (Proto->getResultType() == Context.UnknownAnyTy &&
3763 FDecl && FDecl->isExternC()) {
3764 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3765 ExprResult arg;
3766 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3767 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3768 else
3769 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3770 Invalid |= arg.isInvalid();
3771 AllArgs.push_back(arg.take());
3772 }
3773
3774 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3775 } else {
3776 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003777 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3778 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003779 Invalid |= Arg.isInvalid();
3780 AllArgs.push_back(Arg.take());
3781 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003782 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003783
3784 // Check for array bounds violations.
3785 for (unsigned i = ArgIx; i != NumArgs; ++i)
3786 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003787 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003788 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003789}
3790
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003791static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3792 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3793 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3794 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3795 << ATL->getLocalSourceRange();
3796}
3797
3798/// CheckStaticArrayArgument - If the given argument corresponds to a static
3799/// array parameter, check that it is non-null, and that if it is formed by
3800/// array-to-pointer decay, the underlying array is sufficiently large.
3801///
3802/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3803/// array type derivation, then for each call to the function, the value of the
3804/// corresponding actual argument shall provide access to the first element of
3805/// an array with at least as many elements as specified by the size expression.
3806void
3807Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3808 ParmVarDecl *Param,
3809 const Expr *ArgExpr) {
3810 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003811 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003812 return;
3813
3814 QualType OrigTy = Param->getOriginalType();
3815
3816 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3817 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3818 return;
3819
3820 if (ArgExpr->isNullPointerConstant(Context,
3821 Expr::NPC_NeverValueDependent)) {
3822 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3823 DiagnoseCalleeStaticArrayParam(*this, Param);
3824 return;
3825 }
3826
3827 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3828 if (!CAT)
3829 return;
3830
3831 const ConstantArrayType *ArgCAT =
3832 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3833 if (!ArgCAT)
3834 return;
3835
3836 if (ArgCAT->getSize().ult(CAT->getSize())) {
3837 Diag(CallLoc, diag::warn_static_array_too_small)
3838 << ArgExpr->getSourceRange()
3839 << (unsigned) ArgCAT->getSize().getZExtValue()
3840 << (unsigned) CAT->getSize().getZExtValue();
3841 DiagnoseCalleeStaticArrayParam(*this, Param);
3842 }
3843}
3844
John McCall755d8492011-04-12 00:42:48 +00003845/// Given a function expression of unknown-any type, try to rebuild it
3846/// to have a function type.
3847static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3848
Steve Narofff69936d2007-09-16 03:34:24 +00003849/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003850/// This provides the location of the left/right parens and a list of comma
3851/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003852ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003853Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003854 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003855 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003856 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003857 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003858 if (Result.isInvalid()) return ExprError();
3859 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003860
David Blaikie4e4d0842012-03-11 07:00:24 +00003861 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003862 // If this is a pseudo-destructor expression, build the call immediately.
3863 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003864 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003865 // Pseudo-destructor calls should not have any arguments.
3866 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003867 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003868 SourceRange(ArgExprs[0]->getLocStart(),
3869 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003870 }
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003872 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3873 Context.VoidTy, VK_RValue,
3874 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Douglas Gregor17330012009-02-04 15:01:18 +00003877 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003878 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003879 // FIXME: Will need to cache the results of name lookup (including ADL) in
3880 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003881 bool Dependent = false;
3882 if (Fn->isTypeDependent())
3883 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003884 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003885 Dependent = true;
3886
Peter Collingbournee08ce652011-02-09 21:07:24 +00003887 if (Dependent) {
3888 if (ExecConfig) {
3889 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003890 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003891 Context.DependentTy, VK_RValue, RParenLoc));
3892 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003893 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003894 Context.DependentTy, VK_RValue,
3895 RParenLoc));
3896 }
3897 }
Douglas Gregor17330012009-02-04 15:01:18 +00003898
3899 // Determine whether this is a call to an object (C++ [over.call.object]).
3900 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003901 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3902 ArgExprs.data(),
3903 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003904
John McCall755d8492011-04-12 00:42:48 +00003905 if (Fn->getType() == Context.UnknownAnyTy) {
3906 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3907 if (result.isInvalid()) return ExprError();
3908 Fn = result.take();
3909 }
3910
John McCall864c0412011-04-26 20:42:42 +00003911 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003912 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3913 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003914 }
John McCall864c0412011-04-26 20:42:42 +00003915 }
John McCall129e2df2009-11-30 22:42:35 +00003916
John McCall864c0412011-04-26 20:42:42 +00003917 // Check for overloaded calls. This can happen even in C due to extensions.
3918 if (Fn->getType() == Context.OverloadTy) {
3919 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3920
Douglas Gregoree697e62011-10-13 18:10:35 +00003921 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003922 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003923 OverloadExpr *ovl = find.Expression;
3924 if (isa<UnresolvedLookupExpr>(ovl)) {
3925 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003926 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3927 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003928 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003929 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3930 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003931 }
3932 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003933 }
3934
Douglas Gregorfa047642009-02-04 00:32:51 +00003935 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003936 if (Fn->getType() == Context.UnknownAnyTy) {
3937 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3938 if (result.isInvalid()) return ExprError();
3939 Fn = result.take();
3940 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003941
Eli Friedmanefa42f72009-12-26 03:35:45 +00003942 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003943
John McCall3b4294e2009-12-16 12:17:52 +00003944 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003945 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3946 if (UnOp->getOpcode() == UO_AddrOf)
3947 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3948
John McCall3b4294e2009-12-16 12:17:52 +00003949 if (isa<DeclRefExpr>(NakedFn))
3950 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003951 else if (isa<MemberExpr>(NakedFn))
3952 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003953
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003954 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3955 ArgExprs.size(), RParenLoc, ExecConfig,
3956 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003957}
3958
3959ExprResult
3960Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003961 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003962 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3963 if (!ConfigDecl)
3964 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3965 << "cudaConfigureCall");
3966 QualType ConfigQTy = ConfigDecl->getType();
3967
3968 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003969 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003970 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003971
Peter Collingbourne1f240762011-10-02 23:49:29 +00003972 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3973 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003974}
3975
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003976/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3977///
3978/// __builtin_astype( value, dst type )
3979///
Richard Trieuccd891a2011-09-09 01:45:06 +00003980ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003981 SourceLocation BuiltinLoc,
3982 SourceLocation RParenLoc) {
3983 ExprValueKind VK = VK_RValue;
3984 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003985 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3986 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003987 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3988 return ExprError(Diag(BuiltinLoc,
3989 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003990 << DstTy
3991 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003992 << E->getSourceRange());
3993 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003994 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003995}
3996
John McCall3b4294e2009-12-16 12:17:52 +00003997/// BuildResolvedCallExpr - Build a call to a resolved expression,
3998/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003999/// unary-convert to an expression of function-pointer or
4000/// block-pointer type.
4001///
4002/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004003ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004004Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4005 SourceLocation LParenLoc,
4006 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004007 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004008 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004009 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004010 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004011
Chris Lattner04421082008-04-08 04:40:51 +00004012 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004013 // We special-case function promotion here because we only allow promoting
4014 // builtin functions to function pointers in the callee of a call.
4015 ExprResult Result;
4016 if (BuiltinID &&
4017 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4018 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4019 CK_BuiltinFnToFnPtr).take();
4020 } else {
4021 Result = UsualUnaryConversions(Fn);
4022 }
John Wiegley429bb272011-04-08 18:41:53 +00004023 if (Result.isInvalid())
4024 return ExprError();
4025 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004026
Chris Lattner925e60d2007-12-28 05:29:59 +00004027 // Make the call expr early, before semantic checks. This guarantees cleanup
4028 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004029 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004030 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004031 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4032 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004033 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004034 Context.BoolTy,
4035 VK_RValue,
4036 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004037 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004038 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004039 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004040 Context.BoolTy,
4041 VK_RValue,
4042 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004043
John McCall8e10f3b2011-02-26 05:39:39 +00004044 // Bail out early if calling a builtin with custom typechecking.
4045 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4046 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4047
John McCall1de4d4e2011-04-07 08:22:57 +00004048 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004049 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004050 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004051 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4052 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004053 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004054 if (FuncT == 0)
4055 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4056 << Fn->getType() << Fn->getSourceRange());
4057 } else if (const BlockPointerType *BPT =
4058 Fn->getType()->getAs<BlockPointerType>()) {
4059 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4060 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004061 // Handle calls to expressions of unknown-any type.
4062 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004063 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004064 if (rewrite.isInvalid()) return ExprError();
4065 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004066 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004067 goto retry;
4068 }
4069
Sebastian Redl0eb23302009-01-19 00:08:26 +00004070 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4071 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004072 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004073
David Blaikie4e4d0842012-03-11 07:00:24 +00004074 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004075 if (Config) {
4076 // CUDA: Kernel calls must be to global functions
4077 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4078 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4079 << FDecl->getName() << Fn->getSourceRange());
4080
4081 // CUDA: Kernel function must have 'void' return type
4082 if (!FuncT->getResultType()->isVoidType())
4083 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4084 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004085 } else {
4086 // CUDA: Calls to global functions must be configured
4087 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4088 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4089 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004090 }
4091 }
4092
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004093 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004094 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004095 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004096 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004097 return ExprError();
4098
Chris Lattner925e60d2007-12-28 05:29:59 +00004099 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004100 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004101 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004102
Richard Smith831421f2012-06-25 20:30:08 +00004103 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4104 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004105 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004106 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004107 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004108 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004109 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004110
Douglas Gregor74734d52009-04-02 15:37:10 +00004111 if (FDecl) {
4112 // Check if we have too few/too many template arguments, based
4113 // on our knowledge of the function definition.
4114 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004115 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004116 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004117 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004118 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4119 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004120 }
Douglas Gregor46542412010-10-25 20:39:23 +00004121
4122 // If the function we're calling isn't a function prototype, but we have
4123 // a function prototype from a prior declaratiom, use that prototype.
4124 if (!FDecl->hasPrototype())
4125 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004126 }
4127
Steve Naroffb291ab62007-08-28 23:30:39 +00004128 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004129 for (unsigned i = 0; i != NumArgs; i++) {
4130 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004131
4132 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004133 InitializedEntity Entity
4134 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004135 Proto->getArgType(i),
4136 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004137 ExprResult ArgE = PerformCopyInitialization(Entity,
4138 SourceLocation(),
4139 Owned(Arg));
4140 if (ArgE.isInvalid())
4141 return true;
4142
4143 Arg = ArgE.takeAs<Expr>();
4144
4145 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004146 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4147
4148 if (ArgE.isInvalid())
4149 return true;
4150
4151 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004152 }
4153
Daniel Dunbar96a00142012-03-09 18:35:03 +00004154 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004155 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004156 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004157 return ExprError();
4158
Chris Lattner925e60d2007-12-28 05:29:59 +00004159 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004160 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004161 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004162
Douglas Gregor88a35142008-12-22 05:46:06 +00004163 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4164 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004165 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4166 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004167
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004168 // Check for sentinels
4169 if (NDecl)
4170 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Chris Lattner59907c42007-08-10 20:18:51 +00004172 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004173 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004174 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004175 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004176
John McCall8e10f3b2011-02-26 05:39:39 +00004177 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004178 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004179 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004180 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004181 return ExprError();
4182 }
Chris Lattner59907c42007-08-10 20:18:51 +00004183
John McCall9ae2f072010-08-23 23:25:46 +00004184 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004185}
4186
John McCall60d7b3a2010-08-24 06:29:42 +00004187ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004188Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004189 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004190 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004191 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004192 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004193
4194 TypeSourceInfo *TInfo;
4195 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4196 if (!TInfo)
4197 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4198
John McCall9ae2f072010-08-23 23:25:46 +00004199 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004200}
4201
John McCall60d7b3a2010-08-24 06:29:42 +00004202ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004203Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004204 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004205 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004206
Eli Friedman6223c222008-05-20 05:22:08 +00004207 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004208 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004209 diag::err_illegal_decl_array_incomplete_type,
4210 SourceRange(LParenLoc,
4211 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004212 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004213 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004214 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004215 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004216 } else if (!literalType->isDependentType() &&
4217 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004218 diag::err_typecheck_decl_incomplete_type,
4219 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004220 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004221
Douglas Gregor99a2e602009-12-16 01:38:02 +00004222 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004223 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004224 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004225 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004226 SourceRange(LParenLoc, RParenLoc),
4227 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004228 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004229 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4230 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004231 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004232 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004233 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004234
Chris Lattner371f2582008-12-04 23:50:19 +00004235 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004236 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004237 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004238 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004239 }
Eli Friedman08544622009-12-22 02:35:53 +00004240
John McCallf89e55a2010-11-18 06:31:45 +00004241 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004242 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004243
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004244 return MaybeBindToTemporary(
4245 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004246 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004247}
4248
John McCall60d7b3a2010-08-24 06:29:42 +00004249ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004250Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004251 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004252 // Immediately handle non-overload placeholders. Overloads can be
4253 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004254 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4255 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4256 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004257
4258 // Ignore failures; dropping the entire initializer list because
4259 // of one failure would be terrible for indexing/etc.
4260 if (result.isInvalid()) continue;
4261
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004262 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004263 }
4264 }
4265
Steve Naroff08d92e42007-09-15 18:49:24 +00004266 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004267 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004268
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004269 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4270 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004271 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004272 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004273}
4274
John McCalldc05b112011-09-10 01:16:55 +00004275/// Do an explicit extend of the given block pointer if we're in ARC.
4276static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4277 assert(E.get()->getType()->isBlockPointerType());
4278 assert(E.get()->isRValue());
4279
4280 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004281 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004282
4283 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004284 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004285 /*base path*/ 0, VK_RValue);
4286 S.ExprNeedsCleanups = true;
4287}
4288
4289/// Prepare a conversion of the given expression to an ObjC object
4290/// pointer type.
4291CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4292 QualType type = E.get()->getType();
4293 if (type->isObjCObjectPointerType()) {
4294 return CK_BitCast;
4295 } else if (type->isBlockPointerType()) {
4296 maybeExtendBlockObject(*this, E);
4297 return CK_BlockPointerToObjCPointerCast;
4298 } else {
4299 assert(type->isPointerType());
4300 return CK_CPointerToObjCPointerCast;
4301 }
4302}
4303
John McCallf3ea8cf2010-11-14 08:17:51 +00004304/// Prepares for a scalar cast, performing all the necessary stages
4305/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004306CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004307 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4308 // Also, callers should have filtered out the invalid cases with
4309 // pointers. Everything else should be possible.
4310
John Wiegley429bb272011-04-08 18:41:53 +00004311 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004312 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004313 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004314
John McCall1d9b3b22011-09-09 05:25:32 +00004315 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004316 case Type::STK_MemberPointer:
4317 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004318
John McCall1d9b3b22011-09-09 05:25:32 +00004319 case Type::STK_CPointer:
4320 case Type::STK_BlockPointer:
4321 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004322 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004323 case Type::STK_CPointer:
4324 return CK_BitCast;
4325 case Type::STK_BlockPointer:
4326 return (SrcKind == Type::STK_BlockPointer
4327 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4328 case Type::STK_ObjCObjectPointer:
4329 if (SrcKind == Type::STK_ObjCObjectPointer)
4330 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004331 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004332 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004333 maybeExtendBlockObject(*this, Src);
4334 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004335 case Type::STK_Bool:
4336 return CK_PointerToBoolean;
4337 case Type::STK_Integral:
4338 return CK_PointerToIntegral;
4339 case Type::STK_Floating:
4340 case Type::STK_FloatingComplex:
4341 case Type::STK_IntegralComplex:
4342 case Type::STK_MemberPointer:
4343 llvm_unreachable("illegal cast from pointer");
4344 }
David Blaikie7530c032012-01-17 06:56:22 +00004345 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004346
John McCalldaa8e4e2010-11-15 09:13:47 +00004347 case Type::STK_Bool: // casting from bool is like casting from an integer
4348 case Type::STK_Integral:
4349 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004350 case Type::STK_CPointer:
4351 case Type::STK_ObjCObjectPointer:
4352 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004353 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004354 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004355 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004356 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004357 case Type::STK_Bool:
4358 return CK_IntegralToBoolean;
4359 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004360 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004361 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004362 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004363 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004364 Src = ImpCastExprToType(Src.take(),
4365 DestTy->castAs<ComplexType>()->getElementType(),
4366 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004367 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004368 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004369 Src = ImpCastExprToType(Src.take(),
4370 DestTy->castAs<ComplexType>()->getElementType(),
4371 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004372 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004373 case Type::STK_MemberPointer:
4374 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004375 }
David Blaikie7530c032012-01-17 06:56:22 +00004376 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004377
John McCalldaa8e4e2010-11-15 09:13:47 +00004378 case Type::STK_Floating:
4379 switch (DestTy->getScalarTypeKind()) {
4380 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004381 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004382 case Type::STK_Bool:
4383 return CK_FloatingToBoolean;
4384 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004385 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004386 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004387 Src = ImpCastExprToType(Src.take(),
4388 DestTy->castAs<ComplexType>()->getElementType(),
4389 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004390 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004391 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004392 Src = ImpCastExprToType(Src.take(),
4393 DestTy->castAs<ComplexType>()->getElementType(),
4394 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004395 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004396 case Type::STK_CPointer:
4397 case Type::STK_ObjCObjectPointer:
4398 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004399 llvm_unreachable("valid float->pointer cast?");
4400 case Type::STK_MemberPointer:
4401 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004402 }
David Blaikie7530c032012-01-17 06:56:22 +00004403 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004404
John McCalldaa8e4e2010-11-15 09:13:47 +00004405 case Type::STK_FloatingComplex:
4406 switch (DestTy->getScalarTypeKind()) {
4407 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004408 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004409 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004410 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004411 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004412 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4413 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004414 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004415 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004416 return CK_FloatingCast;
4417 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004418 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004419 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004420 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004421 Src = ImpCastExprToType(Src.take(),
4422 SrcTy->castAs<ComplexType>()->getElementType(),
4423 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004424 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004425 case Type::STK_CPointer:
4426 case Type::STK_ObjCObjectPointer:
4427 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004428 llvm_unreachable("valid complex float->pointer cast?");
4429 case Type::STK_MemberPointer:
4430 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004431 }
David Blaikie7530c032012-01-17 06:56:22 +00004432 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004433
John McCalldaa8e4e2010-11-15 09:13:47 +00004434 case Type::STK_IntegralComplex:
4435 switch (DestTy->getScalarTypeKind()) {
4436 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004437 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004438 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004439 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004440 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004441 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4442 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004443 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004444 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004445 return CK_IntegralCast;
4446 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004447 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004448 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004449 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004450 Src = ImpCastExprToType(Src.take(),
4451 SrcTy->castAs<ComplexType>()->getElementType(),
4452 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004453 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004454 case Type::STK_CPointer:
4455 case Type::STK_ObjCObjectPointer:
4456 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004457 llvm_unreachable("valid complex int->pointer cast?");
4458 case Type::STK_MemberPointer:
4459 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004460 }
David Blaikie7530c032012-01-17 06:56:22 +00004461 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004462 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004463
John McCallf3ea8cf2010-11-14 08:17:51 +00004464 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004465}
4466
Anders Carlssonc3516322009-10-16 02:48:28 +00004467bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004468 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004469 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004470
Anders Carlssona64db8f2007-11-27 05:51:55 +00004471 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004472 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004473 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004474 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004475 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004476 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004477 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004478 } else
4479 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004480 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004481 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004482
John McCall2de56d12010-08-25 11:45:40 +00004483 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004484 return false;
4485}
4486
John Wiegley429bb272011-04-08 18:41:53 +00004487ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4488 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004489 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004490
Anders Carlsson16a89042009-10-16 05:23:41 +00004491 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004492
Nate Begeman9b10da62009-06-27 22:05:55 +00004493 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4494 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004495 // In OpenCL, casts between vectors of different types are not allowed.
4496 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004497 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004498 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004499 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004500 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004501 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004502 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004503 return ExprError();
4504 }
John McCall2de56d12010-08-25 11:45:40 +00004505 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004506 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004507 }
4508
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004509 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004510 // conversion will take place first from scalar to elt type, and then
4511 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004512 if (SrcTy->isPointerType())
4513 return Diag(R.getBegin(),
4514 diag::err_invalid_conversion_between_vector_and_scalar)
4515 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004516
4517 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004518 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004519 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004520 if (CastExprRes.isInvalid())
4521 return ExprError();
4522 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004523
John McCall2de56d12010-08-25 11:45:40 +00004524 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004525 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004526}
4527
John McCall60d7b3a2010-08-24 06:29:42 +00004528ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004529Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4530 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004531 SourceLocation RParenLoc, Expr *CastExpr) {
4532 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004533 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004534
Richard Trieuccd891a2011-09-09 01:45:06 +00004535 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004536 if (D.isInvalidType())
4537 return ExprError();
4538
David Blaikie4e4d0842012-03-11 07:00:24 +00004539 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004540 // Check that there are no default arguments (C++ only).
4541 CheckExtraCXXDefaultArguments(D);
4542 }
4543
John McCalle82247a2011-10-01 05:17:03 +00004544 checkUnusedDeclAttributes(D);
4545
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004546 QualType castType = castTInfo->getType();
4547 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004548
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004549 bool isVectorLiteral = false;
4550
4551 // Check for an altivec or OpenCL literal,
4552 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004553 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4554 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004555 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004556 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004557 if (PLE && PLE->getNumExprs() == 0) {
4558 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4559 return ExprError();
4560 }
4561 if (PE || PLE->getNumExprs() == 1) {
4562 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4563 if (!E->getType()->isVectorType())
4564 isVectorLiteral = true;
4565 }
4566 else
4567 isVectorLiteral = true;
4568 }
4569
4570 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4571 // then handle it as such.
4572 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004573 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004574
Nate Begeman2ef13e52009-08-10 23:49:36 +00004575 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004576 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4577 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004578 if (isa<ParenListExpr>(CastExpr)) {
4579 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004580 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004581 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004582 }
John McCallb042fdf2010-01-15 18:56:44 +00004583
Richard Trieuccd891a2011-09-09 01:45:06 +00004584 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004585}
4586
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004587ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4588 SourceLocation RParenLoc, Expr *E,
4589 TypeSourceInfo *TInfo) {
4590 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4591 "Expected paren or paren list expression");
4592
4593 Expr **exprs;
4594 unsigned numExprs;
4595 Expr *subExpr;
4596 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4597 exprs = PE->getExprs();
4598 numExprs = PE->getNumExprs();
4599 } else {
4600 subExpr = cast<ParenExpr>(E)->getSubExpr();
4601 exprs = &subExpr;
4602 numExprs = 1;
4603 }
4604
4605 QualType Ty = TInfo->getType();
4606 assert(Ty->isVectorType() && "Expected vector type");
4607
Chris Lattner5f9e2722011-07-23 10:55:15 +00004608 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004609 const VectorType *VTy = Ty->getAs<VectorType>();
4610 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4611
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004612 // '(...)' form of vector initialization in AltiVec: the number of
4613 // initializers must be one or must match the size of the vector.
4614 // If a single value is specified in the initializer then it will be
4615 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004616 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004617 // The number of initializers must be one or must match the size of the
4618 // vector. If a single value is specified in the initializer then it will
4619 // be replicated to all the components of the vector
4620 if (numExprs == 1) {
4621 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004622 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4623 if (Literal.isInvalid())
4624 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004625 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004626 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004627 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4628 }
4629 else if (numExprs < numElems) {
4630 Diag(E->getExprLoc(),
4631 diag::err_incorrect_number_of_vector_initializers);
4632 return ExprError();
4633 }
4634 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004635 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004636 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004637 else {
4638 // For OpenCL, when the number of initializers is a single value,
4639 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004640 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004641 VTy->getVectorKind() == VectorType::GenericVector &&
4642 numExprs == 1) {
4643 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004644 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4645 if (Literal.isInvalid())
4646 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004647 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004648 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004649 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4650 }
4651
Benjamin Kramer14c59822012-02-14 12:06:21 +00004652 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004653 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004654 // FIXME: This means that pretty-printing the final AST will produce curly
4655 // braces instead of the original commas.
4656 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004657 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004658 initE->setType(Ty);
4659 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4660}
4661
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004662/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4663/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004664ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004665Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4666 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004667 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004668 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004669
John McCall60d7b3a2010-08-24 06:29:42 +00004670 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Nate Begeman2ef13e52009-08-10 23:49:36 +00004672 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004673 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4674 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004675
John McCall9ae2f072010-08-23 23:25:46 +00004676 if (Result.isInvalid()) return ExprError();
4677
4678 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004679}
4680
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004681ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4682 SourceLocation R,
4683 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004684 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4685 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004686 return Owned(expr);
4687}
4688
Chandler Carruth82214a82011-02-18 23:54:50 +00004689/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004690/// constant and the other is not a pointer. Returns true if a diagnostic is
4691/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004692bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004693 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004694 Expr *NullExpr = LHSExpr;
4695 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004696 Expr::NullPointerConstantKind NullKind =
4697 NullExpr->isNullPointerConstant(Context,
4698 Expr::NPC_ValueDependentIsNotNull);
4699
4700 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004701 NullExpr = RHSExpr;
4702 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004703 NullKind =
4704 NullExpr->isNullPointerConstant(Context,
4705 Expr::NPC_ValueDependentIsNotNull);
4706 }
4707
4708 if (NullKind == Expr::NPCK_NotNull)
4709 return false;
4710
David Blaikie50800fc2012-08-08 17:33:31 +00004711 if (NullKind == Expr::NPCK_ZeroExpression)
4712 return false;
4713
4714 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004715 // In this case, check to make sure that we got here from a "NULL"
4716 // string in the source code.
4717 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004718 SourceLocation loc = NullExpr->getExprLoc();
4719 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004720 return false;
4721 }
4722
4723 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4724 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4725 << NonPointerExpr->getType() << DiagType
4726 << NonPointerExpr->getSourceRange();
4727 return true;
4728}
4729
Richard Trieu26f96072011-09-02 01:51:02 +00004730/// \brief Return false if the condition expression is valid, true otherwise.
4731static bool checkCondition(Sema &S, Expr *Cond) {
4732 QualType CondTy = Cond->getType();
4733
4734 // C99 6.5.15p2
4735 if (CondTy->isScalarType()) return false;
4736
4737 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004738 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004739 return false;
4740
4741 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004742 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004743 diag::err_typecheck_cond_expect_scalar :
4744 diag::err_typecheck_cond_expect_scalar_or_vector)
4745 << CondTy;
4746 return true;
4747}
4748
4749/// \brief Return false if the two expressions can be converted to a vector,
4750/// true otherwise
4751static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4752 ExprResult &RHS,
4753 QualType CondTy) {
4754 // Both operands should be of scalar type.
4755 if (!LHS.get()->getType()->isScalarType()) {
4756 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4757 << CondTy;
4758 return true;
4759 }
4760 if (!RHS.get()->getType()->isScalarType()) {
4761 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4762 << CondTy;
4763 return true;
4764 }
4765
4766 // Implicity convert these scalars to the type of the condition.
4767 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4768 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4769 return false;
4770}
4771
4772/// \brief Handle when one or both operands are void type.
4773static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4774 ExprResult &RHS) {
4775 Expr *LHSExpr = LHS.get();
4776 Expr *RHSExpr = RHS.get();
4777
4778 if (!LHSExpr->getType()->isVoidType())
4779 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4780 << RHSExpr->getSourceRange();
4781 if (!RHSExpr->getType()->isVoidType())
4782 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4783 << LHSExpr->getSourceRange();
4784 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4785 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4786 return S.Context.VoidTy;
4787}
4788
4789/// \brief Return false if the NullExpr can be promoted to PointerTy,
4790/// true otherwise.
4791static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4792 QualType PointerTy) {
4793 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4794 !NullExpr.get()->isNullPointerConstant(S.Context,
4795 Expr::NPC_ValueDependentIsNull))
4796 return true;
4797
4798 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4799 return false;
4800}
4801
4802/// \brief Checks compatibility between two pointers and return the resulting
4803/// type.
4804static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4805 ExprResult &RHS,
4806 SourceLocation Loc) {
4807 QualType LHSTy = LHS.get()->getType();
4808 QualType RHSTy = RHS.get()->getType();
4809
4810 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4811 // Two identical pointers types are always compatible.
4812 return LHSTy;
4813 }
4814
4815 QualType lhptee, rhptee;
4816
4817 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004818 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4819 lhptee = LHSBTy->getPointeeType();
4820 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004821 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004822 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4823 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004824 }
4825
Eli Friedmanae916a12012-04-05 22:30:04 +00004826 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4827 // differently qualified versions of compatible types, the result type is
4828 // a pointer to an appropriately qualified version of the composite
4829 // type.
4830
4831 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4832 // clause doesn't make sense for our extensions. E.g. address space 2 should
4833 // be incompatible with address space 3: they may live on different devices or
4834 // anything.
4835 Qualifiers lhQual = lhptee.getQualifiers();
4836 Qualifiers rhQual = rhptee.getQualifiers();
4837
4838 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4839 lhQual.removeCVRQualifiers();
4840 rhQual.removeCVRQualifiers();
4841
4842 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4843 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4844
4845 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4846
4847 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004848 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4849 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4850 << RHS.get()->getSourceRange();
4851 // In this situation, we assume void* type. No especially good
4852 // reason, but this is what gcc does, and we do have to pick
4853 // to get a consistent AST.
4854 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4855 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4856 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4857 return incompatTy;
4858 }
4859
4860 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004861 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4862 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004863
Eli Friedmanae916a12012-04-05 22:30:04 +00004864 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4865 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4866 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004867}
4868
4869/// \brief Return the resulting type when the operands are both block pointers.
4870static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4871 ExprResult &LHS,
4872 ExprResult &RHS,
4873 SourceLocation Loc) {
4874 QualType LHSTy = LHS.get()->getType();
4875 QualType RHSTy = RHS.get()->getType();
4876
4877 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4878 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4879 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4880 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4881 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4882 return destType;
4883 }
4884 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4885 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4886 << RHS.get()->getSourceRange();
4887 return QualType();
4888 }
4889
4890 // We have 2 block pointer types.
4891 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4892}
4893
4894/// \brief Return the resulting type when the operands are both pointers.
4895static QualType
4896checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4897 ExprResult &RHS,
4898 SourceLocation Loc) {
4899 // get the pointer types
4900 QualType LHSTy = LHS.get()->getType();
4901 QualType RHSTy = RHS.get()->getType();
4902
4903 // get the "pointed to" types
4904 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4905 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4906
4907 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4908 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4909 // Figure out necessary qualifiers (C99 6.5.15p6)
4910 QualType destPointee
4911 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4912 QualType destType = S.Context.getPointerType(destPointee);
4913 // Add qualifiers if necessary.
4914 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4915 // Promote to void*.
4916 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4917 return destType;
4918 }
4919 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4920 QualType destPointee
4921 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4922 QualType destType = S.Context.getPointerType(destPointee);
4923 // Add qualifiers if necessary.
4924 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4925 // Promote to void*.
4926 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4927 return destType;
4928 }
4929
4930 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4931}
4932
4933/// \brief Return false if the first expression is not an integer and the second
4934/// expression is not a pointer, true otherwise.
4935static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4936 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004937 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004938 if (!PointerExpr->getType()->isPointerType() ||
4939 !Int.get()->getType()->isIntegerType())
4940 return false;
4941
Richard Trieuccd891a2011-09-09 01:45:06 +00004942 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4943 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004944
4945 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4946 << Expr1->getType() << Expr2->getType()
4947 << Expr1->getSourceRange() << Expr2->getSourceRange();
4948 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4949 CK_IntegralToPointer);
4950 return true;
4951}
4952
Richard Trieu33fc7572011-09-06 20:06:39 +00004953/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4954/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004955/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004956QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4957 ExprResult &RHS, ExprValueKind &VK,
4958 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004959 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004960
Richard Trieu33fc7572011-09-06 20:06:39 +00004961 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4962 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004963 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004964
Richard Trieu33fc7572011-09-06 20:06:39 +00004965 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4966 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004967 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004968
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004969 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004970 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004971 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004972
4973 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004974 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004975
John Wiegley429bb272011-04-08 18:41:53 +00004976 Cond = UsualUnaryConversions(Cond.take());
4977 if (Cond.isInvalid())
4978 return QualType();
4979 LHS = UsualUnaryConversions(LHS.take());
4980 if (LHS.isInvalid())
4981 return QualType();
4982 RHS = UsualUnaryConversions(RHS.take());
4983 if (RHS.isInvalid())
4984 return QualType();
4985
4986 QualType CondTy = Cond.get()->getType();
4987 QualType LHSTy = LHS.get()->getType();
4988 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004989
Reid Spencer5f016e22007-07-11 17:01:13 +00004990 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004991 if (checkCondition(*this, Cond.get()))
4992 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004993
Chris Lattner70d67a92008-01-06 22:42:25 +00004994 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004995 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004996 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004997
Nate Begeman6155d732010-09-20 22:41:17 +00004998 // OpenCL: If the condition is a vector, and both operands are scalar,
4999 // attempt to implicity convert them to the vector type to act like the
5000 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00005001 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00005002 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00005003 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00005004
Chris Lattner70d67a92008-01-06 22:42:25 +00005005 // If both operands have arithmetic type, do the usual arithmetic conversions
5006 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005007 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5008 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005009 if (LHS.isInvalid() || RHS.isInvalid())
5010 return QualType();
5011 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005012 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005013
Chris Lattner70d67a92008-01-06 22:42:25 +00005014 // If both operands are the same structure or union type, the result is that
5015 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005016 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5017 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005018 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005019 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005020 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005021 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005022 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005023 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005024
Chris Lattner70d67a92008-01-06 22:42:25 +00005025 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005026 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005027 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005028 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005029 }
Richard Trieu26f96072011-09-02 01:51:02 +00005030
Steve Naroffb6d54e52008-01-08 01:11:38 +00005031 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5032 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005033 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5034 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005035
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005036 // All objective-c pointer type analysis is done here.
5037 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5038 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005039 if (LHS.isInvalid() || RHS.isInvalid())
5040 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005041 if (!compositeType.isNull())
5042 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005043
5044
Steve Naroff7154a772009-07-01 14:36:47 +00005045 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005046 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5047 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5048 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005049
Steve Naroff7154a772009-07-01 14:36:47 +00005050 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005051 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5052 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5053 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005054
John McCall404cd162010-11-13 01:35:44 +00005055 // GCC compatibility: soften pointer/integer mismatch. Note that
5056 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005057 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5058 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005059 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005060 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5061 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005062 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005063
Chandler Carruth82214a82011-02-18 23:54:50 +00005064 // Emit a better diagnostic if one of the expressions is a null pointer
5065 // constant and the other is not a pointer type. In this case, the user most
5066 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005067 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005068 return QualType();
5069
Chris Lattner70d67a92008-01-06 22:42:25 +00005070 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005072 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5073 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005074 return QualType();
5075}
5076
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005077/// FindCompositeObjCPointerType - Helper method to find composite type of
5078/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005079QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005080 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005081 QualType LHSTy = LHS.get()->getType();
5082 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005083
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005084 // Handle things like Class and struct objc_class*. Here we case the result
5085 // to the pseudo-builtin, because that will be implicitly cast back to the
5086 // redefinition type if an attempt is made to access its fields.
5087 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005088 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005089 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005090 return LHSTy;
5091 }
5092 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005093 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005094 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005095 return RHSTy;
5096 }
5097 // And the same for struct objc_object* / id
5098 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005099 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005100 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005101 return LHSTy;
5102 }
5103 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005104 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005105 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005106 return RHSTy;
5107 }
5108 // And the same for struct objc_selector* / SEL
5109 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005110 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005111 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005112 return LHSTy;
5113 }
5114 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005115 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005116 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005117 return RHSTy;
5118 }
5119 // Check constraints for Objective-C object pointers types.
5120 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005121
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005122 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5123 // Two identical object pointer types are always compatible.
5124 return LHSTy;
5125 }
John McCall1d9b3b22011-09-09 05:25:32 +00005126 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5127 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005128 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005129
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005130 // If both operands are interfaces and either operand can be
5131 // assigned to the other, use that type as the composite
5132 // type. This allows
5133 // xxx ? (A*) a : (B*) b
5134 // where B is a subclass of A.
5135 //
5136 // Additionally, as for assignment, if either type is 'id'
5137 // allow silent coercion. Finally, if the types are
5138 // incompatible then make sure to use 'id' as the composite
5139 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005140
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005141 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5142 // It could return the composite type.
5143 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5144 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5145 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5146 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5147 } else if ((LHSTy->isObjCQualifiedIdType() ||
5148 RHSTy->isObjCQualifiedIdType()) &&
5149 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5150 // Need to handle "id<xx>" explicitly.
5151 // GCC allows qualified id and any Objective-C type to devolve to
5152 // id. Currently localizing to here until clear this should be
5153 // part of ObjCQualifiedIdTypesAreCompatible.
5154 compositeType = Context.getObjCIdType();
5155 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5156 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005157 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005158 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5159 ;
5160 else {
5161 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5162 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005163 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005164 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005165 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5166 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005167 return incompatTy;
5168 }
5169 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005170 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5171 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005172 return compositeType;
5173 }
5174 // Check Objective-C object pointer types and 'void *'
5175 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005176 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005177 // ARC forbids the implicit conversion of object pointers to 'void *',
5178 // so these types are not compatible.
5179 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5181 LHS = RHS = true;
5182 return QualType();
5183 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005184 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5185 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5186 QualType destPointee
5187 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5188 QualType destType = Context.getPointerType(destPointee);
5189 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005190 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005191 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005192 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005193 return destType;
5194 }
5195 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005196 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005197 // ARC forbids the implicit conversion of object pointers to 'void *',
5198 // so these types are not compatible.
5199 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5201 LHS = RHS = true;
5202 return QualType();
5203 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005204 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5205 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5206 QualType destPointee
5207 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5208 QualType destType = Context.getPointerType(destPointee);
5209 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005210 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005211 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005212 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005213 return destType;
5214 }
5215 return QualType();
5216}
5217
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005218/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005219/// ParenRange in parentheses.
5220static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005221 const PartialDiagnostic &Note,
5222 SourceRange ParenRange) {
5223 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5224 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5225 EndLoc.isValid()) {
5226 Self.Diag(Loc, Note)
5227 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5228 << FixItHint::CreateInsertion(EndLoc, ")");
5229 } else {
5230 // We can't display the parentheses, so just show the bare note.
5231 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005232 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005233}
5234
5235static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5236 return Opc >= BO_Mul && Opc <= BO_Shr;
5237}
5238
Hans Wennborg2f072b42011-06-09 17:06:51 +00005239/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5240/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005241/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5242/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005243static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005244 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005245 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5246 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005247 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005248 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005249
5250 // Built-in binary operator.
5251 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5252 if (IsArithmeticOp(OP->getOpcode())) {
5253 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005254 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005255 return true;
5256 }
5257 }
5258
5259 // Overloaded operator.
5260 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5261 if (Call->getNumArgs() != 2)
5262 return false;
5263
5264 // Make sure this is really a binary operator that is safe to pass into
5265 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5266 OverloadedOperatorKind OO = Call->getOperator();
5267 if (OO < OO_Plus || OO > OO_Arrow)
5268 return false;
5269
5270 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5271 if (IsArithmeticOp(OpKind)) {
5272 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005273 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005274 return true;
5275 }
5276 }
5277
5278 return false;
5279}
5280
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005281static bool IsLogicOp(BinaryOperatorKind Opc) {
5282 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5283}
5284
Hans Wennborg2f072b42011-06-09 17:06:51 +00005285/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5286/// or is a logical expression such as (x==y) which has int type, but is
5287/// commonly interpreted as boolean.
5288static bool ExprLooksBoolean(Expr *E) {
5289 E = E->IgnoreParenImpCasts();
5290
5291 if (E->getType()->isBooleanType())
5292 return true;
5293 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5294 return IsLogicOp(OP->getOpcode());
5295 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5296 return OP->getOpcode() == UO_LNot;
5297
5298 return false;
5299}
5300
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005301/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5302/// and binary operator are mixed in a way that suggests the programmer assumed
5303/// the conditional operator has higher precedence, for example:
5304/// "int x = a + someBinaryCondition ? 1 : 2".
5305static void DiagnoseConditionalPrecedence(Sema &Self,
5306 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005307 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005308 Expr *LHSExpr,
5309 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005310 BinaryOperatorKind CondOpcode;
5311 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005312
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005313 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005314 return;
5315 if (!ExprLooksBoolean(CondRHS))
5316 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005317
Hans Wennborg2f072b42011-06-09 17:06:51 +00005318 // The condition is an arithmetic binary expression, with a right-
5319 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005320
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005321 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005322 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005323 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005324
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005325 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005326 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005327 << BinaryOperator::getOpcodeStr(CondOpcode),
5328 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005329
5330 SuggestParentheses(Self, OpLoc,
5331 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005332 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005333}
5334
Steve Narofff69936d2007-09-16 03:34:24 +00005335/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005336/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005337ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005338 SourceLocation ColonLoc,
5339 Expr *CondExpr, Expr *LHSExpr,
5340 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005341 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5342 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005343 OpaqueValueExpr *opaqueValue = 0;
5344 Expr *commonExpr = 0;
5345 if (LHSExpr == 0) {
5346 commonExpr = CondExpr;
5347
5348 // We usually want to apply unary conversions *before* saving, except
5349 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005350 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005351 && !commonExpr->isTypeDependent()
5352 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5353 && commonExpr->isGLValue()
5354 && commonExpr->isOrdinaryOrBitFieldObject()
5355 && RHSExpr->isOrdinaryOrBitFieldObject()
5356 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005357 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5358 if (commonRes.isInvalid())
5359 return ExprError();
5360 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005361 }
5362
5363 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5364 commonExpr->getType(),
5365 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005366 commonExpr->getObjectKind(),
5367 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005368 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005369 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005370
John McCallf89e55a2010-11-18 06:31:45 +00005371 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005372 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005373 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5374 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005375 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005376 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5377 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005378 return ExprError();
5379
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005380 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5381 RHS.get());
5382
John McCall56ca35d2011-02-17 10:25:35 +00005383 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005384 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5385 LHS.take(), ColonLoc,
5386 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005387
5388 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005389 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005390 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5391 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005392}
5393
John McCalle4be87e2011-01-31 23:13:11 +00005394// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005395// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005396// routine is it effectively iqnores the qualifiers on the top level pointee.
5397// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5398// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005399static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005400checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5401 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5402 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005403
Reid Spencer5f016e22007-07-11 17:01:13 +00005404 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005405 const Type *lhptee, *rhptee;
5406 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005407 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5408 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005409
John McCalle4be87e2011-01-31 23:13:11 +00005410 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005411
5412 // C99 6.5.16.1p1: This following citation is common to constraints
5413 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5414 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005415 Qualifiers lq;
5416
John McCallf85e1932011-06-15 23:02:42 +00005417 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5418 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5419 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5420 // Ignore lifetime for further calculation.
5421 lhq.removeObjCLifetime();
5422 rhq.removeObjCLifetime();
5423 }
5424
John McCall86c05f32011-02-01 00:10:29 +00005425 if (!lhq.compatiblyIncludes(rhq)) {
5426 // Treat address-space mismatches as fatal. TODO: address subspaces
5427 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5428 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5429
John McCallf85e1932011-06-15 23:02:42 +00005430 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005431 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005432 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005433 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005434 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005435 && (lhptee->isVoidType() || rhptee->isVoidType()))
5436 ; // keep old
5437
John McCallf85e1932011-06-15 23:02:42 +00005438 // Treat lifetime mismatches as fatal.
5439 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5440 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5441
John McCall86c05f32011-02-01 00:10:29 +00005442 // For GCC compatibility, other qualifier mismatches are treated
5443 // as still compatible in C.
5444 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005446
Mike Stumpeed9cac2009-02-19 03:04:26 +00005447 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5448 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005449 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005450 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005451 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005452 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005453
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005454 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005455 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005456 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005457 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005458
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005459 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005460 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005461 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005462
5463 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005464 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005465 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005466 }
John McCall86c05f32011-02-01 00:10:29 +00005467
Mike Stumpeed9cac2009-02-19 03:04:26 +00005468 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005469 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005470 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5471 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005472 // Check if the pointee types are compatible ignoring the sign.
5473 // We explicitly check for char so that we catch "char" vs
5474 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005475 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005476 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005477 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005478 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005479
Chris Lattner6a2b9262009-10-17 20:33:28 +00005480 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005481 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005482 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005483 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005484
John McCall86c05f32011-02-01 00:10:29 +00005485 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005486 // Types are compatible ignoring the sign. Qualifier incompatibility
5487 // takes priority over sign incompatibility because the sign
5488 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005489 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005490 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005491
John McCalle4be87e2011-01-31 23:13:11 +00005492 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005493 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005494
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005495 // If we are a multi-level pointer, it's possible that our issue is simply
5496 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5497 // the eventual target type is the same and the pointers have the same
5498 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005499 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005500 do {
John McCall86c05f32011-02-01 00:10:29 +00005501 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5502 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005503 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005504
John McCall86c05f32011-02-01 00:10:29 +00005505 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005506 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005507 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005508
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005509 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005510 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005511 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005512 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005513 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5514 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005515 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005516}
5517
John McCalle4be87e2011-01-31 23:13:11 +00005518/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005519/// block pointer types are compatible or whether a block and normal pointer
5520/// are compatible. It is more restrict than comparing two function pointer
5521// types.
John McCalle4be87e2011-01-31 23:13:11 +00005522static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005523checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5524 QualType RHSType) {
5525 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5526 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005527
Steve Naroff1c7d0672008-09-04 15:10:53 +00005528 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005529
Steve Naroff1c7d0672008-09-04 15:10:53 +00005530 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005531 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5532 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005533
John McCalle4be87e2011-01-31 23:13:11 +00005534 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005535 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005536 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005537
John McCalle4be87e2011-01-31 23:13:11 +00005538 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005539
Steve Naroff1c7d0672008-09-04 15:10:53 +00005540 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005541 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5542 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005543
Richard Trieu1da27a12011-09-06 20:21:22 +00005544 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005545 return Sema::IncompatibleBlockPointer;
5546
Steve Naroff1c7d0672008-09-04 15:10:53 +00005547 return ConvTy;
5548}
5549
John McCalle4be87e2011-01-31 23:13:11 +00005550/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005551/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005552static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005553checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5554 QualType RHSType) {
5555 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5556 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005557
Richard Trieu1da27a12011-09-06 20:21:22 +00005558 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005559 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005560 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5561 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005562 return Sema::IncompatiblePointer;
5563 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005564 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005565 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005566 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5567 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005568 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005569 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005570 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005571 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5572 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005573
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005574 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5575 // make an exception for id<P>
5576 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005577 return Sema::CompatiblePointerDiscardsQualifiers;
5578
Richard Trieu1da27a12011-09-06 20:21:22 +00005579 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005580 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005581 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005582 return Sema::IncompatibleObjCQualifiedId;
5583 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005584}
5585
John McCall1c23e912010-11-16 02:32:08 +00005586Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005587Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005588 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005589 // Fake up an opaque expression. We don't actually care about what
5590 // cast operations are required, so if CheckAssignmentConstraints
5591 // adds casts to this they'll be wasted, but fortunately that doesn't
5592 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005593 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5594 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005595 CastKind K = CK_Invalid;
5596
Richard Trieu1da27a12011-09-06 20:21:22 +00005597 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005598}
5599
Mike Stumpeed9cac2009-02-19 03:04:26 +00005600/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5601/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005602/// pointers. Here are some objectionable examples that GCC considers warnings:
5603///
5604/// int a, *pint;
5605/// short *pshort;
5606/// struct foo *pfoo;
5607///
5608/// pint = pshort; // warning: assignment from incompatible pointer type
5609/// a = pint; // warning: assignment makes integer from pointer without a cast
5610/// pint = a; // warning: assignment makes pointer from integer without a cast
5611/// pint = pfoo; // warning: assignment from incompatible pointer type
5612///
5613/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005614/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005615///
John McCalldaa8e4e2010-11-15 09:13:47 +00005616/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005617Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005618Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005619 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005620 QualType RHSType = RHS.get()->getType();
5621 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005622
Chris Lattnerfc144e22008-01-04 23:18:45 +00005623 // Get canonical types. We're not formatting these types, just comparing
5624 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005625 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5626 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005627
Eli Friedmanb001de72011-10-06 23:00:33 +00005628
John McCallb6cfa242011-01-31 22:28:28 +00005629 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005630 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005631 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005632 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005633 }
5634
Eli Friedman860a3192012-06-16 02:19:17 +00005635 // If we have an atomic type, try a non-atomic assignment, then just add an
5636 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005637 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005638 Sema::AssignConvertType result =
5639 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5640 if (result != Compatible)
5641 return result;
5642 if (Kind != CK_NoOp)
5643 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5644 Kind = CK_NonAtomicToAtomic;
5645 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005646 }
5647
Douglas Gregor9d293df2008-10-28 00:22:11 +00005648 // If the left-hand side is a reference type, then we are in a
5649 // (rare!) case where we've allowed the use of references in C,
5650 // e.g., as a parameter type in a built-in function. In this case,
5651 // just make sure that the type referenced is compatible with the
5652 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005653 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005654 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005655 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5656 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005657 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005658 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005659 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005660 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005661 }
John McCallb6cfa242011-01-31 22:28:28 +00005662
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005663 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5664 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005665 if (LHSType->isExtVectorType()) {
5666 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005667 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005668 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005669 // CK_VectorSplat does T -> vector T, so first cast to the
5670 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005671 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5672 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005673 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005674 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005675 }
5676 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005677 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005678 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005679 }
Mike Stump1eb44332009-09-09 15:08:12 +00005680
John McCallb6cfa242011-01-31 22:28:28 +00005681 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005682 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5683 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005684 // Allow assignments of an AltiVec vector type to an equivalent GCC
5685 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005686 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005687 Kind = CK_BitCast;
5688 return Compatible;
5689 }
5690
Douglas Gregor255210e2010-08-06 10:14:59 +00005691 // If we are allowing lax vector conversions, and LHS and RHS are both
5692 // vectors, the total size only needs to be the same. This is a bitcast;
5693 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005694 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005695 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005696 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005697 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005698 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005699 }
5700 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005701 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005702
John McCallb6cfa242011-01-31 22:28:28 +00005703 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005704 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005705 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005706 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005707 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005708 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005709
John McCallb6cfa242011-01-31 22:28:28 +00005710 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005711 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005712 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005713 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005714 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005715 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005716 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005717
John McCallb6cfa242011-01-31 22:28:28 +00005718 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005719 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005720 Kind = CK_IntegralToPointer; // FIXME: null?
5721 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005722 }
John McCallb6cfa242011-01-31 22:28:28 +00005723
5724 // C pointers are not compatible with ObjC object pointers,
5725 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005726 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005727 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005728 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005729 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005730 return Compatible;
5731 }
5732
5733 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005734 if (RHSType->isObjCClassType() &&
5735 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005736 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005737 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005738 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005739 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005740
John McCallb6cfa242011-01-31 22:28:28 +00005741 Kind = CK_BitCast;
5742 return IncompatiblePointer;
5743 }
5744
5745 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005746 if (RHSType->getAs<BlockPointerType>()) {
5747 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005748 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005749 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005750 }
Steve Naroffb4406862008-09-29 18:10:17 +00005751 }
John McCallb6cfa242011-01-31 22:28:28 +00005752
Steve Naroff1c7d0672008-09-04 15:10:53 +00005753 return Incompatible;
5754 }
5755
John McCallb6cfa242011-01-31 22:28:28 +00005756 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005757 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005758 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005759 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005760 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005761 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005762 }
5763
5764 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005765 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005766 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005767 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005768 }
5769
John McCallb6cfa242011-01-31 22:28:28 +00005770 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005771 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005772 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005773 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005774 }
Steve Naroffb4406862008-09-29 18:10:17 +00005775
John McCallb6cfa242011-01-31 22:28:28 +00005776 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005777 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005778 if (RHSPT->getPointeeType()->isVoidType()) {
5779 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005780 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005781 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005782
Chris Lattnerfc144e22008-01-04 23:18:45 +00005783 return Incompatible;
5784 }
5785
John McCallb6cfa242011-01-31 22:28:28 +00005786 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005787 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005788 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005789 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005790 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005791 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005792 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005793 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005794 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005795 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005796 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005797 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005798 }
5799
5800 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005801 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005802 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005803 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005804 }
5805
John McCallb6cfa242011-01-31 22:28:28 +00005806 // In general, C pointers are not compatible with ObjC object pointers,
5807 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005808 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005809 Kind = CK_CPointerToObjCPointerCast;
5810
John McCallb6cfa242011-01-31 22:28:28 +00005811 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005812 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005813 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005814 }
5815
5816 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005817 if (LHSType->isObjCClassType() &&
5818 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005819 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005820 return Compatible;
5821 }
5822
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005823 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005824 }
John McCallb6cfa242011-01-31 22:28:28 +00005825
5826 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005827 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005828 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005829 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005830 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005831 }
5832
Steve Naroff14108da2009-07-10 23:34:53 +00005833 return Incompatible;
5834 }
John McCallb6cfa242011-01-31 22:28:28 +00005835
5836 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005837 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005838 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005839 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005840 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005841 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005842 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005843
John McCallb6cfa242011-01-31 22:28:28 +00005844 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005845 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005846 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005847 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005848 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005849
Chris Lattnerfc144e22008-01-04 23:18:45 +00005850 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005851 }
John McCallb6cfa242011-01-31 22:28:28 +00005852
5853 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005854 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005855 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005856 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005857 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005858 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005859 }
Steve Naroff14108da2009-07-10 23:34:53 +00005860
John McCallb6cfa242011-01-31 22:28:28 +00005861 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005862 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005863 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005864 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005865 }
5866
Steve Naroff14108da2009-07-10 23:34:53 +00005867 return Incompatible;
5868 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005869
John McCallb6cfa242011-01-31 22:28:28 +00005870 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005871 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5872 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005873 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005874 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005875 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005876 }
John McCallb6cfa242011-01-31 22:28:28 +00005877
Reid Spencer5f016e22007-07-11 17:01:13 +00005878 return Incompatible;
5879}
5880
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005881/// \brief Constructs a transparent union from an expression that is
5882/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005883static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5884 ExprResult &EResult, QualType UnionType,
5885 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005886 // Build an initializer list that designates the appropriate member
5887 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005888 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005889 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005890 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005891 Initializer->setType(UnionType);
5892 Initializer->setInitializedFieldInUnion(Field);
5893
5894 // Build a compound literal constructing a value of the transparent
5895 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005896 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005897 EResult = S.Owned(
5898 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5899 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005900}
5901
5902Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005903Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005904 ExprResult &RHS) {
5905 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005906
Mike Stump1eb44332009-09-09 15:08:12 +00005907 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005908 // transparent_union GCC extension.
5909 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005910 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005911 return Incompatible;
5912
5913 // The field to initialize within the transparent union.
5914 RecordDecl *UD = UT->getDecl();
5915 FieldDecl *InitField = 0;
5916 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005917 for (RecordDecl::field_iterator it = UD->field_begin(),
5918 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005919 it != itend; ++it) {
5920 if (it->getType()->isPointerType()) {
5921 // If the transparent union contains a pointer type, we allow:
5922 // 1) void pointer
5923 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005924 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005925 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005926 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005927 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005928 break;
5929 }
Mike Stump1eb44332009-09-09 15:08:12 +00005930
Richard Trieuf7720da2011-09-06 20:40:12 +00005931 if (RHS.get()->isNullPointerConstant(Context,
5932 Expr::NPC_ValueDependentIsNull)) {
5933 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5934 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005935 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005936 break;
5937 }
5938 }
5939
John McCalldaa8e4e2010-11-15 09:13:47 +00005940 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005941 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005942 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005943 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005944 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005945 break;
5946 }
5947 }
5948
5949 if (!InitField)
5950 return Incompatible;
5951
Richard Trieuf7720da2011-09-06 20:40:12 +00005952 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005953 return Compatible;
5954}
5955
Chris Lattner5cf216b2008-01-04 18:04:52 +00005956Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005957Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5958 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005959 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005960 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005961 // C++ 5.17p3: If the left operand is not of class type, the
5962 // expression is implicitly converted (C++ 4) to the
5963 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005964 ExprResult Res;
5965 if (Diagnose) {
5966 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5967 AA_Assigning);
5968 } else {
5969 ImplicitConversionSequence ICS =
5970 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5971 /*SuppressUserConversions=*/false,
5972 /*AllowExplicit=*/false,
5973 /*InOverloadResolution=*/false,
5974 /*CStyle=*/false,
5975 /*AllowObjCWritebackConversion=*/false);
5976 if (ICS.isFailure())
5977 return Incompatible;
5978 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5979 ICS, AA_Assigning);
5980 }
John Wiegley429bb272011-04-08 18:41:53 +00005981 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005982 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005983 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005984 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005985 !CheckObjCARCUnavailableWeakConversion(LHSType,
5986 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005987 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005988 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005989 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005990 }
5991
5992 // FIXME: Currently, we fall through and treat C++ classes like C
5993 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005994 // FIXME: We also fall through for atomics; not sure what should
5995 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005996 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005997
Steve Naroff529a4ad2007-11-27 17:58:44 +00005998 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5999 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00006000 if ((LHSType->isPointerType() ||
6001 LHSType->isObjCObjectPointerType() ||
6002 LHSType->isBlockPointerType())
6003 && RHS.get()->isNullPointerConstant(Context,
6004 Expr::NPC_ValueDependentIsNull)) {
6005 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006006 return Compatible;
6007 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006008
Chris Lattner943140e2007-10-16 02:55:40 +00006009 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006010 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006011 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006012 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006013 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006014 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006015 if (!LHSType->isReferenceType()) {
6016 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6017 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006018 return Incompatible;
6019 }
Steve Narofff1120de2007-08-24 22:33:52 +00006020
John McCalldaa8e4e2010-11-15 09:13:47 +00006021 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006022 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006023 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006024
Steve Narofff1120de2007-08-24 22:33:52 +00006025 // C99 6.5.16.1p2: The value of the right operand is converted to the
6026 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006027 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6028 // so that we can use references in built-in functions even in C.
6029 // The getNonReferenceType() call makes sure that the resulting expression
6030 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006031 if (result != Incompatible && RHS.get()->getType() != LHSType)
6032 RHS = ImpCastExprToType(RHS.take(),
6033 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006034 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006035}
6036
Richard Trieuf7720da2011-09-06 20:40:12 +00006037QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6038 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006039 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006040 << LHS.get()->getType() << RHS.get()->getType()
6041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006042 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006043}
6044
Richard Trieu08062aa2011-09-06 21:01:04 +00006045QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006046 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006047 if (!IsCompAssign) {
6048 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6049 if (LHS.isInvalid())
6050 return QualType();
6051 }
6052 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6053 if (RHS.isInvalid())
6054 return QualType();
6055
Mike Stumpeed9cac2009-02-19 03:04:26 +00006056 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006057 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006058 QualType LHSType =
6059 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6060 QualType RHSType =
6061 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006062
Nate Begemanbe2341d2008-07-14 18:02:46 +00006063 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006064 if (LHSType == RHSType)
6065 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006066
Douglas Gregor255210e2010-08-06 10:14:59 +00006067 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006068 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6069 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6070 if (LHSType->isExtVectorType()) {
6071 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6072 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006073 }
6074
Richard Trieuccd891a2011-09-09 01:45:06 +00006075 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006076 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6077 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006078 }
6079
David Blaikie4e4d0842012-03-11 07:00:24 +00006080 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006081 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006082 // If we are allowing lax vector conversions, and LHS and RHS are both
6083 // vectors, the total size only needs to be the same. This is a
6084 // bitcast; no bits are changed but the result type is different.
6085 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006086 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6087 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006088 }
6089
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006090 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6091 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6092 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006093 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006094 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006095 std::swap(RHS, LHS);
6096 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006097 }
Mike Stump1eb44332009-09-09 15:08:12 +00006098
Nate Begemandde25982009-06-28 19:12:57 +00006099 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006100 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006101 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006102 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6103 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006104 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006105 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006106 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006107 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6108 if (swapped) std::swap(RHS, LHS);
6109 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006110 }
6111 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6113 RHSType->isRealFloatingType()) {
6114 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006115 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006116 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006117 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006118 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6119 if (swapped) std::swap(RHS, LHS);
6120 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006121 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006122 }
6123 }
Mike Stump1eb44332009-09-09 15:08:12 +00006124
Nate Begemandde25982009-06-28 19:12:57 +00006125 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006126 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006127 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006128 << LHS.get()->getType() << RHS.get()->getType()
6129 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006130 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006131}
6132
Richard Trieu481037f2011-09-16 00:53:10 +00006133// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6134// expression. These are mainly cases where the null pointer is used as an
6135// integer instead of a pointer.
6136static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6137 SourceLocation Loc, bool IsCompare) {
6138 // The canonical way to check for a GNU null is with isNullPointerConstant,
6139 // but we use a bit of a hack here for speed; this is a relatively
6140 // hot path, and isNullPointerConstant is slow.
6141 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6142 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6143
6144 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6145
6146 // Avoid analyzing cases where the result will either be invalid (and
6147 // diagnosed as such) or entirely valid and not something to warn about.
6148 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6149 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6150 return;
6151
6152 // Comparison operations would not make sense with a null pointer no matter
6153 // what the other expression is.
6154 if (!IsCompare) {
6155 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6156 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6157 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6158 return;
6159 }
6160
6161 // The rest of the operations only make sense with a null pointer
6162 // if the other expression is a pointer.
6163 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6164 NonNullType->canDecayToPointerType())
6165 return;
6166
6167 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6168 << LHSNull /* LHS is NULL */ << NonNullType
6169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6170}
6171
Richard Trieu08062aa2011-09-06 21:01:04 +00006172QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006173 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006174 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006175 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6176
Richard Trieu08062aa2011-09-06 21:01:04 +00006177 if (LHS.get()->getType()->isVectorType() ||
6178 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006179 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006180
Richard Trieuccd891a2011-09-09 01:45:06 +00006181 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006182 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006183 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006184
David Chisnall7a7ee302012-01-16 17:27:18 +00006185
Eli Friedman860a3192012-06-16 02:19:17 +00006186 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006187 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006188
Chris Lattner7ef655a2010-01-12 21:23:57 +00006189 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006190 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006191 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006192 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006193 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6194 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006195
Chris Lattner7ef655a2010-01-12 21:23:57 +00006196 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006197}
6198
Chris Lattner7ef655a2010-01-12 21:23:57 +00006199QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006200 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006201 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6202
Richard Trieu08062aa2011-09-06 21:01:04 +00006203 if (LHS.get()->getType()->isVectorType() ||
6204 RHS.get()->getType()->isVectorType()) {
6205 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6206 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006207 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006208 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006209 }
Steve Naroff90045e82007-07-13 23:32:42 +00006210
Richard Trieuccd891a2011-09-09 01:45:06 +00006211 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006212 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006213 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006214
Eli Friedman860a3192012-06-16 02:19:17 +00006215 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006216 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006217
Chris Lattner7ef655a2010-01-12 21:23:57 +00006218 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006219 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006220 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006221 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6222 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006223
Chris Lattner7ef655a2010-01-12 21:23:57 +00006224 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006225}
6226
Chandler Carruth13b21be2011-06-27 08:02:19 +00006227/// \brief Diagnose invalid arithmetic on two void pointers.
6228static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006229 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006230 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006231 ? diag::err_typecheck_pointer_arith_void_type
6232 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006233 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6234 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006235}
6236
6237/// \brief Diagnose invalid arithmetic on a void pointer.
6238static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6239 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006240 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006241 ? diag::err_typecheck_pointer_arith_void_type
6242 : diag::ext_gnu_void_ptr)
6243 << 0 /* one pointer */ << Pointer->getSourceRange();
6244}
6245
6246/// \brief Diagnose invalid arithmetic on two function pointers.
6247static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6248 Expr *LHS, Expr *RHS) {
6249 assert(LHS->getType()->isAnyPointerType());
6250 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006251 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006252 ? diag::err_typecheck_pointer_arith_function_type
6253 : diag::ext_gnu_ptr_func_arith)
6254 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6255 // We only show the second type if it differs from the first.
6256 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6257 RHS->getType())
6258 << RHS->getType()->getPointeeType()
6259 << LHS->getSourceRange() << RHS->getSourceRange();
6260}
6261
6262/// \brief Diagnose invalid arithmetic on a function pointer.
6263static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6264 Expr *Pointer) {
6265 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006266 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006267 ? diag::err_typecheck_pointer_arith_function_type
6268 : diag::ext_gnu_ptr_func_arith)
6269 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6270 << 0 /* one pointer, so only one type */
6271 << Pointer->getSourceRange();
6272}
6273
Richard Trieud9f19342011-09-12 18:08:02 +00006274/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006275///
6276/// \returns True if pointer has incomplete type
6277static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6278 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006279 assert(Operand->getType()->isAnyPointerType() &&
6280 !Operand->getType()->isDependentType());
6281 QualType PointeeTy = Operand->getType()->getPointeeType();
6282 return S.RequireCompleteType(Loc, PointeeTy,
6283 diag::err_typecheck_arithmetic_incomplete_type,
6284 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006285}
6286
Chandler Carruth13b21be2011-06-27 08:02:19 +00006287/// \brief Check the validity of an arithmetic pointer operand.
6288///
6289/// If the operand has pointer type, this code will check for pointer types
6290/// which are invalid in arithmetic operations. These will be diagnosed
6291/// appropriately, including whether or not the use is supported as an
6292/// extension.
6293///
6294/// \returns True when the operand is valid to use (even if as an extension).
6295static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6296 Expr *Operand) {
6297 if (!Operand->getType()->isAnyPointerType()) return true;
6298
6299 QualType PointeeTy = Operand->getType()->getPointeeType();
6300 if (PointeeTy->isVoidType()) {
6301 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006302 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006303 }
6304 if (PointeeTy->isFunctionType()) {
6305 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006306 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006307 }
6308
Richard Trieu097ecd22011-09-02 02:15:37 +00006309 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006310
6311 return true;
6312}
6313
6314/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6315/// operands.
6316///
6317/// This routine will diagnose any invalid arithmetic on pointer operands much
6318/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6319/// for emitting a single diagnostic even for operations where both LHS and RHS
6320/// are (potentially problematic) pointers.
6321///
6322/// \returns True when the operand is valid to use (even if as an extension).
6323static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006324 Expr *LHSExpr, Expr *RHSExpr) {
6325 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6326 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006327 if (!isLHSPointer && !isRHSPointer) return true;
6328
6329 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006330 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6331 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006332
6333 // Check for arithmetic on pointers to incomplete types.
6334 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6335 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6336 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006337 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6338 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6339 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006340
David Blaikie4e4d0842012-03-11 07:00:24 +00006341 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006342 }
6343
6344 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6345 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6346 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006347 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6348 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6349 RHSExpr);
6350 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006351
David Blaikie4e4d0842012-03-11 07:00:24 +00006352 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006353 }
6354
John McCall1503f0d2012-07-31 05:14:30 +00006355 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6356 return false;
6357 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6358 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006359
Chandler Carruth13b21be2011-06-27 08:02:19 +00006360 return true;
6361}
6362
Nico Weber1cb2d742012-03-02 22:01:22 +00006363/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6364/// literal.
6365static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6366 Expr *LHSExpr, Expr *RHSExpr) {
6367 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6368 Expr* IndexExpr = RHSExpr;
6369 if (!StrExpr) {
6370 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6371 IndexExpr = LHSExpr;
6372 }
6373
6374 bool IsStringPlusInt = StrExpr &&
6375 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6376 if (!IsStringPlusInt)
6377 return;
6378
6379 llvm::APSInt index;
6380 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6381 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6382 if (index.isNonNegative() &&
6383 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6384 index.isUnsigned()))
6385 return;
6386 }
6387
6388 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6389 Self.Diag(OpLoc, diag::warn_string_plus_int)
6390 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6391
6392 // Only print a fixit for "str" + int, not for int + "str".
6393 if (IndexExpr == RHSExpr) {
6394 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6395 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6396 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6397 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6398 << FixItHint::CreateInsertion(EndLoc, "]");
6399 } else
6400 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6401}
6402
Richard Trieud9f19342011-09-12 18:08:02 +00006403/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006404static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006405 Expr *LHSExpr, Expr *RHSExpr) {
6406 assert(LHSExpr->getType()->isAnyPointerType());
6407 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006408 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006409 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6410 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006411}
6412
Chris Lattner7ef655a2010-01-12 21:23:57 +00006413QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006414 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6415 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006416 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6417
Richard Trieudef75842011-09-06 21:13:51 +00006418 if (LHS.get()->getType()->isVectorType() ||
6419 RHS.get()->getType()->isVectorType()) {
6420 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006421 if (CompLHSTy) *CompLHSTy = compType;
6422 return compType;
6423 }
Steve Naroff49b45262007-07-13 16:58:59 +00006424
Richard Trieudef75842011-09-06 21:13:51 +00006425 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6426 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006427 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006428
Nico Weber1cb2d742012-03-02 22:01:22 +00006429 // Diagnose "string literal" '+' int.
6430 if (Opc == BO_Add)
6431 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6432
Reid Spencer5f016e22007-07-11 17:01:13 +00006433 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006434 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006435 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006436 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006437 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006438
John McCall1503f0d2012-07-31 05:14:30 +00006439 // Type-checking. Ultimately the pointer's going to be in PExp;
6440 // note that we bias towards the LHS being the pointer.
6441 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006442
John McCall1503f0d2012-07-31 05:14:30 +00006443 bool isObjCPointer;
6444 if (PExp->getType()->isPointerType()) {
6445 isObjCPointer = false;
6446 } else if (PExp->getType()->isObjCObjectPointerType()) {
6447 isObjCPointer = true;
6448 } else {
6449 std::swap(PExp, IExp);
6450 if (PExp->getType()->isPointerType()) {
6451 isObjCPointer = false;
6452 } else if (PExp->getType()->isObjCObjectPointerType()) {
6453 isObjCPointer = true;
6454 } else {
6455 return InvalidOperands(Loc, LHS, RHS);
6456 }
6457 }
6458 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006459
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006460 if (!IExp->getType()->isIntegerType())
6461 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006462
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006463 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6464 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006465
John McCall1503f0d2012-07-31 05:14:30 +00006466 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006467 return QualType();
6468
6469 // Check array bounds for pointer arithemtic
6470 CheckArrayAccess(PExp, IExp);
6471
6472 if (CompLHSTy) {
6473 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6474 if (LHSTy.isNull()) {
6475 LHSTy = LHS.get()->getType();
6476 if (LHSTy->isPromotableIntegerType())
6477 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006478 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006479 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006480 }
6481
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006482 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006483}
6484
Chris Lattnereca7be62008-04-07 05:30:13 +00006485// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006486QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006487 SourceLocation Loc,
6488 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006489 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6490
Richard Trieudef75842011-09-06 21:13:51 +00006491 if (LHS.get()->getType()->isVectorType() ||
6492 RHS.get()->getType()->isVectorType()) {
6493 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006494 if (CompLHSTy) *CompLHSTy = compType;
6495 return compType;
6496 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006497
Richard Trieudef75842011-09-06 21:13:51 +00006498 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6499 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006500 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006501
Chris Lattner6e4ab612007-12-09 21:53:25 +00006502 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006503
Chris Lattner6e4ab612007-12-09 21:53:25 +00006504 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006505 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006506 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006507 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006508 }
Mike Stump1eb44332009-09-09 15:08:12 +00006509
Chris Lattner6e4ab612007-12-09 21:53:25 +00006510 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006511 if (LHS.get()->getType()->isAnyPointerType()) {
6512 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006513
Chris Lattnerb5f15622009-04-24 23:50:08 +00006514 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006515 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6516 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006517 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006518
Chris Lattner6e4ab612007-12-09 21:53:25 +00006519 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006520 if (RHS.get()->getType()->isIntegerType()) {
6521 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006522 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006523
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006524 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006525 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6526 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006527
Richard Trieudef75842011-09-06 21:13:51 +00006528 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6529 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006530 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006531
Chris Lattner6e4ab612007-12-09 21:53:25 +00006532 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006533 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006534 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006535 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006536
David Blaikie4e4d0842012-03-11 07:00:24 +00006537 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006538 // Pointee types must be the same: C++ [expr.add]
6539 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006540 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006541 }
6542 } else {
6543 // Pointee types must be compatible C99 6.5.6p3
6544 if (!Context.typesAreCompatible(
6545 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6546 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006547 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006548 return QualType();
6549 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006550 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006551
Chandler Carruth13b21be2011-06-27 08:02:19 +00006552 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006553 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006554 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006555
Richard Trieudef75842011-09-06 21:13:51 +00006556 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006557 return Context.getPointerDiffType();
6558 }
6559 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Richard Trieudef75842011-09-06 21:13:51 +00006561 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006562}
6563
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006564static bool isScopedEnumerationType(QualType T) {
6565 if (const EnumType *ET = dyn_cast<EnumType>(T))
6566 return ET->getDecl()->isScoped();
6567 return false;
6568}
6569
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006570static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006571 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006572 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006573 llvm::APSInt Right;
6574 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006575 if (RHS.get()->isValueDependent() ||
6576 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006577 return;
6578
6579 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006580 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006581 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006582 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006583 return;
6584 }
6585 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006586 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006587 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006588 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006589 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006590 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006591 return;
6592 }
6593 if (Opc != BO_Shl)
6594 return;
6595
6596 // When left shifting an ICE which is signed, we can check for overflow which
6597 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6598 // integers have defined behavior modulo one more than the maximum value
6599 // representable in the result type, so never warn for those.
6600 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006601 if (LHS.get()->isValueDependent() ||
6602 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6603 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006604 return;
6605 llvm::APInt ResultBits =
6606 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6607 if (LeftBits.uge(ResultBits))
6608 return;
6609 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6610 Result = Result.shl(Right);
6611
Ted Kremenekfa821382011-06-15 00:54:52 +00006612 // Print the bit representation of the signed integer as an unsigned
6613 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006614 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006615 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6616
Chandler Carruth21206d52011-02-23 23:34:11 +00006617 // If we are only missing a sign bit, this is less likely to result in actual
6618 // bugs -- if the result is cast back to an unsigned type, it will have the
6619 // expected value. Thus we place this behind a different warning that can be
6620 // turned off separately if needed.
6621 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006622 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006623 << HexResult.str() << LHSType
6624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006625 return;
6626 }
6627
6628 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006629 << HexResult.str() << Result.getMinSignedBits() << LHSType
6630 << Left.getBitWidth() << LHS.get()->getSourceRange()
6631 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006632}
6633
Chris Lattnereca7be62008-04-07 05:30:13 +00006634// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006635QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006636 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006637 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006638 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6639
Chris Lattnerca5eede2007-12-12 05:47:28 +00006640 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006641 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6642 !RHS.get()->getType()->hasIntegerRepresentation())
6643 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006644
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006645 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6646 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006647 if (isScopedEnumerationType(LHS.get()->getType()) ||
6648 isScopedEnumerationType(RHS.get()->getType())) {
6649 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006650 }
6651
Nate Begeman2207d792009-10-25 02:26:48 +00006652 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006653 if (LHS.get()->getType()->isVectorType() ||
6654 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006655 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006656
Chris Lattnerca5eede2007-12-12 05:47:28 +00006657 // Shifts don't perform usual arithmetic conversions, they just do integer
6658 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006659
John McCall1bc80af2010-12-16 19:28:59 +00006660 // For the LHS, do usual unary conversions, but then reset them away
6661 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006662 ExprResult OldLHS = LHS;
6663 LHS = UsualUnaryConversions(LHS.take());
6664 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006665 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006666 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006667 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006668
6669 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006670 RHS = UsualUnaryConversions(RHS.take());
6671 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006672 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006673
Ryan Flynnd0439682009-08-07 16:20:20 +00006674 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006675 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006676
Chris Lattnerca5eede2007-12-12 05:47:28 +00006677 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006678 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006679}
6680
Chandler Carruth99919472010-07-10 12:30:03 +00006681static bool IsWithinTemplateSpecialization(Decl *D) {
6682 if (DeclContext *DC = D->getDeclContext()) {
6683 if (isa<ClassTemplateSpecializationDecl>(DC))
6684 return true;
6685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6686 return FD->isFunctionTemplateSpecialization();
6687 }
6688 return false;
6689}
6690
Richard Trieue648ac32011-09-02 03:48:46 +00006691/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006692static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6693 ExprResult &RHS) {
6694 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6695 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006696
6697 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6698 if (!LHSEnumType)
6699 return;
6700 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6701 if (!RHSEnumType)
6702 return;
6703
6704 // Ignore anonymous enums.
6705 if (!LHSEnumType->getDecl()->getIdentifier())
6706 return;
6707 if (!RHSEnumType->getDecl()->getIdentifier())
6708 return;
6709
6710 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6711 return;
6712
6713 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6714 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006715 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006716}
6717
Richard Trieu7be1be02011-09-02 02:55:45 +00006718/// \brief Diagnose bad pointer comparisons.
6719static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006720 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006721 bool IsError) {
6722 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006723 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006724 << LHS.get()->getType() << RHS.get()->getType()
6725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006726}
6727
6728/// \brief Returns false if the pointers are converted to a composite type,
6729/// true otherwise.
6730static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006731 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006732 // C++ [expr.rel]p2:
6733 // [...] Pointer conversions (4.10) and qualification
6734 // conversions (4.4) are performed on pointer operands (or on
6735 // a pointer operand and a null pointer constant) to bring
6736 // them to their composite pointer type. [...]
6737 //
6738 // C++ [expr.eq]p1 uses the same notion for (in)equality
6739 // comparisons of pointers.
6740
6741 // C++ [expr.eq]p2:
6742 // In addition, pointers to members can be compared, or a pointer to
6743 // member and a null pointer constant. Pointer to member conversions
6744 // (4.11) and qualification conversions (4.4) are performed to bring
6745 // them to a common type. If one operand is a null pointer constant,
6746 // the common type is the type of the other operand. Otherwise, the
6747 // common type is a pointer to member type similar (4.4) to the type
6748 // of one of the operands, with a cv-qualification signature (4.4)
6749 // that is the union of the cv-qualification signatures of the operand
6750 // types.
6751
Richard Trieuba261492011-09-06 21:27:33 +00006752 QualType LHSType = LHS.get()->getType();
6753 QualType RHSType = RHS.get()->getType();
6754 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6755 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006756
6757 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006758 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006759 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006760 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006761 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006762 return true;
6763 }
6764
6765 if (NonStandardCompositeType)
6766 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006767 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6768 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006769
Richard Trieuba261492011-09-06 21:27:33 +00006770 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6771 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006772 return false;
6773}
6774
6775static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006776 ExprResult &LHS,
6777 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006778 bool IsError) {
6779 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6780 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006781 << LHS.get()->getType() << RHS.get()->getType()
6782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006783}
6784
Jordan Rose9f63a452012-06-08 21:14:25 +00006785static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rose87da0b72012-11-09 23:55:21 +00006786 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rose9f63a452012-06-08 21:14:25 +00006787 case Stmt::ObjCArrayLiteralClass:
6788 case Stmt::ObjCDictionaryLiteralClass:
6789 case Stmt::ObjCStringLiteralClass:
6790 case Stmt::ObjCBoxedExprClass:
6791 return true;
6792 default:
6793 // Note that ObjCBoolLiteral is NOT an object literal!
6794 return false;
6795 }
6796}
6797
Jordan Rose8d872ca2012-07-17 17:46:40 +00006798static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6799 // Get the LHS object's interface type.
6800 QualType Type = LHS->getType();
6801 QualType InterfaceType;
6802 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6803 InterfaceType = PTy->getPointeeType();
6804 if (const ObjCObjectType *iQFaceTy =
6805 InterfaceType->getAsObjCQualifiedInterfaceType())
6806 InterfaceType = iQFaceTy->getBaseType();
6807 } else {
6808 // If this is not actually an Objective-C object, bail out.
6809 return false;
6810 }
6811
6812 // If the RHS isn't an Objective-C object, bail out.
6813 if (!RHS->getType()->isObjCObjectPointerType())
6814 return false;
6815
6816 // Try to find the -isEqual: method.
6817 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6818 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6819 InterfaceType,
6820 /*instance=*/true);
6821 if (!Method) {
6822 if (Type->isObjCIdType()) {
6823 // For 'id', just check the global pool.
6824 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6825 /*receiverId=*/true,
6826 /*warn=*/false);
6827 } else {
6828 // Check protocols.
6829 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6830 cast<ObjCObjectPointerType>(Type),
6831 /*instance=*/true);
6832 }
6833 }
6834
6835 if (!Method)
6836 return false;
6837
6838 QualType T = Method->param_begin()[0]->getType();
6839 if (!T->isObjCObjectPointerType())
6840 return false;
6841
6842 QualType R = Method->getResultType();
6843 if (!R->isScalarType())
6844 return false;
6845
6846 return true;
6847}
6848
6849static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6850 ExprResult &LHS, ExprResult &RHS,
6851 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006852 Expr *Literal;
6853 Expr *Other;
6854 if (isObjCObjectLiteral(LHS)) {
6855 Literal = LHS.get();
6856 Other = RHS.get();
6857 } else {
6858 Literal = RHS.get();
6859 Other = LHS.get();
6860 }
6861
6862 // Don't warn on comparisons against nil.
6863 Other = Other->IgnoreParenCasts();
6864 if (Other->isNullPointerConstant(S.getASTContext(),
6865 Expr::NPC_ValueDependentIsNotNull))
6866 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006867
Jordan Roseeec207f2012-07-17 17:46:44 +00006868 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006869 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006870 enum {
6871 LK_Array,
6872 LK_Dictionary,
6873 LK_Numeric,
6874 LK_Boxed,
6875 LK_String
6876 } LiteralKind;
6877
Jordan Rose87da0b72012-11-09 23:55:21 +00006878 Literal = Literal->IgnoreParenImpCasts();
Jordan Rose9f63a452012-06-08 21:14:25 +00006879 switch (Literal->getStmtClass()) {
6880 case Stmt::ObjCStringLiteralClass:
6881 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006882 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006883 break;
6884 case Stmt::ObjCArrayLiteralClass:
6885 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006886 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006887 break;
6888 case Stmt::ObjCDictionaryLiteralClass:
6889 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006890 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006891 break;
6892 case Stmt::ObjCBoxedExprClass: {
6893 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6894 switch (Inner->getStmtClass()) {
6895 case Stmt::IntegerLiteralClass:
6896 case Stmt::FloatingLiteralClass:
6897 case Stmt::CharacterLiteralClass:
6898 case Stmt::ObjCBoolLiteralExprClass:
6899 case Stmt::CXXBoolLiteralExprClass:
6900 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006901 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006902 break;
6903 case Stmt::ImplicitCastExprClass: {
6904 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6905 // Boolean literals can be represented by implicit casts.
6906 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006907 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006908 break;
6909 }
6910 // FALLTHROUGH
6911 }
6912 default:
6913 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006914 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006915 break;
6916 }
6917 break;
6918 }
6919 default:
6920 llvm_unreachable("Unknown Objective-C object literal kind");
6921 }
6922
Jordan Roseeec207f2012-07-17 17:46:44 +00006923 if (LiteralKind == LK_String)
6924 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6925 << Literal->getSourceRange();
6926 else
6927 S.Diag(Loc, diag::warn_objc_literal_comparison)
6928 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006929
Jordan Rose8d872ca2012-07-17 17:46:40 +00006930 if (BinaryOperator::isEqualityOp(Opc) &&
6931 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6932 SourceLocation Start = LHS.get()->getLocStart();
6933 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6934 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006935
Jordan Rose8d872ca2012-07-17 17:46:40 +00006936 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6937 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6938 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6939 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006940 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006941}
6942
Douglas Gregor0c6db942009-05-04 06:07:12 +00006943// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006944QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006945 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006946 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006947 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6948
John McCall2de56d12010-08-25 11:45:40 +00006949 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006950
Chris Lattner02dd4b12009-12-05 05:40:13 +00006951 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006952 if (LHS.get()->getType()->isVectorType() ||
6953 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006954 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006955
Richard Trieuf1775fb2011-09-06 21:43:51 +00006956 QualType LHSType = LHS.get()->getType();
6957 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006958
Richard Trieuf1775fb2011-09-06 21:43:51 +00006959 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6960 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006961
Richard Trieuf1775fb2011-09-06 21:43:51 +00006962 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006963
Richard Trieuf1775fb2011-09-06 21:43:51 +00006964 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006965 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006966 !LHS.get()->getLocStart().isMacroID() &&
6967 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006968 // For non-floating point types, check for self-comparisons of the form
6969 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6970 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006971 //
6972 // NOTE: Don't warn about comparison expressions resulting from macro
6973 // expansion. Also don't warn about comparisons which are only self
6974 // comparisons within a template specialization. The warnings should catch
6975 // obvious cases in the definition of the template anyways. The idea is to
6976 // warn when the typed comparison operator will always evaluate to the same
6977 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006978 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006979 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006980 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006981 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006982 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006983 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006984 << (Opc == BO_EQ
6985 || Opc == BO_LE
6986 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006987 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006988 !DRL->getDecl()->getType()->isReferenceType() &&
6989 !DRR->getDecl()->getType()->isReferenceType()) {
6990 // what is it always going to eval to?
6991 char always_evals_to;
6992 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006993 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006994 always_evals_to = 0; // false
6995 break;
John McCall2de56d12010-08-25 11:45:40 +00006996 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006997 always_evals_to = 1; // true
6998 break;
6999 default:
7000 // best we can say is 'a constant'
7001 always_evals_to = 2; // e.g. array1 <= array2
7002 break;
7003 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007004 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007005 << 1 // array
7006 << always_evals_to);
7007 }
7008 }
Chandler Carruth99919472010-07-10 12:30:03 +00007009 }
Mike Stump1eb44332009-09-09 15:08:12 +00007010
Chris Lattner55660a72009-03-08 19:39:53 +00007011 if (isa<CastExpr>(LHSStripped))
7012 LHSStripped = LHSStripped->IgnoreParenCasts();
7013 if (isa<CastExpr>(RHSStripped))
7014 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007015
Chris Lattner55660a72009-03-08 19:39:53 +00007016 // Warn about comparisons against a string constant (unless the other
7017 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007018 Expr *literalString = 0;
7019 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007020 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007021 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007022 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007023 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007024 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007025 } else if ((isa<StringLiteral>(RHSStripped) ||
7026 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007027 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007028 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007029 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007030 literalStringStripped = RHSStripped;
7031 }
7032
7033 if (literalString) {
7034 std::string resultComparison;
7035 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007036 case BO_LT: resultComparison = ") < 0"; break;
7037 case BO_GT: resultComparison = ") > 0"; break;
7038 case BO_LE: resultComparison = ") <= 0"; break;
7039 case BO_GE: resultComparison = ") >= 0"; break;
7040 case BO_EQ: resultComparison = ") == 0"; break;
7041 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007042 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007043 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007044
Ted Kremenek351ba912011-02-23 01:52:04 +00007045 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007046 PDiag(diag::warn_stringcompare)
7047 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007048 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007049 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007050 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007051
Douglas Gregord64fdd02010-06-08 19:50:34 +00007052 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007053 if (LHS.get()->getType()->isArithmeticType() &&
7054 RHS.get()->getType()->isArithmeticType()) {
7055 UsualArithmeticConversions(LHS, RHS);
7056 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007057 return QualType();
7058 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007059 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007060 LHS = UsualUnaryConversions(LHS.take());
7061 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007062 return QualType();
7063
Richard Trieuf1775fb2011-09-06 21:43:51 +00007064 RHS = UsualUnaryConversions(RHS.take());
7065 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007066 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007067 }
7068
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 LHSType = LHS.get()->getType();
7070 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007071
Douglas Gregor447b69e2008-11-19 03:25:36 +00007072 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007073 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007074
Richard Trieuccd891a2011-09-09 01:45:06 +00007075 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007076 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007077 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007078 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007079 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007080 if (LHSType->hasFloatingRepresentation())
7081 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007082
Richard Trieuf1775fb2011-09-06 21:43:51 +00007083 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007084 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007085 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007086
Richard Trieuf1775fb2011-09-06 21:43:51 +00007087 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007088 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007089 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007090 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007091
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007092 // All of the following pointer-related warnings are GCC extensions, except
7093 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007094 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007095 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007096 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007097 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007098 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007099
David Blaikie4e4d0842012-03-11 07:00:24 +00007100 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007101 if (LCanPointeeTy == RCanPointeeTy)
7102 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007103 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007104 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7105 // Valid unless comparison between non-null pointer and function pointer
7106 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007107 // In a SFINAE context, we treat this as a hard error to maintain
7108 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007109 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7110 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007111 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007112 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007113
7114 if (isSFINAEContext())
7115 return QualType();
7116
Richard Trieuf1775fb2011-09-06 21:43:51 +00007117 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007118 return ResultTy;
7119 }
7120 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007121
Richard Trieuf1775fb2011-09-06 21:43:51 +00007122 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007123 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007124 else
7125 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007126 }
Eli Friedman3075e762009-08-23 00:27:47 +00007127 // C99 6.5.9p2 and C99 6.5.8p2
7128 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7129 RCanPointeeTy.getUnqualifiedType())) {
7130 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007131 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007132 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007133 << LHSType << RHSType << LHS.get()->getSourceRange()
7134 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007135 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007136 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007137 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7138 // Valid unless comparison between non-null pointer and function pointer
7139 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007140 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007141 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007142 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007143 } else {
7144 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007145 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007146 }
John McCall34d6f932011-03-11 04:25:25 +00007147 if (LCanPointeeTy != RCanPointeeTy) {
7148 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007149 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007150 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007151 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007152 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007153 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007154 }
Mike Stump1eb44332009-09-09 15:08:12 +00007155
David Blaikie4e4d0842012-03-11 07:00:24 +00007156 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007157 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007158 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007159 return ResultTy;
7160
Mike Stump1eb44332009-09-09 15:08:12 +00007161 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007162 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007163 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007164 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007165 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007166 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7167 RHS = ImpCastExprToType(RHS.take(), LHSType,
7168 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007169 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007170 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007171 return ResultTy;
7172 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007173 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007174 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007175 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007176 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7177 LHS = ImpCastExprToType(LHS.take(), RHSType,
7178 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007179 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007180 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007181 return ResultTy;
7182 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007183
7184 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007185 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007186 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7187 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007188 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007189 else
7190 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007191 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007192
7193 // Handle scoped enumeration types specifically, since they don't promote
7194 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007195 if (LHS.get()->getType()->isEnumeralType() &&
7196 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7197 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007198 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007199 }
Mike Stump1eb44332009-09-09 15:08:12 +00007200
Steve Naroff1c7d0672008-09-04 15:10:53 +00007201 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007202 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007203 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007204 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7205 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007206
Steve Naroff1c7d0672008-09-04 15:10:53 +00007207 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007208 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007209 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007210 << LHSType << RHSType << LHS.get()->getSourceRange()
7211 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007212 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007213 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007214 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007215 }
John Wiegley429bb272011-04-08 18:41:53 +00007216
Steve Naroff59f53942008-09-28 01:11:11 +00007217 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007218 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007219 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7220 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007221 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007222 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007223 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007224 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007225 ->getPointeeType()->isVoidType())))
7226 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007227 << LHSType << RHSType << LHS.get()->getSourceRange()
7228 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007229 }
John McCall34d6f932011-03-11 04:25:25 +00007230 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007231 LHS = ImpCastExprToType(LHS.take(), RHSType,
7232 RHSType->isPointerType() ? CK_BitCast
7233 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007234 else
John McCall1d9b3b22011-09-09 05:25:32 +00007235 RHS = ImpCastExprToType(RHS.take(), LHSType,
7236 LHSType->isPointerType() ? CK_BitCast
7237 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007238 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007239 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007240
Richard Trieuf1775fb2011-09-06 21:43:51 +00007241 if (LHSType->isObjCObjectPointerType() ||
7242 RHSType->isObjCObjectPointerType()) {
7243 const PointerType *LPT = LHSType->getAs<PointerType>();
7244 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007245 if (LPT || RPT) {
7246 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7247 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007248
Steve Naroffa8069f12008-11-17 19:49:16 +00007249 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007250 !Context.typesAreCompatible(LHSType, RHSType)) {
7251 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007252 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007253 }
John McCall34d6f932011-03-11 04:25:25 +00007254 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007255 LHS = ImpCastExprToType(LHS.take(), RHSType,
7256 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007257 else
John McCall1d9b3b22011-09-09 05:25:32 +00007258 RHS = ImpCastExprToType(RHS.take(), LHSType,
7259 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007260 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007261 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007262 if (LHSType->isObjCObjectPointerType() &&
7263 RHSType->isObjCObjectPointerType()) {
7264 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7265 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007266 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007267 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007268 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007269
John McCall34d6f932011-03-11 04:25:25 +00007270 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007271 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007272 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007273 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007274 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007275 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007276 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007277 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7278 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007279 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007280 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007281 if (LangOpts.DebuggerSupport) {
7282 // Under a debugger, allow the comparison of pointers to integers,
7283 // since users tend to want to compare addresses.
7284 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007285 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007286 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007287 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007288 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007289 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007290 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007291 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7292 isError = true;
7293 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007294 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007295
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007296 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007297 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007298 << LHSType << RHSType << LHS.get()->getSourceRange()
7299 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007300 if (isError)
7301 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007302 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007303
Richard Trieuf1775fb2011-09-06 21:43:51 +00007304 if (LHSType->isIntegerType())
7305 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007306 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007307 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007308 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007309 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007310 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007311 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007312
Steve Naroff39218df2008-09-04 16:56:14 +00007313 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007314 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007315 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7316 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007317 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007318 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007319 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007320 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7321 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007322 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007323 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007324
Richard Trieuf1775fb2011-09-06 21:43:51 +00007325 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007326}
7327
Tanya Lattner4f692c22012-01-16 21:02:28 +00007328
7329// Return a signed type that is of identical size and number of elements.
7330// For floating point vectors, return an integer type of identical size
7331// and number of elements.
7332QualType Sema::GetSignedVectorType(QualType V) {
7333 const VectorType *VTy = V->getAs<VectorType>();
7334 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7335 if (TypeSize == Context.getTypeSize(Context.CharTy))
7336 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7337 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7338 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7339 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7340 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7341 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7342 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7343 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7344 "Unhandled vector element size in vector compare");
7345 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7346}
7347
Nate Begemanbe2341d2008-07-14 18:02:46 +00007348/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007349/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007350/// like a scalar comparison, a vector comparison produces a vector of integer
7351/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007352QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007353 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007354 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007355 // Check to make sure we're operating on vectors of the same type and width,
7356 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007357 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007358 if (vType.isNull())
7359 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007360
Richard Trieu9f60dee2011-09-07 01:19:57 +00007361 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007362
Anton Yartsev7870b132011-03-27 15:36:07 +00007363 // If AltiVec, the comparison results in a numeric type, i.e.
7364 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007365 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007366 return Context.getLogicalOperationType();
7367
Nate Begemanbe2341d2008-07-14 18:02:46 +00007368 // For non-floating point types, check for self-comparisons of the form
7369 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7370 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007371 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007372 if (DeclRefExpr* DRL
7373 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7374 if (DeclRefExpr* DRR
7375 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007376 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007377 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007378 PDiag(diag::warn_comparison_always)
7379 << 0 // self-
7380 << 2 // "a constant"
7381 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007382 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007383
Nate Begemanbe2341d2008-07-14 18:02:46 +00007384 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007385 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007386 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007387 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007388 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007389
7390 // Return a signed type for the vector.
7391 return GetSignedVectorType(LHSType);
7392}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007393
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007394QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7395 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007396 // Ensure that either both operands are of the same vector type, or
7397 // one operand is of a vector type and the other is of its element type.
7398 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7399 if (vType.isNull() || vType->isFloatingType())
7400 return InvalidOperands(Loc, LHS, RHS);
7401
7402 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007403}
7404
Reid Spencer5f016e22007-07-11 17:01:13 +00007405inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007406 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007407 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7408
Richard Trieu9f60dee2011-09-07 01:19:57 +00007409 if (LHS.get()->getType()->isVectorType() ||
7410 RHS.get()->getType()->isVectorType()) {
7411 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7412 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007413 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007414
Richard Trieu9f60dee2011-09-07 01:19:57 +00007415 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007416 }
Steve Naroff90045e82007-07-13 23:32:42 +00007417
Richard Trieu9f60dee2011-09-07 01:19:57 +00007418 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7419 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007420 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007421 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007422 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007423 LHS = LHSResult.take();
7424 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007425
Eli Friedman860a3192012-06-16 02:19:17 +00007426 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007427 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007428 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007429}
7430
7431inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007432 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007433
Tanya Lattner4f692c22012-01-16 21:02:28 +00007434 // Check vector operands differently.
7435 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7436 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7437
Chris Lattner90a8f272010-07-13 19:41:32 +00007438 // Diagnose cases where the user write a logical and/or but probably meant a
7439 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7440 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007441 if (LHS.get()->getType()->isIntegerType() &&
7442 !LHS.get()->getType()->isBooleanType() &&
7443 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007444 // Don't warn in macros or template instantiations.
7445 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007446 // If the RHS can be constant folded, and if it constant folds to something
7447 // that isn't 0 or 1 (which indicate a potential logical operation that
7448 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007449 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007450 llvm::APSInt Result;
7451 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007452 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007453 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007454 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007455 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007456 << (Opc == BO_LAnd ? "&&" : "||");
7457 // Suggest replacing the logical operator with the bitwise version
7458 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7459 << (Opc == BO_LAnd ? "&" : "|")
7460 << FixItHint::CreateReplacement(SourceRange(
7461 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007462 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007463 Opc == BO_LAnd ? "&" : "|");
7464 if (Opc == BO_LAnd)
7465 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7466 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7467 << FixItHint::CreateRemoval(
7468 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007469 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007470 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007471 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007472 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007473 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007474 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007475
David Blaikie4e4d0842012-03-11 07:00:24 +00007476 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007477 LHS = UsualUnaryConversions(LHS.take());
7478 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007479 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007480
Richard Trieu9f60dee2011-09-07 01:19:57 +00007481 RHS = UsualUnaryConversions(RHS.take());
7482 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007483 return QualType();
7484
Richard Trieu9f60dee2011-09-07 01:19:57 +00007485 if (!LHS.get()->getType()->isScalarType() ||
7486 !RHS.get()->getType()->isScalarType())
7487 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007488
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007489 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007490 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007491
John McCall75f7c0f2010-06-04 00:29:51 +00007492 // The following is safe because we only use this method for
7493 // non-overloadable operands.
7494
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007495 // C++ [expr.log.and]p1
7496 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007497 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007498 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7499 if (LHSRes.isInvalid())
7500 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007501 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007502
Richard Trieu9f60dee2011-09-07 01:19:57 +00007503 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7504 if (RHSRes.isInvalid())
7505 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007506 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007507
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007508 // C++ [expr.log.and]p2
7509 // C++ [expr.log.or]p2
7510 // The result is a bool.
7511 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007512}
7513
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007514/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7515/// is a read-only property; return true if so. A readonly property expression
7516/// depends on various declarations and thus must be treated specially.
7517///
Mike Stump1eb44332009-09-09 15:08:12 +00007518static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007519 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7520 if (!PropExpr) return false;
7521 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007522
John McCall3c3b7f92011-10-25 17:37:35 +00007523 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7524 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007525 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007526 PropExpr->getBase()->getType();
7527
John McCall3c3b7f92011-10-25 17:37:35 +00007528 if (const ObjCObjectPointerType *OPT =
7529 BaseType->getAsObjCInterfacePointerType())
7530 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7531 if (S.isPropertyReadonly(PDecl, IFace))
7532 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007533 return false;
7534}
7535
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007536static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007537 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7538 if (!ME) return false;
7539 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7540 ObjCMessageExpr *Base =
7541 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7542 if (!Base) return false;
7543 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007544}
7545
John McCall78dae242012-03-13 00:37:01 +00007546/// Is the given expression (which must be 'const') a reference to a
7547/// variable which was originally non-const, but which has become
7548/// 'const' due to being captured within a block?
7549enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7550static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7551 assert(E->isLValue() && E->getType().isConstQualified());
7552 E = E->IgnoreParens();
7553
7554 // Must be a reference to a declaration from an enclosing scope.
7555 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7556 if (!DRE) return NCCK_None;
7557 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7558
7559 // The declaration must be a variable which is not declared 'const'.
7560 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7561 if (!var) return NCCK_None;
7562 if (var->getType().isConstQualified()) return NCCK_None;
7563 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7564
7565 // Decide whether the first capture was for a block or a lambda.
7566 DeclContext *DC = S.CurContext;
7567 while (DC->getParent() != var->getDeclContext())
7568 DC = DC->getParent();
7569 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7570}
7571
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007572/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7573/// emit an error and return true. If so, return false.
7574static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007575 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007576 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007577 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007578 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007579 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7580 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007581 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7582 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007583 if (IsLV == Expr::MLV_Valid)
7584 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007585
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007586 unsigned Diag = 0;
7587 bool NeedType = false;
7588 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007589 case Expr::MLV_ConstQualified:
7590 Diag = diag::err_typecheck_assign_const;
7591
John McCall78dae242012-03-13 00:37:01 +00007592 // Use a specialized diagnostic when we're assigning to an object
7593 // from an enclosing function or block.
7594 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7595 if (NCCK == NCCK_Block)
7596 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7597 else
7598 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7599 break;
7600 }
7601
John McCall7acddac2011-06-17 06:42:21 +00007602 // In ARC, use some specialized diagnostics for occasions where we
7603 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007604 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007605 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7606 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7607 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7608
John McCall7acddac2011-06-17 06:42:21 +00007609 // Use the normal diagnostic if it's pseudo-__strong but the
7610 // user actually wrote 'const'.
7611 if (var->isARCPseudoStrong() &&
7612 (!var->getTypeSourceInfo() ||
7613 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7614 // There are two pseudo-strong cases:
7615 // - self
John McCallf85e1932011-06-15 23:02:42 +00007616 ObjCMethodDecl *method = S.getCurMethodDecl();
7617 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007618 Diag = method->isClassMethod()
7619 ? diag::err_typecheck_arc_assign_self_class_method
7620 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007621
7622 // - fast enumeration variables
7623 else
John McCallf85e1932011-06-15 23:02:42 +00007624 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007625
John McCallf85e1932011-06-15 23:02:42 +00007626 SourceRange Assign;
7627 if (Loc != OrigLoc)
7628 Assign = SourceRange(OrigLoc, OrigLoc);
7629 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7630 // We need to preserve the AST regardless, so migration tool
7631 // can do its job.
7632 return false;
7633 }
7634 }
7635 }
7636
7637 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007638 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007639 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007640 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7641 NeedType = true;
7642 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007643 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007644 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7645 NeedType = true;
7646 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007647 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007648 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7649 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007650 case Expr::MLV_Valid:
7651 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007652 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007653 case Expr::MLV_MemberFunction:
7654 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007655 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7656 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007657 case Expr::MLV_IncompleteType:
7658 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007659 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007660 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007661 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007662 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7663 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007664 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007665 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007666 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007667 case Expr::MLV_InvalidMessageExpression:
7668 Diag = diag::error_readonly_message_assignment;
7669 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007670 case Expr::MLV_SubObjCPropertySetting:
7671 Diag = diag::error_no_subobject_property_setting;
7672 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007673 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007674
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007675 SourceRange Assign;
7676 if (Loc != OrigLoc)
7677 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007678 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007679 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007680 else
Mike Stump1eb44332009-09-09 15:08:12 +00007681 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007682 return true;
7683}
7684
Nico Weber7c81b432012-07-03 02:03:06 +00007685static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7686 SourceLocation Loc,
7687 Sema &Sema) {
7688 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007689 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7690 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7691 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7692 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007693 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007694 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007695
Nico Weber7c81b432012-07-03 02:03:06 +00007696 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007697 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7698 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7699 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7700 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7701 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7702 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007703 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007704 }
7705}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007706
7707// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007708QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007709 SourceLocation Loc,
7710 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007711 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7712
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007713 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007714 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007715 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007716
Richard Trieu268942b2011-09-07 01:33:52 +00007717 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007718 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7719 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007720 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007721 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007722 Expr *RHSCheck = RHS.get();
7723
Nico Weber7c81b432012-07-03 02:03:06 +00007724 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007725
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007726 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007727 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007728 if (RHS.isInvalid())
7729 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007730 // Special case of NSObject attributes on c-style pointer types.
7731 if (ConvTy == IncompatiblePointer &&
7732 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007733 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007734 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007735 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007736 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007737
John McCallf89e55a2010-11-18 06:31:45 +00007738 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007739 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007740 Diag(Loc, diag::err_objc_object_assignment)
7741 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007742
Chris Lattner2c156472008-08-21 18:04:13 +00007743 // If the RHS is a unary plus or minus, check to see if they = and + are
7744 // right next to each other. If so, the user may have typo'd "x =+ 4"
7745 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007746 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7747 RHSCheck = ICE->getSubExpr();
7748 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007749 if ((UO->getOpcode() == UO_Plus ||
7750 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007751 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007752 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007753 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007754 // And there is a space or other character before the subexpr of the
7755 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007756 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007757 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007758 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007759 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007760 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007761 }
Chris Lattner2c156472008-08-21 18:04:13 +00007762 }
John McCallf85e1932011-06-15 23:02:42 +00007763
7764 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007765 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7766 // Warn about retain cycles where a block captures the LHS, but
7767 // not if the LHS is a simple variable into which the block is
7768 // being stored...unless that variable can be captured by reference!
7769 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7770 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7771 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7772 checkRetainCycles(LHSExpr, RHS.get());
7773
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007774 // It is safe to assign a weak reference into a strong variable.
7775 // Although this code can still have problems:
7776 // id x = self.weakProp;
7777 // id y = self.weakProp;
7778 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7779 // paths through the function. This should be revisited if
7780 // -Wrepeated-use-of-weak is made flow-sensitive.
7781 DiagnosticsEngine::Level Level =
7782 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7783 RHS.get()->getLocStart());
7784 if (Level != DiagnosticsEngine::Ignored)
7785 getCurFunction()->markSafeWeakUse(RHS.get());
7786
Jordan Rosee10f4d32012-09-15 02:48:31 +00007787 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007788 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007789 }
John McCallf85e1932011-06-15 23:02:42 +00007790 }
Chris Lattner2c156472008-08-21 18:04:13 +00007791 } else {
7792 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007793 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007794 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007795
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007796 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007797 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007798 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007799
Richard Trieu268942b2011-09-07 01:33:52 +00007800 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007801
Reid Spencer5f016e22007-07-11 17:01:13 +00007802 // C99 6.5.16p3: The type of an assignment expression is the type of the
7803 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007804 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007805 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7806 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007807 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007808 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007809 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007810 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007811}
7812
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007813// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007814static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007815 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007816 LHS = S.CheckPlaceholderExpr(LHS.take());
7817 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007818 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007819 return QualType();
7820
John McCallcf2e5062010-10-12 07:14:40 +00007821 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7822 // operands, but not unary promotions.
7823 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007824
John McCallf6a16482010-12-04 03:47:34 +00007825 // So we treat the LHS as a ignored value, and in C++ we allow the
7826 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007827 LHS = S.IgnoredValueConversions(LHS.take());
7828 if (LHS.isInvalid())
7829 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007830
Eli Friedmana6115062012-05-24 00:47:05 +00007831 S.DiagnoseUnusedExprResult(LHS.get());
7832
David Blaikie4e4d0842012-03-11 07:00:24 +00007833 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007834 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7835 if (RHS.isInvalid())
7836 return QualType();
7837 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007838 S.RequireCompleteType(Loc, RHS.get()->getType(),
7839 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007840 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007841
John Wiegley429bb272011-04-08 18:41:53 +00007842 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007843}
7844
Steve Naroff49b45262007-07-13 16:58:59 +00007845/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7846/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007847static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7848 ExprValueKind &VK,
7849 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007850 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007851 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007852 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007853
Chris Lattner3528d352008-11-21 07:05:48 +00007854 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007855 // Atomic types can be used for increment / decrement where the non-atomic
7856 // versions can, so ignore the _Atomic() specifier for the purpose of
7857 // checking.
7858 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7859 ResType = ResAtomicType->getValueType();
7860
Chris Lattner3528d352008-11-21 07:05:48 +00007861 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007862
David Blaikie4e4d0842012-03-11 07:00:24 +00007863 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007864 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007865 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007866 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007867 return QualType();
7868 }
7869 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007870 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007871 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007872 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007873 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007874 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007875 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007876 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007877 } else if (ResType->isObjCObjectPointerType()) {
7878 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7879 // Otherwise, we just need a complete type.
7880 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7881 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7882 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007883 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007884 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007885 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007886 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007887 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007888 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007889 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007890 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007891 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007892 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007893 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007894 } else {
John McCall09431682010-11-18 19:01:18 +00007895 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007896 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007897 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007898 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007899 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007900 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007901 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007902 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007903 // In C++, a prefix increment is the same type as the operand. Otherwise
7904 // (in C or with postfix), the increment is the unqualified type of the
7905 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007906 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007907 VK = VK_LValue;
7908 return ResType;
7909 } else {
7910 VK = VK_RValue;
7911 return ResType.getUnqualifiedType();
7912 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007913}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007914
7915
Anders Carlsson369dee42008-02-01 07:15:58 +00007916/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007917/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007918/// where the declaration is needed for type checking. We only need to
7919/// handle cases when the expression references a function designator
7920/// or is an lvalue. Here are some examples:
7921/// - &(x) => x
7922/// - &*****f => f for f a function designator.
7923/// - &s.xx => s
7924/// - &s.zz[1].yy -> s, if zz is an array
7925/// - *(x + 1) -> x, if x is an array
7926/// - &"123"[2] -> 0
7927/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007928static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007929 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007930 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007931 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007932 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007933 // If this is an arrow operator, the address is an offset from
7934 // the base's value, so the object the base refers to is
7935 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007936 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007937 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007938 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007939 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007940 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007941 // FIXME: This code shouldn't be necessary! We should catch the implicit
7942 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007943 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7944 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7945 if (ICE->getSubExpr()->getType()->isArrayType())
7946 return getPrimaryDecl(ICE->getSubExpr());
7947 }
7948 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007949 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007950 case Stmt::UnaryOperatorClass: {
7951 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007952
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007953 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007954 case UO_Real:
7955 case UO_Imag:
7956 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007957 return getPrimaryDecl(UO->getSubExpr());
7958 default:
7959 return 0;
7960 }
7961 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007962 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007963 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007964 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007965 // If the result of an implicit cast is an l-value, we care about
7966 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007967 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007968 default:
7969 return 0;
7970 }
7971}
7972
Richard Trieu5520f232011-09-07 21:46:33 +00007973namespace {
7974 enum {
7975 AO_Bit_Field = 0,
7976 AO_Vector_Element = 1,
7977 AO_Property_Expansion = 2,
7978 AO_Register_Variable = 3,
7979 AO_No_Error = 4
7980 };
7981}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007982/// \brief Diagnose invalid operand for address of operations.
7983///
7984/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007985static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7986 Expr *E, unsigned Type) {
7987 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7988}
7989
Reid Spencer5f016e22007-07-11 17:01:13 +00007990/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007991/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007992/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007993/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007994/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007995/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007996/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007997static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007998 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007999 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8000 if (PTy->getKind() == BuiltinType::Overload) {
8001 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8002 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8003 << OrigOp.get()->getSourceRange();
8004 return QualType();
8005 }
8006
8007 return S.Context.OverloadTy;
8008 }
8009
8010 if (PTy->getKind() == BuiltinType::UnknownAny)
8011 return S.Context.UnknownAnyTy;
8012
8013 if (PTy->getKind() == BuiltinType::BoundMember) {
8014 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8015 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008016 return QualType();
8017 }
John McCall3c3b7f92011-10-25 17:37:35 +00008018
8019 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8020 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008021 }
John McCall9c72c602010-08-27 09:08:28 +00008022
John McCall3c3b7f92011-10-25 17:37:35 +00008023 if (OrigOp.get()->isTypeDependent())
8024 return S.Context.DependentTy;
8025
8026 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008027
John McCall9c72c602010-08-27 09:08:28 +00008028 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008029 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008030
David Blaikie4e4d0842012-03-11 07:00:24 +00008031 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008032 // Implement C99-only parts of addressof rules.
8033 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008034 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008035 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8036 // (assuming the deref expression is valid).
8037 return uOp->getSubExpr()->getType();
8038 }
8039 // Technically, there should be a check for array subscript
8040 // expressions here, but the result of one is always an lvalue anyway.
8041 }
John McCall5808ce42011-02-03 08:15:49 +00008042 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008043 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008044 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008045
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008046 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008047 bool sfinae = S.isSFINAEContext();
8048 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8049 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008050 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008051 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008052 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008053 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008054 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008055 } else if (lval == Expr::LV_MemberFunction) {
8056 // If it's an instance method, make a member pointer.
8057 // The expression must have exactly the form &A::foo.
8058
8059 // If the underlying expression isn't a decl ref, give up.
8060 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008061 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008062 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008063 return QualType();
8064 }
8065 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8066 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8067
8068 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008069 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008070 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008071 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008072
8073 // The method was named without a qualifier.
8074 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008075 if (MD->getParent()->getName().empty())
8076 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8077 << op->getSourceRange();
8078 else {
8079 SmallString<32> Str;
8080 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8081 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8082 << op->getSourceRange()
8083 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8084 }
John McCall9c72c602010-08-27 09:08:28 +00008085 }
8086
John McCall09431682010-11-18 19:01:18 +00008087 return S.Context.getMemberPointerType(op->getType(),
8088 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008089 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008090 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008091 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008092 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008093 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008094 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008095 AddressOfError = AO_Property_Expansion;
8096 } else {
8097 // FIXME: emit more specific diag...
8098 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8099 << op->getSourceRange();
8100 return QualType();
8101 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008102 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008103 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008104 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008105 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008106 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008107 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008108 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008109 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008110 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008111 // with the register storage-class specifier.
8112 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008113 // in C++ it is not error to take address of a register
8114 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008115 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008116 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008117 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008118 }
John McCallba135432009-11-21 08:51:07 +00008119 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008120 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008121 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008122 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008123 // Could be a pointer to member, though, if there is an explicit
8124 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008125 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008126 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008127 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008128 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008129 S.Diag(OpLoc,
8130 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008131 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008132 return QualType();
8133 }
Mike Stump1eb44332009-09-09 15:08:12 +00008134
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008135 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8136 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008137 return S.Context.getMemberPointerType(op->getType(),
8138 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008139 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008140 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008141 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008142 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008143 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008144
Richard Trieu5520f232011-09-07 21:46:33 +00008145 if (AddressOfError != AO_No_Error) {
8146 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8147 return QualType();
8148 }
8149
Eli Friedman441cf102009-05-16 23:27:50 +00008150 if (lval == Expr::LV_IncompleteVoidType) {
8151 // Taking the address of a void variable is technically illegal, but we
8152 // allow it in cases which are otherwise valid.
8153 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008154 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008155 }
8156
Reid Spencer5f016e22007-07-11 17:01:13 +00008157 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008158 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008159 return S.Context.getObjCObjectPointerType(op->getType());
8160 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008161}
8162
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008163/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008164static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8165 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008166 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008167 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008168
John Wiegley429bb272011-04-08 18:41:53 +00008169 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8170 if (ConvResult.isInvalid())
8171 return QualType();
8172 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008173 QualType OpTy = Op->getType();
8174 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008175
8176 if (isa<CXXReinterpretCastExpr>(Op)) {
8177 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8178 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8179 Op->getSourceRange());
8180 }
8181
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008182 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8183 // is an incomplete type or void. It would be possible to warn about
8184 // dereferencing a void pointer, but it's completely well-defined, and such a
8185 // warning is unlikely to catch any mistakes.
8186 if (const PointerType *PT = OpTy->getAs<PointerType>())
8187 Result = PT->getPointeeType();
8188 else if (const ObjCObjectPointerType *OPT =
8189 OpTy->getAs<ObjCObjectPointerType>())
8190 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008191 else {
John McCallfb8721c2011-04-10 19:13:55 +00008192 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008193 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008194 if (PR.take() != Op)
8195 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008196 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008197
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008198 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008199 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008200 << OpTy << Op->getSourceRange();
8201 return QualType();
8202 }
John McCall09431682010-11-18 19:01:18 +00008203
8204 // Dereferences are usually l-values...
8205 VK = VK_LValue;
8206
8207 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008208 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008209 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008210
8211 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008212}
8213
John McCall2de56d12010-08-25 11:45:40 +00008214static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008215 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008216 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008217 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008218 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008219 case tok::periodstar: Opc = BO_PtrMemD; break;
8220 case tok::arrowstar: Opc = BO_PtrMemI; break;
8221 case tok::star: Opc = BO_Mul; break;
8222 case tok::slash: Opc = BO_Div; break;
8223 case tok::percent: Opc = BO_Rem; break;
8224 case tok::plus: Opc = BO_Add; break;
8225 case tok::minus: Opc = BO_Sub; break;
8226 case tok::lessless: Opc = BO_Shl; break;
8227 case tok::greatergreater: Opc = BO_Shr; break;
8228 case tok::lessequal: Opc = BO_LE; break;
8229 case tok::less: Opc = BO_LT; break;
8230 case tok::greaterequal: Opc = BO_GE; break;
8231 case tok::greater: Opc = BO_GT; break;
8232 case tok::exclaimequal: Opc = BO_NE; break;
8233 case tok::equalequal: Opc = BO_EQ; break;
8234 case tok::amp: Opc = BO_And; break;
8235 case tok::caret: Opc = BO_Xor; break;
8236 case tok::pipe: Opc = BO_Or; break;
8237 case tok::ampamp: Opc = BO_LAnd; break;
8238 case tok::pipepipe: Opc = BO_LOr; break;
8239 case tok::equal: Opc = BO_Assign; break;
8240 case tok::starequal: Opc = BO_MulAssign; break;
8241 case tok::slashequal: Opc = BO_DivAssign; break;
8242 case tok::percentequal: Opc = BO_RemAssign; break;
8243 case tok::plusequal: Opc = BO_AddAssign; break;
8244 case tok::minusequal: Opc = BO_SubAssign; break;
8245 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8246 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8247 case tok::ampequal: Opc = BO_AndAssign; break;
8248 case tok::caretequal: Opc = BO_XorAssign; break;
8249 case tok::pipeequal: Opc = BO_OrAssign; break;
8250 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008251 }
8252 return Opc;
8253}
8254
John McCall2de56d12010-08-25 11:45:40 +00008255static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008256 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008257 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008258 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008259 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008260 case tok::plusplus: Opc = UO_PreInc; break;
8261 case tok::minusminus: Opc = UO_PreDec; break;
8262 case tok::amp: Opc = UO_AddrOf; break;
8263 case tok::star: Opc = UO_Deref; break;
8264 case tok::plus: Opc = UO_Plus; break;
8265 case tok::minus: Opc = UO_Minus; break;
8266 case tok::tilde: Opc = UO_Not; break;
8267 case tok::exclaim: Opc = UO_LNot; break;
8268 case tok::kw___real: Opc = UO_Real; break;
8269 case tok::kw___imag: Opc = UO_Imag; break;
8270 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008271 }
8272 return Opc;
8273}
8274
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008275/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8276/// This warning is only emitted for builtin assignment operations. It is also
8277/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008278static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008279 SourceLocation OpLoc) {
8280 if (!S.ActiveTemplateInstantiations.empty())
8281 return;
8282 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8283 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008284 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8285 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8286 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8287 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8288 if (!LHSDeclRef || !RHSDeclRef ||
8289 LHSDeclRef->getLocation().isMacroID() ||
8290 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008291 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008292 const ValueDecl *LHSDecl =
8293 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8294 const ValueDecl *RHSDecl =
8295 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8296 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008297 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008298 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008299 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008300 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008301 if (RefTy->getPointeeType().isVolatileQualified())
8302 return;
8303
8304 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008305 << LHSDeclRef->getType()
8306 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008307}
8308
Douglas Gregoreaebc752008-11-06 23:29:22 +00008309/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8310/// operator @p Opc at location @c TokLoc. This routine only supports
8311/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008312ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008313 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008314 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008315 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008316 // The syntax only allows initializer lists on the RHS of assignment,
8317 // so we don't need to worry about accepting invalid code for
8318 // non-assignment operators.
8319 // C++11 5.17p9:
8320 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8321 // of x = {} is x = T().
8322 InitializationKind Kind =
8323 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8324 InitializedEntity Entity =
8325 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8326 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008327 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008328 if (Init.isInvalid())
8329 return Init;
8330 RHSExpr = Init.take();
8331 }
8332
Richard Trieu78ea78b2011-09-07 01:49:20 +00008333 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008334 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008335 // The following two variables are used for compound assignment operators
8336 QualType CompLHSTy; // Type of LHS after promotions for computation
8337 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008338 ExprValueKind VK = VK_RValue;
8339 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008340
8341 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008342 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008343 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008344 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008345 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8346 VK = LHS.get()->getValueKind();
8347 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008348 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008349 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008350 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008351 break;
John McCall2de56d12010-08-25 11:45:40 +00008352 case BO_PtrMemD:
8353 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008354 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008355 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008356 break;
John McCall2de56d12010-08-25 11:45:40 +00008357 case BO_Mul:
8358 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008359 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008360 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008361 break;
John McCall2de56d12010-08-25 11:45:40 +00008362 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008363 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008364 break;
John McCall2de56d12010-08-25 11:45:40 +00008365 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008366 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008367 break;
John McCall2de56d12010-08-25 11:45:40 +00008368 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008369 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008370 break;
John McCall2de56d12010-08-25 11:45:40 +00008371 case BO_Shl:
8372 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008373 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008374 break;
John McCall2de56d12010-08-25 11:45:40 +00008375 case BO_LE:
8376 case BO_LT:
8377 case BO_GE:
8378 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008379 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008380 break;
John McCall2de56d12010-08-25 11:45:40 +00008381 case BO_EQ:
8382 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008383 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008384 break;
John McCall2de56d12010-08-25 11:45:40 +00008385 case BO_And:
8386 case BO_Xor:
8387 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008388 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008389 break;
John McCall2de56d12010-08-25 11:45:40 +00008390 case BO_LAnd:
8391 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008392 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008393 break;
John McCall2de56d12010-08-25 11:45:40 +00008394 case BO_MulAssign:
8395 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008396 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008397 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008398 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008401 break;
John McCall2de56d12010-08-25 11:45:40 +00008402 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008403 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008404 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008405 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8406 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008407 break;
John McCall2de56d12010-08-25 11:45:40 +00008408 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008409 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008410 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8411 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008412 break;
John McCall2de56d12010-08-25 11:45:40 +00008413 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008414 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8415 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_ShlAssign:
8419 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008420 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008421 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008422 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8423 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008424 break;
John McCall2de56d12010-08-25 11:45:40 +00008425 case BO_AndAssign:
8426 case BO_XorAssign:
8427 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008428 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008429 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008430 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8431 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008432 break;
John McCall2de56d12010-08-25 11:45:40 +00008433 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008434 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008435 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008436 VK = RHS.get()->getValueKind();
8437 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008438 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008439 break;
8440 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008441 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008442 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008443
8444 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008445 CheckArrayAccess(LHS.get());
8446 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008447
Eli Friedmanab3a8522009-03-28 01:22:36 +00008448 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008449 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008450 ResultTy, VK, OK, OpLoc,
8451 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008452 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008453 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008454 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008455 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008456 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008457 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008458 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008459 CompResultTy, OpLoc,
8460 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008461}
8462
Sebastian Redlaee3c932009-10-27 12:10:02 +00008463/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8464/// operators are mixed in a way that suggests that the programmer forgot that
8465/// comparison operators have higher precedence. The most typical example of
8466/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008467static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008468 SourceLocation OpLoc, Expr *LHSExpr,
8469 Expr *RHSExpr) {
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008470 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8471 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008472
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008473 // Check that one of the sides is a comparison operator.
8474 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8475 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8476 if (!isLeftComp && !isRightComp)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008477 return;
8478
8479 // Bitwise operations are sometimes used as eager logical ops.
8480 // Don't diagnose this.
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008481 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8482 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8483 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008484 return;
8485
Richard Trieu78ea78b2011-09-07 01:49:20 +00008486 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8487 OpLoc)
8488 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008489 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu70979d42011-08-10 22:41:34 +00008490 SourceRange ParensRange = isLeftComp ?
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008491 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8492 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008493
8494 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008495 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu70979d42011-08-10 22:41:34 +00008496 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008497 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008498 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008499 SuggestParentheses(Self, OpLoc,
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008500 Self.PDiag(diag::note_precedence_bitwise_first)
8501 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu70979d42011-08-10 22:41:34 +00008502 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008503}
8504
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008505/// \brief It accepts a '&' expr that is inside a '|' one.
8506/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8507/// in parentheses.
8508static void
8509EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8510 BinaryOperator *Bop) {
8511 assert(Bop->getOpcode() == BO_And);
8512 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8513 << Bop->getSourceRange() << OpLoc;
8514 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008515 Self.PDiag(diag::note_precedence_silence)
8516 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008517 Bop->getSourceRange());
8518}
8519
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008520/// \brief It accepts a '&&' expr that is inside a '||' one.
8521/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8522/// in parentheses.
8523static void
8524EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008525 BinaryOperator *Bop) {
8526 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008527 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8528 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008529 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008530 Self.PDiag(diag::note_precedence_silence)
8531 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008532 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008533}
8534
8535/// \brief Returns true if the given expression can be evaluated as a constant
8536/// 'true'.
8537static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8538 bool Res;
8539 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8540}
8541
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008542/// \brief Returns true if the given expression can be evaluated as a constant
8543/// 'false'.
8544static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8545 bool Res;
8546 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8547}
8548
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008549/// \brief Look for '&&' in the left hand of a '||' expr.
8550static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008551 Expr *LHSExpr, Expr *RHSExpr) {
8552 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008553 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008554 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008555 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008556 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008557 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8558 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8559 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8560 } else if (Bop->getOpcode() == BO_LOr) {
8561 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8562 // If it's "a || b && 1 || c" we didn't warn earlier for
8563 // "a || b && 1", but warn now.
8564 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8565 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8566 }
8567 }
8568 }
8569}
8570
8571/// \brief Look for '&&' in the right hand of a '||' expr.
8572static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008573 Expr *LHSExpr, Expr *RHSExpr) {
8574 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008575 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008576 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008577 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008578 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008579 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8580 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8581 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008582 }
8583 }
8584}
8585
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008586/// \brief Look for '&' in the left or right hand of a '|' expr.
8587static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8588 Expr *OrArg) {
8589 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8590 if (Bop->getOpcode() == BO_And)
8591 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8592 }
8593}
8594
David Blaikieb3f55c52012-10-05 00:41:03 +00008595static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +00008596 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +00008597 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8598 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008599 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008600 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +00008601 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +00008602 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008603 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008604 Bop->getSourceRange());
8605 }
8606 }
8607}
8608
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008609/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008610/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008611static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008612 SourceLocation OpLoc, Expr *LHSExpr,
8613 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008614 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008615 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008616 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008617
8618 // Diagnose "arg1 & arg2 | arg3"
8619 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008620 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8621 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008622 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008623
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008624 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8625 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008626 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008627 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8628 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008629 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008630
8631 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8632 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +00008633 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8634 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8635 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +00008636 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008637}
8638
Reid Spencer5f016e22007-07-11 17:01:13 +00008639// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008640ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008641 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008642 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008643 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008644 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8645 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008646
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008647 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008648 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008649
Richard Trieubefece12011-09-07 02:02:10 +00008650 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008651}
8652
John McCall3c3b7f92011-10-25 17:37:35 +00008653/// Build an overloaded binary operator expression in the given scope.
8654static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8655 BinaryOperatorKind Opc,
8656 Expr *LHS, Expr *RHS) {
8657 // Find all of the overloaded operators visible from this
8658 // point. We perform both an operator-name lookup from the local
8659 // scope and an argument-dependent lookup based on the types of
8660 // the arguments.
8661 UnresolvedSet<16> Functions;
8662 OverloadedOperatorKind OverOp
8663 = BinaryOperator::getOverloadedOperator(Opc);
8664 if (Sc && OverOp != OO_None)
8665 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8666 RHS->getType(), Functions);
8667
8668 // Build the (potentially-overloaded, potentially-dependent)
8669 // binary operation.
8670 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8671}
8672
John McCall60d7b3a2010-08-24 06:29:42 +00008673ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008674 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008675 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008676 // We want to end up calling one of checkPseudoObjectAssignment
8677 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8678 // both expressions are overloadable or either is type-dependent),
8679 // or CreateBuiltinBinOp (in any other case). We also want to get
8680 // any placeholder types out of the way.
8681
John McCall3c3b7f92011-10-25 17:37:35 +00008682 // Handle pseudo-objects in the LHS.
8683 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8684 // Assignments with a pseudo-object l-value need special analysis.
8685 if (pty->getKind() == BuiltinType::PseudoObject &&
8686 BinaryOperator::isAssignmentOp(Opc))
8687 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8688
8689 // Don't resolve overloads if the other type is overloadable.
8690 if (pty->getKind() == BuiltinType::Overload) {
8691 // We can't actually test that if we still have a placeholder,
8692 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008693 // code below are valid when the LHS is an overload set. Note
8694 // that an overload set can be dependently-typed, but it never
8695 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008696 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8697 if (resolvedRHS.isInvalid()) return ExprError();
8698 RHSExpr = resolvedRHS.take();
8699
John McCallac516502011-10-28 01:04:34 +00008700 if (RHSExpr->isTypeDependent() ||
8701 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008702 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8703 }
8704
8705 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8706 if (LHS.isInvalid()) return ExprError();
8707 LHSExpr = LHS.take();
8708 }
8709
8710 // Handle pseudo-objects in the RHS.
8711 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8712 // An overload in the RHS can potentially be resolved by the type
8713 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008714 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8715 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8716 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8717
Eli Friedman87884912012-01-17 21:27:43 +00008718 if (LHSExpr->getType()->isOverloadableType())
8719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8720
John McCall3c3b7f92011-10-25 17:37:35 +00008721 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008722 }
John McCall3c3b7f92011-10-25 17:37:35 +00008723
8724 // Don't resolve overloads if the other type is overloadable.
8725 if (pty->getKind() == BuiltinType::Overload &&
8726 LHSExpr->getType()->isOverloadableType())
8727 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8728
8729 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8730 if (!resolvedRHS.isUsable()) return ExprError();
8731 RHSExpr = resolvedRHS.take();
8732 }
8733
David Blaikie4e4d0842012-03-11 07:00:24 +00008734 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008735 // If either expression is type-dependent, always build an
8736 // overloaded op.
8737 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8738 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008739
John McCallac516502011-10-28 01:04:34 +00008740 // Otherwise, build an overloaded op if either expression has an
8741 // overloadable type.
8742 if (LHSExpr->getType()->isOverloadableType() ||
8743 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008744 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008745 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008746
Douglas Gregoreaebc752008-11-06 23:29:22 +00008747 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008748 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008749}
8750
John McCall60d7b3a2010-08-24 06:29:42 +00008751ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008752 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008753 Expr *InputExpr) {
8754 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008755 ExprValueKind VK = VK_RValue;
8756 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008757 QualType resultType;
8758 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008759 case UO_PreInc:
8760 case UO_PreDec:
8761 case UO_PostInc:
8762 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008763 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008764 Opc == UO_PreInc ||
8765 Opc == UO_PostInc,
8766 Opc == UO_PreInc ||
8767 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008768 break;
John McCall2de56d12010-08-25 11:45:40 +00008769 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008770 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008771 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008772 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008773 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008774 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008775 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008776 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008777 }
John McCall2de56d12010-08-25 11:45:40 +00008778 case UO_Plus:
8779 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008780 Input = UsualUnaryConversions(Input.take());
8781 if (Input.isInvalid()) return ExprError();
8782 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008783 if (resultType->isDependentType())
8784 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008785 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8786 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008787 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008788 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008789 resultType->isEnumeralType())
8790 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008791 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008792 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008793 resultType->isPointerType())
8794 break;
8795
Sebastian Redl0eb23302009-01-19 00:08:26 +00008796 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008797 << resultType << Input.get()->getSourceRange());
8798
John McCall2de56d12010-08-25 11:45:40 +00008799 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008800 Input = UsualUnaryConversions(Input.take());
8801 if (Input.isInvalid()) return ExprError();
8802 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008803 if (resultType->isDependentType())
8804 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008805 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8806 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8807 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008808 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008809 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008810 else if (resultType->hasIntegerRepresentation())
8811 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008812 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008813 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008814 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008815 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008816 break;
John Wiegley429bb272011-04-08 18:41:53 +00008817
John McCall2de56d12010-08-25 11:45:40 +00008818 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008819 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008820 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8821 if (Input.isInvalid()) return ExprError();
8822 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008823
8824 // Though we still have to promote half FP to float...
8825 if (resultType->isHalfType()) {
8826 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8827 resultType = Context.FloatTy;
8828 }
8829
Sebastian Redl28507842009-02-26 14:39:58 +00008830 if (resultType->isDependentType())
8831 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008832 if (resultType->isScalarType()) {
8833 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008834 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008835 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8836 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008837 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8838 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008839 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008840 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008841 // Vector logical not returns the signed variant of the operand type.
8842 resultType = GetSignedVectorType(resultType);
8843 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008844 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008845 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008846 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008847 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008848
Reid Spencer5f016e22007-07-11 17:01:13 +00008849 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008850 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008851 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008852 break;
John McCall2de56d12010-08-25 11:45:40 +00008853 case UO_Real:
8854 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008855 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008856 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8857 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008858 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008859 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8860 if (Input.get()->getValueKind() != VK_RValue &&
8861 Input.get()->getObjectKind() == OK_Ordinary)
8862 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008863 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008864 // In C, a volatile scalar is read by __imag. In C++, it is not.
8865 Input = DefaultLvalueConversion(Input.take());
8866 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008867 break;
John McCall2de56d12010-08-25 11:45:40 +00008868 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008869 resultType = Input.get()->getType();
8870 VK = Input.get()->getValueKind();
8871 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008872 break;
8873 }
John Wiegley429bb272011-04-08 18:41:53 +00008874 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008875 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008876
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008877 // Check for array bounds violations in the operand of the UnaryOperator,
8878 // except for the '*' and '&' operators that have to be handled specially
8879 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8880 // that are explicitly defined as valid by the standard).
8881 if (Opc != UO_AddrOf && Opc != UO_Deref)
8882 CheckArrayAccess(Input.get());
8883
John Wiegley429bb272011-04-08 18:41:53 +00008884 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008885 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008886}
8887
Douglas Gregord3d08532011-12-14 21:23:13 +00008888/// \brief Determine whether the given expression is a qualified member
8889/// access expression, of a form that could be turned into a pointer to member
8890/// with the address-of operator.
8891static bool isQualifiedMemberAccess(Expr *E) {
8892 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8893 if (!DRE->getQualifier())
8894 return false;
8895
8896 ValueDecl *VD = DRE->getDecl();
8897 if (!VD->isCXXClassMember())
8898 return false;
8899
8900 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8901 return true;
8902 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8903 return Method->isInstance();
8904
8905 return false;
8906 }
8907
8908 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8909 if (!ULE->getQualifier())
8910 return false;
8911
8912 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8913 DEnd = ULE->decls_end();
8914 D != DEnd; ++D) {
8915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8916 if (Method->isInstance())
8917 return true;
8918 } else {
8919 // Overload set does not contain methods.
8920 break;
8921 }
8922 }
8923
8924 return false;
8925 }
8926
8927 return false;
8928}
8929
John McCall60d7b3a2010-08-24 06:29:42 +00008930ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008931 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008932 // First things first: handle placeholders so that the
8933 // overloaded-operator check considers the right type.
8934 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8935 // Increment and decrement of pseudo-object references.
8936 if (pty->getKind() == BuiltinType::PseudoObject &&
8937 UnaryOperator::isIncrementDecrementOp(Opc))
8938 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8939
8940 // extension is always a builtin operator.
8941 if (Opc == UO_Extension)
8942 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8943
8944 // & gets special logic for several kinds of placeholder.
8945 // The builtin code knows what to do.
8946 if (Opc == UO_AddrOf &&
8947 (pty->getKind() == BuiltinType::Overload ||
8948 pty->getKind() == BuiltinType::UnknownAny ||
8949 pty->getKind() == BuiltinType::BoundMember))
8950 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8951
8952 // Anything else needs to be handled now.
8953 ExprResult Result = CheckPlaceholderExpr(Input);
8954 if (Result.isInvalid()) return ExprError();
8955 Input = Result.take();
8956 }
8957
David Blaikie4e4d0842012-03-11 07:00:24 +00008958 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008959 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8960 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008961 // Find all of the overloaded operators visible from this
8962 // point. We perform both an operator-name lookup from the local
8963 // scope and an argument-dependent lookup based on the types of
8964 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008965 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008966 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008967 if (S && OverOp != OO_None)
8968 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8969 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008970
John McCall9ae2f072010-08-23 23:25:46 +00008971 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008972 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008973
John McCall9ae2f072010-08-23 23:25:46 +00008974 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008975}
8976
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008977// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008978ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008979 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008980 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008981}
8982
Steve Naroff1b273c42007-09-16 14:56:35 +00008983/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008984ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008985 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008986 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008987 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008988 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008989 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008990}
8991
John McCallf85e1932011-06-15 23:02:42 +00008992/// Given the last statement in a statement-expression, check whether
8993/// the result is a producing expression (like a call to an
8994/// ns_returns_retained function) and, if so, rebuild it to hoist the
8995/// release out of the full-expression. Otherwise, return null.
8996/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008997static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008998 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008999 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00009000 if (!cleanups) return 0;
9001
9002 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00009003 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00009004 return 0;
9005
9006 // Splice out the cast. This shouldn't modify any interesting
9007 // features of the statement.
9008 Expr *producer = cast->getSubExpr();
9009 assert(producer->getType() == cast->getType());
9010 assert(producer->getValueKind() == cast->getValueKind());
9011 cleanups->setSubExpr(producer);
9012 return cleanups;
9013}
9014
John McCall73f428c2012-04-04 01:27:53 +00009015void Sema::ActOnStartStmtExpr() {
9016 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9017}
9018
9019void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009020 // Note that function is also called by TreeTransform when leaving a
9021 // StmtExpr scope without rebuilding anything.
9022
John McCall73f428c2012-04-04 01:27:53 +00009023 DiscardCleanupsInEvaluationContext();
9024 PopExpressionEvaluationContext();
9025}
9026
John McCall60d7b3a2010-08-24 06:29:42 +00009027ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009028Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009029 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009030 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9031 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9032
John McCall73f428c2012-04-04 01:27:53 +00009033 if (hasAnyUnrecoverableErrorsInThisFunction())
9034 DiscardCleanupsInEvaluationContext();
9035 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9036 PopExpressionEvaluationContext();
9037
Douglas Gregordd8f5692010-03-10 04:54:39 +00009038 bool isFileScope
9039 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009040 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009041 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009042
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009043 // FIXME: there are a variety of strange constraints to enforce here, for
9044 // example, it is not possible to goto into a stmt expression apparently.
9045 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009046
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009047 // If there are sub stmts in the compound stmt, take the type of the last one
9048 // as the type of the stmtexpr.
9049 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009050 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009051 if (!Compound->body_empty()) {
9052 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009053 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009054 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009055 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9056 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009057 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009058 }
John McCallf85e1932011-06-15 23:02:42 +00009059
John Wiegley429bb272011-04-08 18:41:53 +00009060 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009061 // Do function/array conversion on the last expression, but not
9062 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009063 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9064 if (LastExpr.isInvalid())
9065 return ExprError();
9066 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009067
John Wiegley429bb272011-04-08 18:41:53 +00009068 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009069 // In ARC, if the final expression ends in a consume, splice
9070 // the consume out and bind it later. In the alternate case
9071 // (when dealing with a retainable type), the result
9072 // initialization will create a produce. In both cases the
9073 // result will be +1, and we'll need to balance that out with
9074 // a bind.
9075 if (Expr *rebuiltLastStmt
9076 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9077 LastExpr = rebuiltLastStmt;
9078 } else {
9079 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009080 InitializedEntity::InitializeResult(LPLoc,
9081 Ty,
9082 false),
9083 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009084 LastExpr);
9085 }
9086
John Wiegley429bb272011-04-08 18:41:53 +00009087 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009088 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009089 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009090 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009091 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009092 else
John Wiegley429bb272011-04-08 18:41:53 +00009093 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009094 StmtExprMayBindToTemp = true;
9095 }
9096 }
9097 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009098 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009099
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009100 // FIXME: Check that expression type is complete/non-abstract; statement
9101 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009102 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9103 if (StmtExprMayBindToTemp)
9104 return MaybeBindToTemporary(ResStmtExpr);
9105 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009106}
Steve Naroffd34e9152007-08-01 22:05:33 +00009107
John McCall60d7b3a2010-08-24 06:29:42 +00009108ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009109 TypeSourceInfo *TInfo,
9110 OffsetOfComponent *CompPtr,
9111 unsigned NumComponents,
9112 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009113 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009114 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009115 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009116
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009117 // We must have at least one component that refers to the type, and the first
9118 // one is known to be a field designator. Verify that the ArgTy represents
9119 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009120 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009121 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9122 << ArgTy << TypeRange);
9123
9124 // Type must be complete per C99 7.17p3 because a declaring a variable
9125 // with an incomplete type would be ill-formed.
9126 if (!Dependent
9127 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009128 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009129 return ExprError();
9130
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009131 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9132 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009133 // FIXME: This diagnostic isn't actually visible because the location is in
9134 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009135 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009136 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9137 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009138
9139 bool DidWarnAboutNonPOD = false;
9140 QualType CurrentType = ArgTy;
9141 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009142 SmallVector<OffsetOfNode, 4> Comps;
9143 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009144 for (unsigned i = 0; i != NumComponents; ++i) {
9145 const OffsetOfComponent &OC = CompPtr[i];
9146 if (OC.isBrackets) {
9147 // Offset of an array sub-field. TODO: Should we allow vector elements?
9148 if (!CurrentType->isDependentType()) {
9149 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9150 if(!AT)
9151 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9152 << CurrentType);
9153 CurrentType = AT->getElementType();
9154 } else
9155 CurrentType = Context.DependentTy;
9156
Richard Smithea011432011-10-17 23:29:39 +00009157 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9158 if (IdxRval.isInvalid())
9159 return ExprError();
9160 Expr *Idx = IdxRval.take();
9161
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009162 // The expression must be an integral expression.
9163 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009164 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9165 !Idx->getType()->isIntegerType())
9166 return ExprError(Diag(Idx->getLocStart(),
9167 diag::err_typecheck_subscript_not_integer)
9168 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009169
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009170 // Record this array index.
9171 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009172 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009173 continue;
9174 }
9175
9176 // Offset of a field.
9177 if (CurrentType->isDependentType()) {
9178 // We have the offset of a field, but we can't look into the dependent
9179 // type. Just record the identifier of the field.
9180 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9181 CurrentType = Context.DependentTy;
9182 continue;
9183 }
9184
9185 // We need to have a complete type to look into.
9186 if (RequireCompleteType(OC.LocStart, CurrentType,
9187 diag::err_offsetof_incomplete_type))
9188 return ExprError();
9189
9190 // Look for the designated field.
9191 const RecordType *RC = CurrentType->getAs<RecordType>();
9192 if (!RC)
9193 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9194 << CurrentType);
9195 RecordDecl *RD = RC->getDecl();
9196
9197 // C++ [lib.support.types]p5:
9198 // The macro offsetof accepts a restricted set of type arguments in this
9199 // International Standard. type shall be a POD structure or a POD union
9200 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009201 // C++11 [support.types]p4:
9202 // If type is not a standard-layout class (Clause 9), the results are
9203 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009204 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009205 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9206 unsigned DiagID =
9207 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9208 : diag::warn_offsetof_non_pod_type;
9209
9210 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009211 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009212 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009213 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9214 << CurrentType))
9215 DidWarnAboutNonPOD = true;
9216 }
9217
9218 // Look for the field.
9219 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9220 LookupQualifiedName(R, RD);
9221 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009222 IndirectFieldDecl *IndirectMemberDecl = 0;
9223 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009224 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009225 MemberDecl = IndirectMemberDecl->getAnonField();
9226 }
9227
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009228 if (!MemberDecl)
9229 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9230 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9231 OC.LocEnd));
9232
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009233 // C99 7.17p3:
9234 // (If the specified member is a bit-field, the behavior is undefined.)
9235 //
9236 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009237 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009238 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9239 << MemberDecl->getDeclName()
9240 << SourceRange(BuiltinLoc, RParenLoc);
9241 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9242 return ExprError();
9243 }
Eli Friedman19410a72010-08-05 10:11:36 +00009244
9245 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009246 if (IndirectMemberDecl)
9247 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009248
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009249 // If the member was found in a base class, introduce OffsetOfNodes for
9250 // the base class indirections.
9251 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9252 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009253 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009254 CXXBasePath &Path = Paths.front();
9255 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9256 B != BEnd; ++B)
9257 Comps.push_back(OffsetOfNode(B->Base));
9258 }
Eli Friedman19410a72010-08-05 10:11:36 +00009259
Francois Pichet87c2e122010-11-21 06:08:52 +00009260 if (IndirectMemberDecl) {
9261 for (IndirectFieldDecl::chain_iterator FI =
9262 IndirectMemberDecl->chain_begin(),
9263 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9264 assert(isa<FieldDecl>(*FI));
9265 Comps.push_back(OffsetOfNode(OC.LocStart,
9266 cast<FieldDecl>(*FI), OC.LocEnd));
9267 }
9268 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009269 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009270
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009271 CurrentType = MemberDecl->getType().getNonReferenceType();
9272 }
9273
9274 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009275 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009276}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009277
John McCall60d7b3a2010-08-24 06:29:42 +00009278ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009279 SourceLocation BuiltinLoc,
9280 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009281 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009282 OffsetOfComponent *CompPtr,
9283 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009284 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009285
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009286 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009287 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009288 if (ArgTy.isNull())
9289 return ExprError();
9290
Eli Friedman5a15dc12010-08-05 10:15:45 +00009291 if (!ArgTInfo)
9292 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9293
9294 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009295 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009296}
9297
9298
John McCall60d7b3a2010-08-24 06:29:42 +00009299ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009300 Expr *CondExpr,
9301 Expr *LHSExpr, Expr *RHSExpr,
9302 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009303 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9304
John McCallf89e55a2010-11-18 06:31:45 +00009305 ExprValueKind VK = VK_RValue;
9306 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009307 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009308 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009309 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009310 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009311 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009312 } else {
9313 // The conditional expression is required to be a constant expression.
9314 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009315 ExprResult CondICE
9316 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9317 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009318 if (CondICE.isInvalid())
9319 return ExprError();
9320 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009321
Sebastian Redl28507842009-02-26 14:39:58 +00009322 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009323 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9324
9325 resType = ActiveExpr->getType();
9326 ValueDependent = ActiveExpr->isValueDependent();
9327 VK = ActiveExpr->getValueKind();
9328 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009329 }
9330
Sebastian Redlf53597f2009-03-15 17:47:39 +00009331 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009332 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009333 resType->isDependentType(),
9334 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009335}
9336
Steve Naroff4eb206b2008-09-03 18:15:37 +00009337//===----------------------------------------------------------------------===//
9338// Clang Extensions.
9339//===----------------------------------------------------------------------===//
9340
9341/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009342void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009343 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009344 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009345 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009346 if (CurScope)
9347 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009348 else
9349 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009350
Eli Friedman84b007f2012-01-26 03:00:14 +00009351 getCurBlock()->HasImplicitReturnType = true;
9352
John McCall538773c2011-11-11 03:19:12 +00009353 // Enter a new evaluation context to insulate the block from any
9354 // cleanups from the enclosing full-expression.
9355 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009356}
9357
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009358void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9359 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009360 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009361 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009362 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009363
John McCallbf1a0282010-06-04 23:28:52 +00009364 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009365 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009366
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009367 // FIXME: We should allow unexpanded parameter packs here, but that would,
9368 // in turn, make the block expression contain unexpanded parameter packs.
9369 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9370 // Drop the parameters.
9371 FunctionProtoType::ExtProtoInfo EPI;
9372 EPI.HasTrailingReturn = false;
9373 EPI.TypeQuals |= DeclSpec::TQ_const;
9374 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9375 EPI);
9376 Sig = Context.getTrivialTypeSourceInfo(T);
9377 }
9378
John McCall711c52b2011-01-05 12:14:39 +00009379 // GetTypeForDeclarator always produces a function type for a block
9380 // literal signature. Furthermore, it is always a FunctionProtoType
9381 // unless the function was written with a typedef.
9382 assert(T->isFunctionType() &&
9383 "GetTypeForDeclarator made a non-function block signature");
9384
9385 // Look for an explicit signature in that function type.
9386 FunctionProtoTypeLoc ExplicitSignature;
9387
9388 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9389 if (isa<FunctionProtoTypeLoc>(tmp)) {
9390 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9391
9392 // Check whether that explicit signature was synthesized by
9393 // GetTypeForDeclarator. If so, don't save that as part of the
9394 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009395 if (ExplicitSignature.getLocalRangeBegin() ==
9396 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009397 // This would be much cheaper if we stored TypeLocs instead of
9398 // TypeSourceInfos.
9399 TypeLoc Result = ExplicitSignature.getResultLoc();
9400 unsigned Size = Result.getFullDataSize();
9401 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9402 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9403
9404 ExplicitSignature = FunctionProtoTypeLoc();
9405 }
John McCall82dc0092010-06-04 11:21:44 +00009406 }
Mike Stump1eb44332009-09-09 15:08:12 +00009407
John McCall711c52b2011-01-05 12:14:39 +00009408 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9409 CurBlock->FunctionType = T;
9410
9411 const FunctionType *Fn = T->getAs<FunctionType>();
9412 QualType RetTy = Fn->getResultType();
9413 bool isVariadic =
9414 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9415
John McCallc71a4912010-06-04 19:02:56 +00009416 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009417
John McCall82dc0092010-06-04 11:21:44 +00009418 // Don't allow returning a objc interface by value.
9419 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009420 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009421 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9422 return;
9423 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009424
John McCall82dc0092010-06-04 11:21:44 +00009425 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009426 // return type. TODO: what should we do with declarators like:
9427 // ^ * { ... }
9428 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009429 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009430 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009431 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009432 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009433 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009434
John McCall82dc0092010-06-04 11:21:44 +00009435 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009436 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009437 if (ExplicitSignature) {
9438 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9439 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009440 if (Param->getIdentifier() == 0 &&
9441 !Param->isImplicit() &&
9442 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009443 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009444 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009445 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009446 }
John McCall82dc0092010-06-04 11:21:44 +00009447
9448 // Fake up parameter variables if we have a typedef, like
9449 // ^ fntype { ... }
9450 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9451 for (FunctionProtoType::arg_type_iterator
9452 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9453 ParmVarDecl *Param =
9454 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009455 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009456 *I);
John McCallc71a4912010-06-04 19:02:56 +00009457 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009458 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009459 }
John McCall82dc0092010-06-04 11:21:44 +00009460
John McCallc71a4912010-06-04 19:02:56 +00009461 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009462 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009463 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009464 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9465 CurBlock->TheDecl->param_end(),
9466 /*CheckParameterNames=*/false);
9467 }
9468
John McCall82dc0092010-06-04 11:21:44 +00009469 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009470 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009471
John McCall82dc0092010-06-04 11:21:44 +00009472 // Put the parameter variables in scope. We can bail out immediately
9473 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009474 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009475 return;
9476
Steve Naroff090276f2008-10-10 01:28:17 +00009477 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009478 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9479 (*AI)->setOwningFunction(CurBlock->TheDecl);
9480
Steve Naroff090276f2008-10-10 01:28:17 +00009481 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009482 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009483 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009484
Steve Naroff090276f2008-10-10 01:28:17 +00009485 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009486 }
John McCall7a9813c2010-01-22 00:28:27 +00009487 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009488}
9489
9490/// ActOnBlockError - If there is an error parsing a block, this callback
9491/// is invoked to pop the information about the block from the action impl.
9492void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009493 // Leave the expression-evaluation context.
9494 DiscardCleanupsInEvaluationContext();
9495 PopExpressionEvaluationContext();
9496
Steve Naroff4eb206b2008-09-03 18:15:37 +00009497 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009498 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009499 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009500}
9501
9502/// ActOnBlockStmtExpr - This is called when the body of a block statement
9503/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009504ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009505 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009506 // If blocks are disabled, emit an error.
9507 if (!LangOpts.Blocks)
9508 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009509
John McCall538773c2011-11-11 03:19:12 +00009510 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009511 if (hasAnyUnrecoverableErrorsInThisFunction())
9512 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009513 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9514 PopExpressionEvaluationContext();
9515
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009516 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009517
9518 if (BSI->HasImplicitReturnType)
9519 deduceClosureReturnType(*BSI);
9520
Steve Naroff090276f2008-10-10 01:28:17 +00009521 PopDeclContext();
9522
Steve Naroff4eb206b2008-09-03 18:15:37 +00009523 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009524 if (!BSI->ReturnType.isNull())
9525 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009526
Mike Stump56925862009-07-28 22:04:01 +00009527 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009528 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009529
John McCall469a1eb2011-02-02 13:00:07 +00009530 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009531 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9532 SmallVector<BlockDecl::Capture, 4> Captures;
9533 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9534 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9535 if (Cap.isThisCapture())
9536 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009537 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009538 Cap.isNested(), Cap.getCopyExpr());
9539 Captures.push_back(NewCap);
9540 }
9541 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9542 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009543
John McCallc71a4912010-06-04 19:02:56 +00009544 // If the user wrote a function type in some form, try to use that.
9545 if (!BSI->FunctionType.isNull()) {
9546 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9547
9548 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9549 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9550
9551 // Turn protoless block types into nullary block types.
9552 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009553 FunctionProtoType::ExtProtoInfo EPI;
9554 EPI.ExtInfo = Ext;
9555 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009556
9557 // Otherwise, if we don't need to change anything about the function type,
9558 // preserve its sugar structure.
9559 } else if (FTy->getResultType() == RetTy &&
9560 (!NoReturn || FTy->getNoReturnAttr())) {
9561 BlockTy = BSI->FunctionType;
9562
9563 // Otherwise, make the minimal modifications to the function type.
9564 } else {
9565 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009566 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9567 EPI.TypeQuals = 0; // FIXME: silently?
9568 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009569 BlockTy = Context.getFunctionType(RetTy,
9570 FPT->arg_type_begin(),
9571 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009572 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009573 }
9574
9575 // If we don't have a function type, just build one from nothing.
9576 } else {
John McCalle23cf432010-12-14 08:05:40 +00009577 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009578 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009579 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009580 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009581
John McCallc71a4912010-06-04 19:02:56 +00009582 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9583 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009584 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009585
Chris Lattner17a78302009-04-19 05:28:12 +00009586 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009587 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009588 !hasAnyUnrecoverableErrorsInThisFunction() &&
9589 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009590 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009591
Chris Lattnere476bdc2011-02-17 23:58:47 +00009592 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009593
Jordan Rose7dd900e2012-07-02 21:19:23 +00009594 // Try to apply the named return value optimization. We have to check again
9595 // if we can do this, though, because blocks keep return statements around
9596 // to deduce an implicit return type.
9597 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9598 !BSI->TheDecl->isDependentContext())
9599 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009600
Benjamin Kramerd2486192011-07-12 14:11:05 +00009601 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9602 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009603 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009604
John McCall80ee6e82011-11-10 05:35:25 +00009605 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009606 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009607 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009608 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009609 ExprCleanupObjects.push_back(Result->getBlockDecl());
9610 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009611
9612 // It also gets a branch-protected scope if any of the captured
9613 // variables needs destruction.
9614 for (BlockDecl::capture_const_iterator
9615 ci = Result->getBlockDecl()->capture_begin(),
9616 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9617 const VarDecl *var = ci->getVariable();
9618 if (var->getType().isDestructedType() != QualType::DK_none) {
9619 getCurFunction()->setHasBranchProtectedScope();
9620 break;
9621 }
9622 }
John McCall80ee6e82011-11-10 05:35:25 +00009623 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009624
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009625 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009626}
9627
John McCall60d7b3a2010-08-24 06:29:42 +00009628ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009629 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009630 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009631 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009632 GetTypeFromParser(Ty, &TInfo);
9633 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009634}
9635
John McCall60d7b3a2010-08-24 06:29:42 +00009636ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009637 Expr *E, TypeSourceInfo *TInfo,
9638 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009639 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009640
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009641 // Get the va_list type
9642 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009643 if (VaListType->isArrayType()) {
9644 // Deal with implicit array decay; for example, on x86-64,
9645 // va_list is an array, but it's supposed to decay to
9646 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009647 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009648 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009649 ExprResult Result = UsualUnaryConversions(E);
9650 if (Result.isInvalid())
9651 return ExprError();
9652 E = Result.take();
Logan Chienb687f3b2012-10-20 06:11:33 +00009653 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9654 // If va_list is a record type and we are compiling in C++ mode,
9655 // check the argument using reference binding.
9656 InitializedEntity Entity
9657 = InitializedEntity::InitializeParameter(Context,
9658 Context.getLValueReferenceType(VaListType), false);
9659 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9660 if (Init.isInvalid())
9661 return ExprError();
9662 E = Init.takeAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009663 } else {
9664 // Otherwise, the va_list argument must be an l-value because
9665 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009666 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009667 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009668 return ExprError();
9669 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009670
Douglas Gregordd027302009-05-19 23:10:31 +00009671 if (!E->isTypeDependent() &&
9672 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009673 return ExprError(Diag(E->getLocStart(),
9674 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009675 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009676 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009677
David Majnemer0adde122011-06-14 05:17:32 +00009678 if (!TInfo->getType()->isDependentType()) {
9679 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009680 diag::err_second_parameter_to_va_arg_incomplete,
9681 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009682 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009683
David Majnemer0adde122011-06-14 05:17:32 +00009684 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009685 TInfo->getType(),
9686 diag::err_second_parameter_to_va_arg_abstract,
9687 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009688 return ExprError();
9689
Douglas Gregor4eb75222011-07-30 06:45:27 +00009690 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009691 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009692 TInfo->getType()->isObjCLifetimeType()
9693 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9694 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009695 << TInfo->getType()
9696 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009697 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009698
9699 // Check for va_arg where arguments of the given type will be promoted
9700 // (i.e. this va_arg is guaranteed to have undefined behavior).
9701 QualType PromoteType;
9702 if (TInfo->getType()->isPromotableIntegerType()) {
9703 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9704 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9705 PromoteType = QualType();
9706 }
9707 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9708 PromoteType = Context.DoubleTy;
9709 if (!PromoteType.isNull())
9710 Diag(TInfo->getTypeLoc().getBeginLoc(),
9711 diag::warn_second_parameter_to_va_arg_never_compatible)
9712 << TInfo->getType()
9713 << PromoteType
9714 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009715 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009716
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009717 QualType T = TInfo->getType().getNonLValueExprType(Context);
9718 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009719}
9720
John McCall60d7b3a2010-08-24 06:29:42 +00009721ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009722 // The type of __null will be int or long, depending on the size of
9723 // pointers on the target.
9724 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009725 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9726 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009727 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009728 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009729 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009730 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009731 Ty = Context.LongLongTy;
9732 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009733 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009734 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009735
Sebastian Redlf53597f2009-03-15 17:47:39 +00009736 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009737}
9738
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009739static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009740 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009741 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009742 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009743
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009744 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9745 if (!PT)
9746 return;
9747
9748 // Check if the destination is of type 'id'.
9749 if (!PT->isObjCIdType()) {
9750 // Check if the destination is the 'NSString' interface.
9751 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9752 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9753 return;
9754 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009755
John McCall4b9c2d22011-11-06 09:01:30 +00009756 // Ignore any parens, implicit casts (should only be
9757 // array-to-pointer decays), and not-so-opaque values. The last is
9758 // important for making this trigger for property assignments.
9759 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9760 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9761 if (OV->getSourceExpr())
9762 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9763
9764 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009765 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009766 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009767
Douglas Gregor849b2432010-03-31 17:46:05 +00009768 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009769}
9770
Chris Lattner5cf216b2008-01-04 18:04:52 +00009771bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9772 SourceLocation Loc,
9773 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009774 Expr *SrcExpr, AssignmentAction Action,
9775 bool *Complained) {
9776 if (Complained)
9777 *Complained = false;
9778
Chris Lattner5cf216b2008-01-04 18:04:52 +00009779 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009780 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009781 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009782 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009783 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009784 ConversionFixItGenerator ConvHints;
9785 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009786 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009787
Chris Lattner5cf216b2008-01-04 18:04:52 +00009788 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009789 case Compatible:
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00009790 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9791 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009792
Chris Lattnerb7b61152008-01-04 18:22:42 +00009793 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009794 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009795 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9796 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009797 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009798 case IntToPointer:
9799 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009800 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9801 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009802 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009803 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009804 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009805 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009806 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9807 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009808 if (Hint.isNull() && !CheckInferredResultType) {
9809 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9810 }
9811 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009812 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009813 case IncompatiblePointerSign:
9814 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9815 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009816 case FunctionVoidPointer:
9817 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9818 break;
John McCall86c05f32011-02-01 00:10:29 +00009819 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009820 // Perform array-to-pointer decay if necessary.
9821 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9822
John McCall86c05f32011-02-01 00:10:29 +00009823 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9824 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9825 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9826 DiagKind = diag::err_typecheck_incompatible_address_space;
9827 break;
John McCallf85e1932011-06-15 23:02:42 +00009828
9829
9830 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009831 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009832 break;
John McCall86c05f32011-02-01 00:10:29 +00009833 }
9834
9835 llvm_unreachable("unknown error case for discarding qualifiers!");
9836 // fallthrough
9837 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009838 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009839 // If the qualifiers lost were because we were applying the
9840 // (deprecated) C++ conversion from a string literal to a char*
9841 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9842 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009843 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009844 // bit of refactoring (so that the second argument is an
9845 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009846 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009847 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009848 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009849 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9850 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009851 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9852 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009853 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009854 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009855 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009856 case IntToBlockPointer:
9857 DiagKind = diag::err_int_to_block_pointer;
9858 break;
9859 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009860 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009861 break;
Steve Naroff39579072008-10-14 22:18:38 +00009862 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009863 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009864 // it can give a more specific diagnostic.
9865 DiagKind = diag::warn_incompatible_qualified_id;
9866 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009867 case IncompatibleVectors:
9868 DiagKind = diag::warn_incompatible_vectors;
9869 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009870 case IncompatibleObjCWeakRef:
9871 DiagKind = diag::err_arc_weak_unavailable_assign;
9872 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009873 case Incompatible:
9874 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009875 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9876 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009877 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009878 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009879 break;
9880 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009881
Douglas Gregord4eea832010-04-09 00:35:39 +00009882 QualType FirstType, SecondType;
9883 switch (Action) {
9884 case AA_Assigning:
9885 case AA_Initializing:
9886 // The destination type comes first.
9887 FirstType = DstType;
9888 SecondType = SrcType;
9889 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009890
Douglas Gregord4eea832010-04-09 00:35:39 +00009891 case AA_Returning:
9892 case AA_Passing:
9893 case AA_Converting:
9894 case AA_Sending:
9895 case AA_Casting:
9896 // The source type comes first.
9897 FirstType = SrcType;
9898 SecondType = DstType;
9899 break;
9900 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009901
Anna Zaks67221552011-07-28 19:51:27 +00009902 PartialDiagnostic FDiag = PDiag(DiagKind);
9903 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9904
9905 // If we can fix the conversion, suggest the FixIts.
9906 assert(ConvHints.isNull() || Hint.isNull());
9907 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009908 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9909 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009910 FDiag << *HI;
9911 } else {
9912 FDiag << Hint;
9913 }
9914 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9915
Richard Trieu6efd4c52011-11-23 22:32:32 +00009916 if (MayHaveFunctionDiff)
9917 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9918
Anna Zaks67221552011-07-28 19:51:27 +00009919 Diag(Loc, FDiag);
9920
Richard Trieu6efd4c52011-11-23 22:32:32 +00009921 if (SecondType == Context.OverloadTy)
9922 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9923 FirstType);
9924
Douglas Gregor926df6c2011-06-11 01:09:30 +00009925 if (CheckInferredResultType)
9926 EmitRelatedResultTypeNote(SrcExpr);
9927
Douglas Gregora41a8c52010-04-22 00:20:18 +00009928 if (Complained)
9929 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009930 return isInvalid;
9931}
Anders Carlssone21555e2008-11-30 19:50:32 +00009932
Richard Smith282e7e62012-02-04 09:53:13 +00009933ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9934 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009935 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9936 public:
9937 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9938 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9939 }
9940 } Diagnoser;
9941
9942 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9943}
9944
9945ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9946 llvm::APSInt *Result,
9947 unsigned DiagID,
9948 bool AllowFold) {
9949 class IDDiagnoser : public VerifyICEDiagnoser {
9950 unsigned DiagID;
9951
9952 public:
9953 IDDiagnoser(unsigned DiagID)
9954 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9955
9956 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9957 S.Diag(Loc, DiagID) << SR;
9958 }
9959 } Diagnoser(DiagID);
9960
9961 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9962}
9963
9964void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9965 SourceRange SR) {
9966 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009967}
9968
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009969ExprResult
9970Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009971 VerifyICEDiagnoser &Diagnoser,
9972 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009973 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009974
David Blaikie4e4d0842012-03-11 07:00:24 +00009975 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009976 // C++11 [expr.const]p5:
9977 // If an expression of literal class type is used in a context where an
9978 // integral constant expression is required, then that class type shall
9979 // have a single non-explicit conversion function to an integral or
9980 // unscoped enumeration type
9981 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009982 if (!Diagnoser.Suppress) {
9983 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9984 public:
9985 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9986
9987 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9988 QualType T) {
9989 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9990 }
9991
9992 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9993 SourceLocation Loc,
9994 QualType T) {
9995 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9996 }
9997
9998 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9999 SourceLocation Loc,
10000 QualType T,
10001 QualType ConvTy) {
10002 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10003 }
10004
10005 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10006 CXXConversionDecl *Conv,
10007 QualType ConvTy) {
10008 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10009 << ConvTy->isEnumeralType() << ConvTy;
10010 }
10011
10012 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10013 QualType T) {
10014 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10015 }
10016
10017 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10018 CXXConversionDecl *Conv,
10019 QualType ConvTy) {
10020 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10021 << ConvTy->isEnumeralType() << ConvTy;
10022 }
10023
10024 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10025 SourceLocation Loc,
10026 QualType T,
10027 QualType ConvTy) {
10028 return DiagnosticBuilder::getEmpty();
10029 }
10030 } ConvertDiagnoser;
10031
10032 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10033 ConvertDiagnoser,
10034 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010035 } else {
10036 // The caller wants to silently enquire whether this is an ICE. Don't
10037 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010038 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10039 public:
10040 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10041
10042 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10043 QualType T) {
10044 return DiagnosticBuilder::getEmpty();
10045 }
10046
10047 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10048 SourceLocation Loc,
10049 QualType T) {
10050 return DiagnosticBuilder::getEmpty();
10051 }
10052
10053 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10054 SourceLocation Loc,
10055 QualType T,
10056 QualType ConvTy) {
10057 return DiagnosticBuilder::getEmpty();
10058 }
10059
10060 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10061 CXXConversionDecl *Conv,
10062 QualType ConvTy) {
10063 return DiagnosticBuilder::getEmpty();
10064 }
10065
10066 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10067 QualType T) {
10068 return DiagnosticBuilder::getEmpty();
10069 }
10070
10071 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10072 CXXConversionDecl *Conv,
10073 QualType ConvTy) {
10074 return DiagnosticBuilder::getEmpty();
10075 }
10076
10077 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10078 SourceLocation Loc,
10079 QualType T,
10080 QualType ConvTy) {
10081 return DiagnosticBuilder::getEmpty();
10082 }
10083 } ConvertDiagnoser;
10084
10085 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10086 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010087 }
10088 if (Converted.isInvalid())
10089 return Converted;
10090 E = Converted.take();
10091 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10092 return ExprError();
10093 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10094 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010095 if (!Diagnoser.Suppress)
10096 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010097 return ExprError();
10098 }
10099
Richard Smithdaaefc52011-12-14 23:32:26 +000010100 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10101 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +000010102 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010103 if (Result)
10104 *Result = E->EvaluateKnownConstInt(Context);
10105 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010106 }
10107
Anders Carlssone21555e2008-11-30 19:50:32 +000010108 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010109 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10110 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010111
Richard Smithdaaefc52011-12-14 23:32:26 +000010112 // Try to evaluate the expression, and produce diagnostics explaining why it's
10113 // not a constant expression as a side-effect.
10114 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10115 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10116
10117 // In C++11, we can rely on diagnostics being produced for any expression
10118 // which is not a constant expression. If no diagnostics were produced, then
10119 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010120 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010121 if (Result)
10122 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010123 return Owned(E);
10124 }
10125
10126 // If our only note is the usual "invalid subexpression" note, just point
10127 // the caret at its location rather than producing an essentially
10128 // redundant note.
10129 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10130 diag::note_invalid_subexpr_in_const_expr) {
10131 DiagLoc = Notes[0].first;
10132 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010133 }
10134
10135 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010136 if (!Diagnoser.Suppress) {
10137 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010138 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10139 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010140 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010141
Richard Smith282e7e62012-02-04 09:53:13 +000010142 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010143 }
10144
Douglas Gregorab41fe92012-05-04 22:38:52 +000010145 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010146 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10147 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010148
Anders Carlssone21555e2008-11-30 19:50:32 +000010149 if (Result)
10150 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010151 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010152}
Douglas Gregore0762c92009-06-19 23:52:42 +000010153
Eli Friedmanef331b72012-01-20 01:26:23 +000010154namespace {
10155 // Handle the case where we conclude a expression which we speculatively
10156 // considered to be unevaluated is actually evaluated.
10157 class TransformToPE : public TreeTransform<TransformToPE> {
10158 typedef TreeTransform<TransformToPE> BaseTransform;
10159
10160 public:
10161 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10162
10163 // Make sure we redo semantic analysis
10164 bool AlwaysRebuild() { return true; }
10165
Eli Friedman56ff2832012-02-06 23:29:57 +000010166 // Make sure we handle LabelStmts correctly.
10167 // FIXME: This does the right thing, but maybe we need a more general
10168 // fix to TreeTransform?
10169 StmtResult TransformLabelStmt(LabelStmt *S) {
10170 S->getDecl()->setStmt(0);
10171 return BaseTransform::TransformLabelStmt(S);
10172 }
10173
Eli Friedmanef331b72012-01-20 01:26:23 +000010174 // We need to special-case DeclRefExprs referring to FieldDecls which
10175 // are not part of a member pointer formation; normal TreeTransforming
10176 // doesn't catch this case because of the way we represent them in the AST.
10177 // FIXME: This is a bit ugly; is it really the best way to handle this
10178 // case?
10179 //
10180 // Error on DeclRefExprs referring to FieldDecls.
10181 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10182 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010183 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010184 return SemaRef.Diag(E->getLocation(),
10185 diag::err_invalid_non_static_member_use)
10186 << E->getDecl() << E->getSourceRange();
10187
10188 return BaseTransform::TransformDeclRefExpr(E);
10189 }
10190
10191 // Exception: filter out member pointer formation
10192 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10193 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10194 return E;
10195
10196 return BaseTransform::TransformUnaryOperator(E);
10197 }
10198
Douglas Gregore2c59132012-02-09 08:14:43 +000010199 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10200 // Lambdas never need to be transformed.
10201 return E;
10202 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010203 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010204}
10205
Benjamin Krameraccaf192012-11-14 15:08:31 +000010206ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010207 assert(ExprEvalContexts.back().Context == Unevaluated &&
10208 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010209 ExprEvalContexts.back().Context =
10210 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10211 if (ExprEvalContexts.back().Context == Unevaluated)
10212 return E;
10213 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010214}
10215
Douglas Gregor2afce722009-11-26 00:44:06 +000010216void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010217Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010218 Decl *LambdaContextDecl,
10219 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010220 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010221 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010222 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010223 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010224 LambdaContextDecl,
10225 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010226 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010227 if (!MaybeODRUseExprs.empty())
10228 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010229}
10230
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010231void
10232Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10233 ReuseLambdaContextDecl_t,
10234 bool IsDecltype) {
10235 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10236 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10237}
10238
Richard Trieu67e29332011-08-02 04:35:43 +000010239void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010240 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010241
Douglas Gregore2c59132012-02-09 08:14:43 +000010242 if (!Rec.Lambdas.empty()) {
10243 if (Rec.Context == Unevaluated) {
10244 // C++11 [expr.prim.lambda]p2:
10245 // A lambda-expression shall not appear in an unevaluated operand
10246 // (Clause 5).
10247 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10248 Diag(Rec.Lambdas[I]->getLocStart(),
10249 diag::err_lambda_unevaluated_operand);
10250 } else {
10251 // Mark the capture expressions odr-used. This was deferred
10252 // during lambda expression creation.
10253 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10254 LambdaExpr *Lambda = Rec.Lambdas[I];
10255 for (LambdaExpr::capture_init_iterator
10256 C = Lambda->capture_init_begin(),
10257 CEnd = Lambda->capture_init_end();
10258 C != CEnd; ++C) {
10259 MarkDeclarationsReferencedInExpr(*C);
10260 }
10261 }
10262 }
10263 }
10264
Douglas Gregor2afce722009-11-26 00:44:06 +000010265 // When are coming out of an unevaluated context, clear out any
10266 // temporaries that we may have created as part of the evaluation of
10267 // the expression in that context: they aren't relevant because they
10268 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010269 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010270 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10271 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010272 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010273 CleanupVarDeclMarking();
10274 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010275 // Otherwise, merge the contexts together.
10276 } else {
10277 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010278 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10279 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010280 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010281
10282 // Pop the current expression evaluation context off the stack.
10283 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010284}
Douglas Gregore0762c92009-06-19 23:52:42 +000010285
John McCallf85e1932011-06-15 23:02:42 +000010286void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010287 ExprCleanupObjects.erase(
10288 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10289 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010290 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010291 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010292}
10293
Eli Friedman71b8fb52012-01-21 01:01:51 +000010294ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10295 if (!E->getType()->isVariablyModifiedType())
10296 return E;
Benjamin Krameraccaf192012-11-14 15:08:31 +000010297 return TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +000010298}
10299
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010300static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010301 // Do not mark anything as "used" within a dependent context; wait for
10302 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010303 if (SemaRef.CurContext->isDependentContext())
10304 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010305
Eli Friedman5f2987c2012-02-02 03:46:19 +000010306 switch (SemaRef.ExprEvalContexts.back().Context) {
10307 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010308 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010309 // (Depending on how you read the standard, we actually do need to do
10310 // something here for null pointer constants, but the standard's
10311 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010313
Eli Friedman5f2987c2012-02-02 03:46:19 +000010314 case Sema::ConstantEvaluated:
10315 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010316 // We are in a potentially evaluated expression (or a constant-expression
10317 // in C++03); we need to do implicit template instantiation, implicitly
10318 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010319 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010320
Eli Friedman5f2987c2012-02-02 03:46:19 +000010321 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010322 // Referenced declarations will only be used if the construct in the
10323 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010324 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010325 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010326 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010327}
10328
10329/// \brief Mark a function referenced, and check whether it is odr-used
10330/// (C++ [basic.def.odr]p2, C99 6.9p3)
10331void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10332 assert(Func && "No function?");
10333
10334 Func->setReferenced();
10335
Richard Smithce2661f2012-11-07 01:14:25 +000010336 // C++11 [basic.def.odr]p3:
10337 // A function whose name appears as a potentially-evaluated expression is
10338 // odr-used if it is the unique lookup result or the selected member of a
10339 // set of overloaded functions [...].
10340 //
10341 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10342 // can just check that here. Skip the rest of this function if we've already
10343 // marked the function as used.
10344 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10345 // C++11 [temp.inst]p3:
10346 // Unless a function template specialization has been explicitly
10347 // instantiated or explicitly specialized, the function template
10348 // specialization is implicitly instantiated when the specialization is
10349 // referenced in a context that requires a function definition to exist.
10350 //
10351 // We consider constexpr function templates to be referenced in a context
10352 // that requires a definition to exist whenever they are referenced.
10353 //
10354 // FIXME: This instantiates constexpr functions too frequently. If this is
10355 // really an unevaluated context (and we're not just in the definition of a
10356 // function template or overload resolution or other cases which we
10357 // incorrectly consider to be unevaluated contexts), and we're not in a
10358 // subexpression which we actually need to evaluate (for instance, a
10359 // template argument, array bound or an expression in a braced-init-list),
10360 // we are not permitted to instantiate this constexpr function definition.
10361 //
10362 // FIXME: This also implicitly defines special members too frequently. They
10363 // are only supposed to be implicitly defined if they are odr-used, but they
10364 // are not odr-used from constant expressions in unevaluated contexts.
10365 // However, they cannot be referenced if they are deleted, and they are
10366 // deleted whenever the implicit definition of the special member would
10367 // fail.
10368 if (!Func->isConstexpr() || Func->getBody())
10369 return;
10370 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10371 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10372 return;
10373 }
Mike Stump1eb44332009-09-09 15:08:12 +000010374
Douglas Gregore0762c92009-06-19 23:52:42 +000010375 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010376 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010377 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010378 if (Constructor->isDefaultConstructor()) {
10379 if (Constructor->isTrivial())
10380 return;
10381 if (!Constructor->isUsed(false))
10382 DefineImplicitDefaultConstructor(Loc, Constructor);
10383 } else if (Constructor->isCopyConstructor()) {
10384 if (!Constructor->isUsed(false))
10385 DefineImplicitCopyConstructor(Loc, Constructor);
10386 } else if (Constructor->isMoveConstructor()) {
10387 if (!Constructor->isUsed(false))
10388 DefineImplicitMoveConstructor(Loc, Constructor);
10389 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010390 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010391
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010392 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010393 } else if (CXXDestructorDecl *Destructor =
10394 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010395 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10396 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010397 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010398 if (Destructor->isVirtual())
10399 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010400 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010401 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10402 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010403 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010404 if (!MethodDecl->isUsed(false)) {
10405 if (MethodDecl->isCopyAssignmentOperator())
10406 DefineImplicitCopyAssignment(Loc, MethodDecl);
10407 else
10408 DefineImplicitMoveAssignment(Loc, MethodDecl);
10409 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010410 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10411 MethodDecl->getParent()->isLambda()) {
10412 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10413 if (Conversion->isLambdaToBlockPointerConversion())
10414 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10415 else
10416 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010417 } else if (MethodDecl->isVirtual())
10418 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010419 }
John McCall15e310a2011-02-19 02:53:41 +000010420
Eli Friedman5f2987c2012-02-02 03:46:19 +000010421 // Recursive functions should be marked when used from another function.
10422 // FIXME: Is this really right?
10423 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010424
Richard Smithb9d0b762012-07-27 04:22:15 +000010425 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010426 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010427 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010428 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10429 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010430
Eli Friedman5f2987c2012-02-02 03:46:19 +000010431 // Implicit instantiation of function templates and member functions of
10432 // class templates.
10433 if (Func->isImplicitlyInstantiable()) {
10434 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010435 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010436 if (FunctionTemplateSpecializationInfo *SpecInfo
10437 = Func->getTemplateSpecializationInfo()) {
10438 if (SpecInfo->getPointOfInstantiation().isInvalid())
10439 SpecInfo->setPointOfInstantiation(Loc);
10440 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010441 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010442 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010443 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10444 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010445 } else if (MemberSpecializationInfo *MSInfo
10446 = Func->getMemberSpecializationInfo()) {
10447 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010448 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010449 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010450 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010451 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010452 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10453 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010454 }
Mike Stump1eb44332009-09-09 15:08:12 +000010455
Richard Smith57b9c4e2012-02-14 22:25:15 +000010456 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010457 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10458 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010459 PendingLocalImplicitInstantiations.push_back(
10460 std::make_pair(Func, PointOfInstantiation));
10461 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010462 // Do not defer instantiations of constexpr functions, to avoid the
10463 // expression evaluator needing to call back into Sema if it sees a
10464 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010465 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010466 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010467 PendingInstantiations.push_back(std::make_pair(Func,
10468 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010469 // Notify the consumer that a function was implicitly instantiated.
10470 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10471 }
John McCall15e310a2011-02-19 02:53:41 +000010472 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010473 } else {
10474 // Walk redefinitions, as some of them may be instantiable.
10475 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10476 e(Func->redecls_end()); i != e; ++i) {
10477 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10478 MarkFunctionReferenced(Loc, *i);
10479 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010480 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010481
10482 // Keep track of used but undefined functions.
10483 if (!Func->isPure() && !Func->hasBody() &&
10484 Func->getLinkage() != ExternalLinkage) {
10485 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10486 if (old.isInvalid()) old = Loc;
10487 }
10488
10489 Func->setUsed(true);
10490}
10491
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010492static void
10493diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10494 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010495 DeclContext *VarDC = var->getDeclContext();
10496
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010497 // If the parameter still belongs to the translation unit, then
10498 // we're actually just using one parameter in the declaration of
10499 // the next.
10500 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010501 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010502 return;
10503
Eli Friedman0a294222012-02-07 00:15:00 +000010504 // For C code, don't diagnose about capture if we're not actually in code
10505 // right now; it's impossible to write a non-constant expression outside of
10506 // function context, so we'll get other (more useful) diagnostics later.
10507 //
10508 // For C++, things get a bit more nasty... it would be nice to suppress this
10509 // diagnostic for certain cases like using a local variable in an array bound
10510 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010511 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010512 return;
10513
Eli Friedman0a294222012-02-07 00:15:00 +000010514 if (isa<CXXMethodDecl>(VarDC) &&
10515 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10516 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10517 << var->getIdentifier();
10518 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10519 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10520 << var->getIdentifier() << fn->getDeclName();
10521 } else if (isa<BlockDecl>(VarDC)) {
10522 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10523 << var->getIdentifier();
10524 } else {
10525 // FIXME: Is there any other context where a local variable can be
10526 // declared?
10527 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10528 << var->getIdentifier();
10529 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010530
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010531 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10532 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010533
10534 // FIXME: Add additional diagnostic info about class etc. which prevents
10535 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010536}
10537
Douglas Gregorf8af9822012-02-12 18:42:33 +000010538/// \brief Capture the given variable in the given lambda expression.
10539static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010540 VarDecl *Var, QualType FieldType,
10541 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010542 SourceLocation Loc,
10543 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010544 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010545
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010546 // Build the non-static data member.
10547 FieldDecl *Field
10548 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10549 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010550 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010551 Field->setImplicit(true);
10552 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010553 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010554
10555 // C++11 [expr.prim.lambda]p21:
10556 // When the lambda-expression is evaluated, the entities that
10557 // are captured by copy are used to direct-initialize each
10558 // corresponding non-static data member of the resulting closure
10559 // object. (For array members, the array elements are
10560 // direct-initialized in increasing subscript order.) These
10561 // initializations are performed in the (unspecified) order in
10562 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010563
Douglas Gregore2c59132012-02-09 08:14:43 +000010564 // Introduce a new evaluation context for the initialization, so
10565 // that temporaries introduced as part of the capture are retained
10566 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010567 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10568
Douglas Gregor73d90922012-02-10 09:26:04 +000010569 // C++ [expr.prim.labda]p12:
10570 // An entity captured by a lambda-expression is odr-used (3.2) in
10571 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010572 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10573 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010574 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010575 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010576
10577 // When the field has array type, create index variables for each
10578 // dimension of the array. We use these index variables to subscript
10579 // the source array, and other clients (e.g., CodeGen) will perform
10580 // the necessary iteration with these index variables.
10581 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010582 QualType BaseType = FieldType;
10583 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010584 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010585 while (const ConstantArrayType *Array
10586 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010587 // Create the iteration variable for this array index.
10588 IdentifierInfo *IterationVarName = 0;
10589 {
10590 SmallString<8> Str;
10591 llvm::raw_svector_ostream OS(Str);
10592 OS << "__i" << IndexVariables.size();
10593 IterationVarName = &S.Context.Idents.get(OS.str());
10594 }
10595 VarDecl *IterationVar
10596 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10597 IterationVarName, SizeType,
10598 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10599 SC_None, SC_None);
10600 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010601 LSI->ArrayIndexVars.push_back(IterationVar);
10602
Douglas Gregor18fe0842012-02-09 02:45:47 +000010603 // Create a reference to the iteration variable.
10604 ExprResult IterationVarRef
10605 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10606 assert(!IterationVarRef.isInvalid() &&
10607 "Reference to invented variable cannot fail!");
10608 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10609 assert(!IterationVarRef.isInvalid() &&
10610 "Conversion of invented variable cannot fail!");
10611
10612 // Subscript the array with this iteration variable.
10613 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10614 Ref, Loc, IterationVarRef.take(), Loc);
10615 if (Subscript.isInvalid()) {
10616 S.CleanupVarDeclMarking();
10617 S.DiscardCleanupsInEvaluationContext();
10618 S.PopExpressionEvaluationContext();
10619 return ExprError();
10620 }
10621
10622 Ref = Subscript.take();
10623 BaseType = Array->getElementType();
10624 }
10625
10626 // Construct the entity that we will be initializing. For an array, this
10627 // will be first element in the array, which may require several levels
10628 // of array-subscript entities.
10629 SmallVector<InitializedEntity, 4> Entities;
10630 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010631 Entities.push_back(
10632 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010633 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10634 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10635 0,
10636 Entities.back()));
10637
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010638 InitializationKind InitKind
10639 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010640 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010641 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010642 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010643 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010644
10645 // If this initialization requires any cleanups (e.g., due to a
10646 // default argument to a copy constructor), note that for the
10647 // lambda.
10648 if (S.ExprNeedsCleanups)
10649 LSI->ExprNeedsCleanups = true;
10650
10651 // Exit the expression evaluation context used for the capture.
10652 S.CleanupVarDeclMarking();
10653 S.DiscardCleanupsInEvaluationContext();
10654 S.PopExpressionEvaluationContext();
10655 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010656}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010657
Douglas Gregor999713e2012-02-18 09:37:24 +000010658bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10659 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10660 bool BuildAndDiagnose,
10661 QualType &CaptureType,
10662 QualType &DeclRefType) {
10663 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010664
Eli Friedmanb942cb22012-02-03 22:47:37 +000010665 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010666 if (Var->getDeclContext() == DC) return true;
10667 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010668
Douglas Gregorf8af9822012-02-12 18:42:33 +000010669 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010670
Douglas Gregor999713e2012-02-18 09:37:24 +000010671 // Walk up the stack to determine whether we can capture the variable,
10672 // performing the "simple" checks that don't depend on type. We stop when
10673 // we've either hit the declared scope of the variable or find an existing
10674 // capture of that variable.
10675 CaptureType = Var->getType();
10676 DeclRefType = CaptureType.getNonReferenceType();
10677 bool Explicit = (Kind != TryCapture_Implicit);
10678 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010679 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010680 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010681 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010682 DeclContext *ParentDC;
10683 if (isa<BlockDecl>(DC))
10684 ParentDC = DC->getParent();
10685 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010686 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010687 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10688 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010689 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010690 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010691 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010692 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010693 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010694
Eli Friedmanb942cb22012-02-03 22:47:37 +000010695 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010696 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010697
Eli Friedmanb942cb22012-02-03 22:47:37 +000010698 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010699 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010700 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010701 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010702
10703 // Retrieve the capture type for this variable.
10704 CaptureType = CSI->getCapture(Var).getCaptureType();
10705
10706 // Compute the type of an expression that refers to this variable.
10707 DeclRefType = CaptureType.getNonReferenceType();
10708
10709 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10710 if (Cap.isCopyCapture() &&
10711 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10712 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010713 break;
10714 }
10715
Douglas Gregorf8af9822012-02-12 18:42:33 +000010716 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010717 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010718
10719 // Lambdas are not allowed to capture unnamed variables
10720 // (e.g. anonymous unions).
10721 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10722 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010723 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010724 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010725 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10726 Diag(Var->getLocation(), diag::note_declared_at);
10727 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010728 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010729 }
10730
10731 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010732 if (Var->getType()->isVariablyModifiedType()) {
10733 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010734 if (IsBlock)
10735 Diag(Loc, diag::err_ref_vm_type);
10736 else
10737 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10738 Diag(Var->getLocation(), diag::note_previous_decl)
10739 << Var->getDeclName();
10740 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010741 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010742 }
10743
Eli Friedmanb942cb22012-02-03 22:47:37 +000010744 // Lambdas are not allowed to capture __block variables; they don't
10745 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010746 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010747 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010748 Diag(Loc, diag::err_lambda_capture_block)
10749 << Var->getDeclName();
10750 Diag(Var->getLocation(), diag::note_previous_decl)
10751 << Var->getDeclName();
10752 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010753 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010754 }
10755
Douglas Gregorf8af9822012-02-12 18:42:33 +000010756 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10757 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010758 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010759 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10760 Diag(Var->getLocation(), diag::note_previous_decl)
10761 << Var->getDeclName();
10762 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10763 diag::note_lambda_decl);
10764 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010765 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010766 }
10767
10768 FunctionScopesIndex--;
10769 DC = ParentDC;
10770 Explicit = false;
10771 } while (!Var->getDeclContext()->Equals(DC));
10772
Douglas Gregor999713e2012-02-18 09:37:24 +000010773 // Walk back down the scope stack, computing the type of the capture at
10774 // each step, checking type-specific requirements, and adding captures if
10775 // requested.
10776 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10777 ++I) {
10778 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010779
Douglas Gregor999713e2012-02-18 09:37:24 +000010780 // Compute the type of the capture and of a reference to the capture within
10781 // this scope.
10782 if (isa<BlockScopeInfo>(CSI)) {
10783 Expr *CopyExpr = 0;
10784 bool ByRef = false;
10785
10786 // Blocks are not allowed to capture arrays.
10787 if (CaptureType->isArrayType()) {
10788 if (BuildAndDiagnose) {
10789 Diag(Loc, diag::err_ref_array_type);
10790 Diag(Var->getLocation(), diag::note_previous_decl)
10791 << Var->getDeclName();
10792 }
10793 return true;
10794 }
10795
John McCall100c6492012-03-30 05:23:48 +000010796 // Forbid the block-capture of autoreleasing variables.
10797 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10798 if (BuildAndDiagnose) {
10799 Diag(Loc, diag::err_arc_autoreleasing_capture)
10800 << /*block*/ 0;
10801 Diag(Var->getLocation(), diag::note_previous_decl)
10802 << Var->getDeclName();
10803 }
10804 return true;
10805 }
10806
Douglas Gregor999713e2012-02-18 09:37:24 +000010807 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10808 // Block capture by reference does not change the capture or
10809 // declaration reference types.
10810 ByRef = true;
10811 } else {
10812 // Block capture by copy introduces 'const'.
10813 CaptureType = CaptureType.getNonReferenceType().withConst();
10814 DeclRefType = CaptureType;
10815
David Blaikie4e4d0842012-03-11 07:00:24 +000010816 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010817 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10818 // The capture logic needs the destructor, so make sure we mark it.
10819 // Usually this is unnecessary because most local variables have
10820 // their destructors marked at declaration time, but parameters are
10821 // an exception because it's technically only the call site that
10822 // actually requires the destructor.
10823 if (isa<ParmVarDecl>(Var))
10824 FinalizeVarWithDestructor(Var, Record);
10825
10826 // According to the blocks spec, the capture of a variable from
10827 // the stack requires a const copy constructor. This is not true
10828 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010829 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010830 DeclRefType.withConst(),
10831 VK_LValue, Loc);
10832 ExprResult Result
10833 = PerformCopyInitialization(
10834 InitializedEntity::InitializeBlock(Var->getLocation(),
10835 CaptureType, false),
10836 Loc, Owned(DeclRef));
10837
10838 // Build a full-expression copy expression if initialization
10839 // succeeded and used a non-trivial constructor. Recover from
10840 // errors by pretending that the copy isn't necessary.
10841 if (!Result.isInvalid() &&
10842 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10843 ->isTrivial()) {
10844 Result = MaybeCreateExprWithCleanups(Result);
10845 CopyExpr = Result.take();
10846 }
10847 }
10848 }
10849 }
10850
10851 // Actually capture the variable.
10852 if (BuildAndDiagnose)
10853 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10854 SourceLocation(), CaptureType, CopyExpr);
10855 Nested = true;
10856 continue;
10857 }
Douglas Gregor68932842012-02-18 05:51:20 +000010858
Douglas Gregor999713e2012-02-18 09:37:24 +000010859 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10860
10861 // Determine whether we are capturing by reference or by value.
10862 bool ByRef = false;
10863 if (I == N - 1 && Kind != TryCapture_Implicit) {
10864 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010865 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010866 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010867 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010868
10869 // Compute the type of the field that will capture this variable.
10870 if (ByRef) {
10871 // C++11 [expr.prim.lambda]p15:
10872 // An entity is captured by reference if it is implicitly or
10873 // explicitly captured but not captured by copy. It is
10874 // unspecified whether additional unnamed non-static data
10875 // members are declared in the closure type for entities
10876 // captured by reference.
10877 //
10878 // FIXME: It is not clear whether we want to build an lvalue reference
10879 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10880 // to do the former, while EDG does the latter. Core issue 1249 will
10881 // clarify, but for now we follow GCC because it's a more permissive and
10882 // easily defensible position.
10883 CaptureType = Context.getLValueReferenceType(DeclRefType);
10884 } else {
10885 // C++11 [expr.prim.lambda]p14:
10886 // For each entity captured by copy, an unnamed non-static
10887 // data member is declared in the closure type. The
10888 // declaration order of these members is unspecified. The type
10889 // of such a data member is the type of the corresponding
10890 // captured entity if the entity is not a reference to an
10891 // object, or the referenced type otherwise. [Note: If the
10892 // captured entity is a reference to a function, the
10893 // corresponding data member is also a reference to a
10894 // function. - end note ]
10895 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10896 if (!RefType->getPointeeType()->isFunctionType())
10897 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010898 }
John McCall100c6492012-03-30 05:23:48 +000010899
10900 // Forbid the lambda copy-capture of autoreleasing variables.
10901 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10902 if (BuildAndDiagnose) {
10903 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10904 Diag(Var->getLocation(), diag::note_previous_decl)
10905 << Var->getDeclName();
10906 }
10907 return true;
10908 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010909 }
10910
Douglas Gregor999713e2012-02-18 09:37:24 +000010911 // Capture this variable in the lambda.
10912 Expr *CopyExpr = 0;
10913 if (BuildAndDiagnose) {
10914 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010915 DeclRefType, Loc,
10916 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010917 if (!Result.isInvalid())
10918 CopyExpr = Result.take();
10919 }
10920
10921 // Compute the type of a reference to this captured variable.
10922 if (ByRef)
10923 DeclRefType = CaptureType.getNonReferenceType();
10924 else {
10925 // C++ [expr.prim.lambda]p5:
10926 // The closure type for a lambda-expression has a public inline
10927 // function call operator [...]. This function call operator is
10928 // declared const (9.3.1) if and only if the lambda-expression’s
10929 // parameter-declaration-clause is not followed by mutable.
10930 DeclRefType = CaptureType.getNonReferenceType();
10931 if (!LSI->Mutable && !CaptureType->isReferenceType())
10932 DeclRefType.addConst();
10933 }
10934
10935 // Add the capture.
10936 if (BuildAndDiagnose)
10937 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10938 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010939 Nested = true;
10940 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010941
10942 return false;
10943}
10944
10945bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10946 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10947 QualType CaptureType;
10948 QualType DeclRefType;
10949 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10950 /*BuildAndDiagnose=*/true, CaptureType,
10951 DeclRefType);
10952}
10953
10954QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10955 QualType CaptureType;
10956 QualType DeclRefType;
10957
10958 // Determine whether we can capture this variable.
10959 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10960 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10961 return QualType();
10962
10963 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010964}
10965
Eli Friedmand2cce132012-02-02 23:15:15 +000010966static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10967 SourceLocation Loc) {
10968 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010969 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010970 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010971 Var->getLinkage() != ExternalLinkage &&
10972 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010973 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10974 if (old.isInvalid()) old = Loc;
10975 }
10976
Douglas Gregor999713e2012-02-18 09:37:24 +000010977 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010978
Eli Friedmand2cce132012-02-02 23:15:15 +000010979 Var->setUsed(true);
10980}
10981
10982void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10983 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10984 // an object that satisfies the requirements for appearing in a
10985 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10986 // is immediately applied." This function handles the lvalue-to-rvalue
10987 // conversion part.
10988 MaybeODRUseExprs.erase(E->IgnoreParens());
10989}
10990
Eli Friedmanac626012012-02-29 03:16:56 +000010991ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10992 if (!Res.isUsable())
10993 return Res;
10994
10995 // If a constant-expression is a reference to a variable where we delay
10996 // deciding whether it is an odr-use, just assume we will apply the
10997 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10998 // (a non-type template argument), we have special handling anyway.
10999 UpdateMarkingForLValueToRValue(Res.get());
11000 return Res;
11001}
11002
Eli Friedmand2cce132012-02-02 23:15:15 +000011003void Sema::CleanupVarDeclMarking() {
11004 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11005 e = MaybeODRUseExprs.end();
11006 i != e; ++i) {
11007 VarDecl *Var;
11008 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000011009 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011010 Var = cast<VarDecl>(DRE->getDecl());
11011 Loc = DRE->getLocation();
11012 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11013 Var = cast<VarDecl>(ME->getMemberDecl());
11014 Loc = ME->getMemberLoc();
11015 } else {
11016 llvm_unreachable("Unexpcted expression");
11017 }
11018
11019 MarkVarDeclODRUsed(*this, Var, Loc);
11020 }
11021
11022 MaybeODRUseExprs.clear();
11023}
11024
11025// Mark a VarDecl referenced, and perform the necessary handling to compute
11026// odr-uses.
11027static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11028 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011029 Var->setReferenced();
11030
Eli Friedmand2cce132012-02-02 23:15:15 +000011031 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011032 return;
11033
11034 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000011035 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011036 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11037 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000011038 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11039 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011040 (!AlreadyInstantiated ||
11041 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000011042 if (!AlreadyInstantiated) {
11043 // This is a modification of an existing AST node. Notify listeners.
11044 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11045 L->StaticDataMemberInstantiated(Var);
11046 MSInfo->setPointOfInstantiation(Loc);
11047 }
11048 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011049 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011050 // Do not defer instantiations of variables which could be used in a
11051 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011052 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011053 else
Richard Smith37ce0102012-02-15 02:42:50 +000011054 SemaRef.PendingInstantiations.push_back(
11055 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011056 }
11057 }
11058
Richard Smith5016a702012-10-20 01:38:33 +000011059 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11060 // the requirements for appearing in a constant expression (5.19) and, if
11061 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000011062 // is immediately applied." We check the first part here, and
11063 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11064 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000011065 // C++03 depends on whether we get the C++03 version correct. The second
11066 // part does not apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011067 const VarDecl *DefVD;
Richard Smith5016a702012-10-20 01:38:33 +000011068 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011069 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5016a702012-10-20 01:38:33 +000011070 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11071 if (!Var->getType()->isReferenceType())
11072 SemaRef.MaybeODRUseExprs.insert(E);
11073 } else
Eli Friedmand2cce132012-02-02 23:15:15 +000011074 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11075}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011076
Eli Friedmand2cce132012-02-02 23:15:15 +000011077/// \brief Mark a variable referenced, and check whether it is odr-used
11078/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11079/// used directly for normal expressions referring to VarDecl.
11080void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11081 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011082}
11083
11084static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11085 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011086 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11087 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11088 return;
11089 }
11090
Eli Friedman5f2987c2012-02-02 03:46:19 +000011091 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011092
11093 // If this is a call to a method via a cast, also mark the method in the
11094 // derived class used in case codegen can devirtualize the call.
11095 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11096 if (!ME)
11097 return;
11098 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11099 if (!MD)
11100 return;
11101 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011102 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011103 if (!MostDerivedClassDecl)
11104 return;
11105 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011106 if (!DM)
11107 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011108 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011109}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011110
Eli Friedman5f2987c2012-02-02 03:46:19 +000011111/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11112void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11113 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11114}
11115
11116/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11117void Sema::MarkMemberReferenced(MemberExpr *E) {
11118 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11119}
11120
Douglas Gregor73d90922012-02-10 09:26:04 +000011121/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011122/// marks the declaration referenced, and performs odr-use checking for functions
11123/// and variables. This method should not be used when building an normal
11124/// expression which refers to a variable.
11125void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11126 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11127 MarkVariableReferenced(Loc, VD);
11128 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11129 MarkFunctionReferenced(Loc, FD);
11130 else
11131 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011132}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011133
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011134namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011135 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011136 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011137 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011138 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11139 Sema &S;
11140 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011141
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011142 public:
11143 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011144
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011145 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011146
11147 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11148 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011149 };
11150}
11151
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011152bool MarkReferencedDecls::TraverseTemplateArgument(
11153 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011154 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011155 if (Decl *D = Arg.getAsDecl())
11156 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011157 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011158
11159 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011160}
11161
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011162bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011163 if (ClassTemplateSpecializationDecl *Spec
11164 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11165 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011166 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011167 }
11168
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011169 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011170}
11171
11172void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11173 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011174 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011175}
11176
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011177namespace {
11178 /// \brief Helper class that marks all of the declarations referenced by
11179 /// potentially-evaluated subexpressions as "referenced".
11180 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11181 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011182 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011183
11184 public:
11185 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11186
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011187 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11188 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011189
11190 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011191 // If we were asked not to visit local variables, don't.
11192 if (SkipLocalVariables) {
11193 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11194 if (VD->hasLocalStorage())
11195 return;
11196 }
11197
Eli Friedman5f2987c2012-02-02 03:46:19 +000011198 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011199 }
11200
11201 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011202 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011203 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011204 }
11205
John McCall80ee6e82011-11-10 05:35:25 +000011206 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011207 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011208 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11209 Visit(E->getSubExpr());
11210 }
11211
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011212 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011213 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011214 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011215 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011216 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011217 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011218 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011219
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011220 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11221 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011222 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011223 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11224 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11225 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011226 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011227 S.LookupDestructor(Record));
11228 }
11229
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011230 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011231 }
11232
11233 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011234 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011235 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011236 }
11237
Douglas Gregor102ff972010-10-19 17:17:35 +000011238 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11239 Visit(E->getExpr());
11240 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011241
11242 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11243 Inherited::VisitImplicitCastExpr(E);
11244
11245 if (E->getCastKind() == CK_LValueToRValue)
11246 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11247 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011248 };
11249}
11250
11251/// \brief Mark any declarations that appear within this expression or any
11252/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011253///
11254/// \param SkipLocalVariables If true, don't mark local variables as
11255/// 'referenced'.
11256void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11257 bool SkipLocalVariables) {
11258 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011259}
11260
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011261/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11262/// of the program being compiled.
11263///
11264/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011265/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011266/// possibility that the code will actually be executable. Code in sizeof()
11267/// expressions, code used only during overload resolution, etc., are not
11268/// potentially evaluated. This routine will suppress such diagnostics or,
11269/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011270/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011271/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011272///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011273/// This routine should be used for all diagnostics that describe the run-time
11274/// behavior of a program, such as passing a non-POD value through an ellipsis.
11275/// Failure to do so will likely result in spurious diagnostics or failures
11276/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011277bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011278 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011279 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011280 case Unevaluated:
11281 // The argument will never be evaluated, so don't complain.
11282 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011283
Richard Smithf6702a32011-12-20 02:08:33 +000011284 case ConstantEvaluated:
11285 // Relevant diagnostics should be produced by constant evaluation.
11286 break;
11287
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011288 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011289 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011290 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011291 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011292 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011293 }
11294 else
11295 Diag(Loc, PD);
11296
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011297 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011298 }
11299
11300 return false;
11301}
11302
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011303bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11304 CallExpr *CE, FunctionDecl *FD) {
11305 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11306 return false;
11307
Richard Smith76f3f692012-02-22 02:04:18 +000011308 // If we're inside a decltype's expression, don't check for a valid return
11309 // type or construct temporaries until we know whether this is the last call.
11310 if (ExprEvalContexts.back().IsDecltype) {
11311 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11312 return false;
11313 }
11314
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011315 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011316 FunctionDecl *FD;
11317 CallExpr *CE;
11318
11319 public:
11320 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11321 : FD(FD), CE(CE) { }
11322
11323 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11324 if (!FD) {
11325 S.Diag(Loc, diag::err_call_incomplete_return)
11326 << T << CE->getSourceRange();
11327 return;
11328 }
11329
11330 S.Diag(Loc, diag::err_call_function_incomplete_return)
11331 << CE->getSourceRange() << FD->getDeclName() << T;
11332 S.Diag(FD->getLocation(),
11333 diag::note_function_with_incomplete_return_type_declared_here)
11334 << FD->getDeclName();
11335 }
11336 } Diagnoser(FD, CE);
11337
11338 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011339 return true;
11340
11341 return false;
11342}
11343
Douglas Gregor92c3a042011-01-19 16:50:08 +000011344// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011345// will prevent this condition from triggering, which is what we want.
11346void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11347 SourceLocation Loc;
11348
John McCalla52ef082009-11-11 02:41:58 +000011349 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011350 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011351
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011352 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011353 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011354 return;
11355
Douglas Gregor92c3a042011-01-19 16:50:08 +000011356 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11357
John McCallc8d8ac52009-11-12 00:06:05 +000011358 // Greylist some idioms by putting them into a warning subcategory.
11359 if (ObjCMessageExpr *ME
11360 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11361 Selector Sel = ME->getSelector();
11362
John McCallc8d8ac52009-11-12 00:06:05 +000011363 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011364 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011365 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11366
11367 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011368 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011369 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11370 }
John McCalla52ef082009-11-11 02:41:58 +000011371
John McCall5a881bb2009-10-12 21:59:07 +000011372 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011373 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011374 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011375 return;
11376
Douglas Gregor92c3a042011-01-19 16:50:08 +000011377 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011378 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011379 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11380 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11381 else {
John McCall5a881bb2009-10-12 21:59:07 +000011382 // Not an assignment.
11383 return;
11384 }
11385
Douglas Gregor55b38842010-04-14 16:09:52 +000011386 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011387
Daniel Dunbar96a00142012-03-09 18:35:03 +000011388 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011389 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11390 Diag(Loc, diag::note_condition_assign_silence)
11391 << FixItHint::CreateInsertion(Open, "(")
11392 << FixItHint::CreateInsertion(Close, ")");
11393
Douglas Gregor92c3a042011-01-19 16:50:08 +000011394 if (IsOrAssign)
11395 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11396 << FixItHint::CreateReplacement(Loc, "!=");
11397 else
11398 Diag(Loc, diag::note_condition_assign_to_comparison)
11399 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011400}
11401
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011402/// \brief Redundant parentheses over an equality comparison can indicate
11403/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011404void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011405 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011406 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011407 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11408 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011409 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011410 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011411 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011412
Richard Trieuccd891a2011-09-09 01:45:06 +000011413 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011414
11415 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011416 if (opE->getOpcode() == BO_EQ &&
11417 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11418 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011419 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011420
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011421 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011422 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011423 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011424 << FixItHint::CreateRemoval(ParenERange.getBegin())
11425 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011426 Diag(Loc, diag::note_equality_comparison_to_assign)
11427 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011428 }
11429}
11430
John Wiegley429bb272011-04-08 18:41:53 +000011431ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011432 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011433 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11434 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011435
John McCall864c0412011-04-26 20:42:42 +000011436 ExprResult result = CheckPlaceholderExpr(E);
11437 if (result.isInvalid()) return ExprError();
11438 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011439
John McCall864c0412011-04-26 20:42:42 +000011440 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011441 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011442 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11443
John Wiegley429bb272011-04-08 18:41:53 +000011444 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11445 if (ERes.isInvalid())
11446 return ExprError();
11447 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011448
11449 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011450 if (!T->isScalarType()) { // C99 6.8.4.1p1
11451 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11452 << T << E->getSourceRange();
11453 return ExprError();
11454 }
John McCall5a881bb2009-10-12 21:59:07 +000011455 }
11456
John Wiegley429bb272011-04-08 18:41:53 +000011457 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011458}
Douglas Gregor586596f2010-05-06 17:25:47 +000011459
John McCall60d7b3a2010-08-24 06:29:42 +000011460ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011461 Expr *SubExpr) {
11462 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011463 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011464
Richard Trieuccd891a2011-09-09 01:45:06 +000011465 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011466}
John McCall2a984ca2010-10-12 00:20:44 +000011467
John McCall1de4d4e2011-04-07 08:22:57 +000011468namespace {
John McCall755d8492011-04-12 00:42:48 +000011469 /// A visitor for rebuilding a call to an __unknown_any expression
11470 /// to have an appropriate type.
11471 struct RebuildUnknownAnyFunction
11472 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11473
11474 Sema &S;
11475
11476 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11477
11478 ExprResult VisitStmt(Stmt *S) {
11479 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011480 }
11481
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011482 ExprResult VisitExpr(Expr *E) {
11483 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11484 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011485 return ExprError();
11486 }
11487
11488 /// Rebuild an expression which simply semantically wraps another
11489 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011490 template <class T> ExprResult rebuildSugarExpr(T *E) {
11491 ExprResult SubResult = Visit(E->getSubExpr());
11492 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011493
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011494 Expr *SubExpr = SubResult.take();
11495 E->setSubExpr(SubExpr);
11496 E->setType(SubExpr->getType());
11497 E->setValueKind(SubExpr->getValueKind());
11498 assert(E->getObjectKind() == OK_Ordinary);
11499 return E;
John McCall755d8492011-04-12 00:42:48 +000011500 }
11501
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011502 ExprResult VisitParenExpr(ParenExpr *E) {
11503 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011504 }
11505
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011506 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11507 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011508 }
11509
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011510 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11511 ExprResult SubResult = Visit(E->getSubExpr());
11512 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011513
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011514 Expr *SubExpr = SubResult.take();
11515 E->setSubExpr(SubExpr);
11516 E->setType(S.Context.getPointerType(SubExpr->getType()));
11517 assert(E->getValueKind() == VK_RValue);
11518 assert(E->getObjectKind() == OK_Ordinary);
11519 return E;
John McCall755d8492011-04-12 00:42:48 +000011520 }
11521
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011522 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11523 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011524
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011525 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011526
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011527 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011528 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011529 !(isa<CXXMethodDecl>(VD) &&
11530 cast<CXXMethodDecl>(VD)->isInstance()))
11531 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011532
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011533 return E;
John McCall755d8492011-04-12 00:42:48 +000011534 }
11535
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011536 ExprResult VisitMemberExpr(MemberExpr *E) {
11537 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011538 }
11539
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011540 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11541 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011542 }
11543 };
11544}
11545
11546/// Given a function expression of unknown-any type, try to rebuild it
11547/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011548static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11549 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11550 if (Result.isInvalid()) return ExprError();
11551 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011552}
11553
11554namespace {
John McCall379b5152011-04-11 07:02:50 +000011555 /// A visitor for rebuilding an expression of type __unknown_anytype
11556 /// into one which resolves the type directly on the referring
11557 /// expression. Strict preservation of the original source
11558 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011559 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011560 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011561
11562 Sema &S;
11563
11564 /// The current destination type.
11565 QualType DestType;
11566
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011567 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11568 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011569
John McCalla5fc4722011-04-09 22:50:59 +000011570 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011571 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011572 }
11573
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011574 ExprResult VisitExpr(Expr *E) {
11575 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11576 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011577 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011578 }
11579
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011580 ExprResult VisitCallExpr(CallExpr *E);
11581 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011582
John McCalla5fc4722011-04-09 22:50:59 +000011583 /// Rebuild an expression which simply semantically wraps another
11584 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011585 template <class T> ExprResult rebuildSugarExpr(T *E) {
11586 ExprResult SubResult = Visit(E->getSubExpr());
11587 if (SubResult.isInvalid()) return ExprError();
11588 Expr *SubExpr = SubResult.take();
11589 E->setSubExpr(SubExpr);
11590 E->setType(SubExpr->getType());
11591 E->setValueKind(SubExpr->getValueKind());
11592 assert(E->getObjectKind() == OK_Ordinary);
11593 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011594 }
John McCall1de4d4e2011-04-07 08:22:57 +000011595
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011596 ExprResult VisitParenExpr(ParenExpr *E) {
11597 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011598 }
11599
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011600 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11601 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011602 }
11603
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011604 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11605 const PointerType *Ptr = DestType->getAs<PointerType>();
11606 if (!Ptr) {
11607 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11608 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011609 return ExprError();
11610 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011611 assert(E->getValueKind() == VK_RValue);
11612 assert(E->getObjectKind() == OK_Ordinary);
11613 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011614
11615 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011616 DestType = Ptr->getPointeeType();
11617 ExprResult SubResult = Visit(E->getSubExpr());
11618 if (SubResult.isInvalid()) return ExprError();
11619 E->setSubExpr(SubResult.take());
11620 return E;
John McCall755d8492011-04-12 00:42:48 +000011621 }
11622
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011623 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011624
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011625 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011626
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011627 ExprResult VisitMemberExpr(MemberExpr *E) {
11628 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011629 }
John McCalla5fc4722011-04-09 22:50:59 +000011630
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011631 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11632 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011633 }
11634 };
11635}
11636
John McCall379b5152011-04-11 07:02:50 +000011637/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011638ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11639 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011640
11641 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011642 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011643 FK_FunctionPointer,
11644 FK_BlockPointer
11645 };
11646
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011647 FnKind Kind;
11648 QualType CalleeType = CalleeExpr->getType();
11649 if (CalleeType == S.Context.BoundMemberTy) {
11650 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11651 Kind = FK_MemberFunction;
11652 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11653 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11654 CalleeType = Ptr->getPointeeType();
11655 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011656 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011657 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11658 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011659 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011660 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011661
11662 // Verify that this is a legal result type of a function.
11663 if (DestType->isArrayType() || DestType->isFunctionType()) {
11664 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011665 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011666 diagID = diag::err_block_returning_array_function;
11667
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011668 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011669 << DestType->isFunctionType() << DestType;
11670 return ExprError();
11671 }
11672
11673 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011674 E->setType(DestType.getNonLValueExprType(S.Context));
11675 E->setValueKind(Expr::getValueKindForType(DestType));
11676 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011677
11678 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011679 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011680 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011681 Proto->arg_type_begin(),
11682 Proto->getNumArgs(),
11683 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011684 else
11685 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011686 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011687
11688 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011689 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011690 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011691 // Nothing to do.
11692 break;
11693
11694 case FK_FunctionPointer:
11695 DestType = S.Context.getPointerType(DestType);
11696 break;
11697
11698 case FK_BlockPointer:
11699 DestType = S.Context.getBlockPointerType(DestType);
11700 break;
11701 }
11702
11703 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011704 ExprResult CalleeResult = Visit(CalleeExpr);
11705 if (!CalleeResult.isUsable()) return ExprError();
11706 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011707
11708 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011709 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011710}
11711
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011712ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011713 // Verify that this is a legal result type of a call.
11714 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011715 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011716 << DestType->isFunctionType() << DestType;
11717 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011718 }
11719
John McCall48218c62011-07-13 17:56:40 +000011720 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011721 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11722 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11723 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011724 }
John McCall755d8492011-04-12 00:42:48 +000011725
John McCall379b5152011-04-11 07:02:50 +000011726 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011727 E->setType(DestType.getNonReferenceType());
11728 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011729
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011730 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011731}
11732
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011733ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011734 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011735 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011736 assert(E->getValueKind() == VK_RValue);
11737 assert(E->getObjectKind() == OK_Ordinary);
11738
11739 E->setType(DestType);
11740
11741 // Rebuild the sub-expression as the pointee (function) type.
11742 DestType = DestType->castAs<PointerType>()->getPointeeType();
11743
11744 ExprResult Result = Visit(E->getSubExpr());
11745 if (!Result.isUsable()) return ExprError();
11746
11747 E->setSubExpr(Result.take());
11748 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011749 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011750 assert(E->getValueKind() == VK_RValue);
11751 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011752
Sean Callanance9c8312012-03-06 21:34:12 +000011753 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011754
Sean Callanance9c8312012-03-06 21:34:12 +000011755 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011756
Sean Callanance9c8312012-03-06 21:34:12 +000011757 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11758 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011759
Sean Callanance9c8312012-03-06 21:34:12 +000011760 ExprResult Result = Visit(E->getSubExpr());
11761 if (!Result.isUsable()) return ExprError();
11762
11763 E->setSubExpr(Result.take());
11764 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011765 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011766 llvm_unreachable("Unhandled cast type!");
11767 }
John McCall379b5152011-04-11 07:02:50 +000011768}
11769
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011770ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11771 ExprValueKind ValueKind = VK_LValue;
11772 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011773
11774 // We know how to make this work for certain kinds of decls:
11775
11776 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011777 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11778 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11779 DestType = Ptr->getPointeeType();
11780 ExprResult Result = resolveDecl(E, VD);
11781 if (Result.isInvalid()) return ExprError();
11782 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011783 CK_FunctionToPointerDecay, VK_RValue);
11784 }
11785
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011786 if (!Type->isFunctionType()) {
11787 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11788 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011789 return ExprError();
11790 }
John McCall379b5152011-04-11 07:02:50 +000011791
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011792 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11793 if (MD->isInstance()) {
11794 ValueKind = VK_RValue;
11795 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011796 }
11797
John McCall379b5152011-04-11 07:02:50 +000011798 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011799 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011800 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011801
11802 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011803 } else if (isa<VarDecl>(VD)) {
11804 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11805 Type = RefTy->getPointeeType();
11806 } else if (Type->isFunctionType()) {
11807 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11808 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011809 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011810 }
11811
11812 // - nothing else
11813 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011814 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11815 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011816 return ExprError();
11817 }
11818
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011819 VD->setType(DestType);
11820 E->setType(Type);
11821 E->setValueKind(ValueKind);
11822 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011823}
11824
John McCall1de4d4e2011-04-07 08:22:57 +000011825/// Check a cast of an unknown-any type. We intentionally only
11826/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011827ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11828 Expr *CastExpr, CastKind &CastKind,
11829 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011830 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011831 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011832 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011833
Richard Trieuccd891a2011-09-09 01:45:06 +000011834 CastExpr = result.take();
11835 VK = CastExpr->getValueKind();
11836 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011837
Richard Trieuccd891a2011-09-09 01:45:06 +000011838 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011839}
11840
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011841ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11842 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11843}
11844
John McCallb8a8de32012-11-14 00:49:39 +000011845QualType Sema::checkUnknownAnyArg(Expr *&arg) {
11846 // Filter out placeholders.
11847 ExprResult argR = CheckPlaceholderExpr(arg);
11848 if (argR.isInvalid()) return QualType();
11849 arg = argR.take();
11850
11851 // If the argument is an explicit cast, use that exact type as the
11852 // effective parameter type.
11853 if (ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg)) {
11854 return castArg->getTypeAsWritten();
11855 }
11856
11857 // Otherwise, try to pass by value.
11858 return arg->getType().getUnqualifiedType();
11859}
11860
Richard Trieuccd891a2011-09-09 01:45:06 +000011861static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11862 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011863 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011864 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011865 E = E->IgnoreParenImpCasts();
11866 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11867 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011868 diagID = diag::err_uncasted_call_of_unknown_any;
11869 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011870 break;
John McCall379b5152011-04-11 07:02:50 +000011871 }
John McCall1de4d4e2011-04-07 08:22:57 +000011872 }
11873
John McCall379b5152011-04-11 07:02:50 +000011874 SourceLocation loc;
11875 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011876 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011877 loc = ref->getLocation();
11878 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011879 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011880 loc = mem->getMemberLoc();
11881 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011882 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011883 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011884 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011885 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011886 if (!d) {
11887 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11888 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11889 << orig->getSourceRange();
11890 return ExprError();
11891 }
John McCall379b5152011-04-11 07:02:50 +000011892 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011893 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11894 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011895 return ExprError();
11896 }
11897
11898 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011899
11900 // Never recoverable.
11901 return ExprError();
11902}
11903
John McCall2a984ca2010-10-12 00:20:44 +000011904/// Check for operands with placeholder types and complain if found.
11905/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011906ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011907 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11908 if (!placeholderType) return Owned(E);
11909
11910 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011911
John McCall1de4d4e2011-04-07 08:22:57 +000011912 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011913 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011914 // Try to resolve a single function template specialization.
11915 // This is obligatory.
11916 ExprResult result = Owned(E);
11917 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11918 return result;
11919
11920 // If that failed, try to recover with a call.
11921 } else {
11922 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11923 /*complain*/ true);
11924 return result;
11925 }
11926 }
John McCall1de4d4e2011-04-07 08:22:57 +000011927
John McCall864c0412011-04-26 20:42:42 +000011928 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011929 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011930 ExprResult result = Owned(E);
11931 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11932 /*complain*/ true);
11933 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011934 }
11935
11936 // ARC unbridged casts.
11937 case BuiltinType::ARCUnbridgedCast: {
11938 Expr *realCast = stripARCUnbridgedCast(E);
11939 diagnoseARCUnbridgedCast(realCast);
11940 return Owned(realCast);
11941 }
John McCall864c0412011-04-26 20:42:42 +000011942
John McCall1de4d4e2011-04-07 08:22:57 +000011943 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011944 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011945 return diagnoseUnknownAnyExpr(*this, E);
11946
John McCall3c3b7f92011-10-25 17:37:35 +000011947 // Pseudo-objects.
11948 case BuiltinType::PseudoObject:
11949 return checkPseudoObjectRValue(E);
11950
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011951 case BuiltinType::BuiltinFn:
11952 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11953 return ExprError();
11954
John McCalle0a22d02011-10-18 21:02:43 +000011955 // Everything else should be impossible.
11956#define BUILTIN_TYPE(Id, SingletonId) \
11957 case BuiltinType::Id:
11958#define PLACEHOLDER_TYPE(Id, SingletonId)
11959#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011960 break;
11961 }
11962
11963 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011964}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011965
Richard Trieuccd891a2011-09-09 01:45:06 +000011966bool Sema::CheckCaseExpression(Expr *E) {
11967 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011968 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011969 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11970 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011971 return false;
11972}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011973
11974/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11975ExprResult
11976Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11977 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11978 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011979 QualType BoolT = Context.ObjCBuiltinBoolTy;
11980 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000011981 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011982 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000011983 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000011984 NamedDecl *ND = Result.getFoundDecl();
11985 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11986 Context.setBOOLDecl(TD);
11987 }
11988 }
11989 if (Context.getBOOLDecl())
11990 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011991 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011992 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011993}