blob: 0c1065813eb65d01d8bcf89d411e85edb6f2810a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "clang/Sema/DelayedDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000036#include "clang/Sema/Designator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
John McCall19510852010-08-20 18:27:03 +000040#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000041#include "clang/Sema/ScopeInfo.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000045using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000046
Sebastian Redl14b0c192011-09-24 17:48:00 +000047/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50 // See if this is an auto-typed variable whose initializer we are parsing.
51 if (ParsingInitForAutoVars.count(D))
52 return false;
53
54 // See if this is a deleted function.
55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56 if (FD->isDeleted())
57 return false;
Richard Smith60e141e2013-05-04 07:00:32 +000058
59 // If the function has a deduced return type, and we can't deduce it,
60 // then we can't use it either.
61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
63 return false;
Sebastian Redl14b0c192011-09-24 17:48:00 +000064 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000065
66 // See if this function is unavailable.
67 if (D->getAvailability() == AR_Unavailable &&
68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69 return false;
70
Sebastian Redl14b0c192011-09-24 17:48:00 +000071 return true;
72}
David Chisnall0f436562009-08-17 16:35:33 +000073
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000074static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
75 // Warn if this is used but marked unused.
76 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000077 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000078 if (!DC->hasAttr<UnusedAttr>())
79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
80 }
81}
82
Ted Kremenekd6cf9122012-02-10 02:45:47 +000083static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000084 NamedDecl *D, SourceLocation Loc,
85 const ObjCInterfaceDecl *UnknownObjCClass) {
86 // See if this declaration is unavailable or deprecated.
87 std::string Message;
88 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000089 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
90 if (Result == AR_Available) {
91 const DeclContext *DC = ECD->getDeclContext();
92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
93 Result = TheEnumDecl->getAvailability(&Message);
94 }
Jordan Rose04bec392012-10-10 16:42:54 +000095
Fariborz Jahanianfd090882012-09-21 20:46:37 +000096 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000097 if (Result == AR_Deprecated || Result == AR_Unavailable) {
98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
100 AvailabilityResult PDeclResult = PD->getAvailability(0);
101 if (PDeclResult == Result)
102 ObjCPDecl = PD;
103 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000104 }
Jordan Rose04bec392012-10-10 16:42:54 +0000105 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000106
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000107 switch (Result) {
108 case AR_Available:
109 case AR_NotYetIntroduced:
110 break;
111
112 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000114 break;
115
116 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000117 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000118 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000119 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000121 if (ObjCPDecl)
122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
123 << ObjCPDecl->getDeclName() << 1;
124 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000125 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000127 << D->getDeclName();
128 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000129 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000130 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000131 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000132 S.Diag(D->getLocation(), diag::note_unavailable_here)
133 << isa<FunctionDecl>(D) << false;
134 if (ObjCPDecl)
135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
136 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000137 }
138 break;
139 }
140 return Result;
141}
142
Richard Smith6c4c36c2012-03-30 20:53:28 +0000143/// \brief Emit a note explaining that this function is deleted or unavailable.
144void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
145 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
146
Richard Smith5bdaac52012-04-02 20:59:25 +0000147 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
148 // If the method was explicitly defaulted, point at that declaration.
149 if (!Method->isImplicit())
150 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
151
152 // Try to diagnose why this special member function was implicitly
153 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000154 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000155 if (CSM != CXXInvalid)
156 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
157
158 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000159 }
160
161 Diag(Decl->getLocation(), diag::note_unavailable_here)
162 << 1 << Decl->isDeleted();
163}
164
Jordan Rose0eb3f452012-06-18 22:09:19 +0000165/// \brief Determine whether a FunctionDecl was ever declared with an
166/// explicit storage class.
167static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
168 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
169 E = D->redecls_end();
170 I != E; ++I) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000171 if (I->getStorageClass() != SC_None)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000172 return true;
173 }
174 return false;
175}
176
177/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000178/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000179///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000180/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000181/// in many cases it will not behave correctly. This is not enabled in C++ mode
182/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
183/// and so while there may still be user mistakes, most of the time we can't
184/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000185static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
186 const NamedDecl *D,
187 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000188 // This is disabled under C++; there are too many ways for this to fire in
189 // contexts where the warning is a false positive, or where it is technically
190 // correct but benign.
191 if (S.getLangOpts().CPlusPlus)
192 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000193
194 // Check if this is an inlined function or method.
195 FunctionDecl *Current = S.getCurFunctionDecl();
196 if (!Current)
197 return;
198 if (!Current->isInlined())
199 return;
200 if (Current->getLinkage() != ExternalLinkage)
201 return;
202
203 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000204 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000205 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000206
Jordan Rose05233272012-06-21 05:54:50 +0000207 // Downgrade from ExtWarn to Extension if
208 // (1) the supposedly external inline function is in the main file,
209 // and probably won't be included anywhere else.
210 // (2) the thing we're referencing is a pure function.
211 // (3) the thing we're referencing is another inline function.
212 // This last can give us false negatives, but it's better than warning on
213 // wrappers for simple C library functions.
214 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
215 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
216 if (!DowngradeWarning && UsedFn)
217 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
218
219 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
220 : diag::warn_internal_in_extern_inline)
221 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000222
John McCallb421d922013-04-02 02:48:58 +0000223 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose0eb3f452012-06-18 22:09:19 +0000224
225 S.Diag(D->getCanonicalDecl()->getLocation(),
226 diag::note_internal_decl_declared_here)
227 << D;
228}
229
John McCallb421d922013-04-02 02:48:58 +0000230void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
231 const FunctionDecl *First = Cur->getFirstDeclaration();
232
233 // Suggest "static" on the function, if possible.
234 if (!hasAnyExplicitStorageClass(First)) {
235 SourceLocation DeclBegin = First->getSourceRange().getBegin();
236 Diag(DeclBegin, diag::note_convert_inline_to_static)
237 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
238 }
239}
240
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000241/// \brief Determine whether the use of this declaration is valid, and
242/// emit any corresponding diagnostics.
243///
244/// This routine diagnoses various problems with referencing
245/// declarations that can occur when using a declaration. For example,
246/// it might warn if a deprecated or unavailable declaration is being
247/// used, or produce an error (and return true) if a C++0x deleted
248/// function is being used.
249///
250/// \returns true if there was an error (this declaration cannot be
251/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000252///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000253bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000254 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000255 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000256 // If there were any diagnostics suppressed by template argument deduction,
257 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000259 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
260 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000261 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000262 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
263 Diag(Suppressed[I].first, Suppressed[I].second);
264
265 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000266 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000267 // entry from the table, because we want to avoid ever emitting these
268 // diagnostics again.
269 Suppressed.clear();
270 }
271 }
272
Richard Smith34b41d92011-02-20 03:19:35 +0000273 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000274 if (ParsingInitForAutoVars.count(D)) {
275 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
276 << D->getDeclName();
277 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000278 }
279
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000280 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000281 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000282 if (FD->isDeleted()) {
283 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000284 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000285 return true;
286 }
Richard Smith60e141e2013-05-04 07:00:32 +0000287
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
292 return true;
Douglas Gregor25d944a2009-02-24 04:26:15 +0000293 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000294 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000295
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000296 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000297
Jordan Rose0eb3f452012-06-18 22:09:19 +0000298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000299
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000300 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000301}
302
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000303/// \brief Retrieve the message suffix that should be added to a
304/// diagnostic complaining about the given function being deleted or
305/// unavailable.
306std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000307 std::string Message;
308 if (FD->getAvailability(&Message))
309 return ": " + Message;
310
311 return std::string();
312}
313
John McCall3323fad2011-09-09 07:56:05 +0000314/// DiagnoseSentinelCalls - This routine checks whether a call or
315/// message-send is to a declaration with the sentinel attribute, and
316/// if so, it checks that the requirements of the sentinel are
317/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000318void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000319 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000320 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000321 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000322 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000323
John McCall3323fad2011-09-09 07:56:05 +0000324 // The number of formal parameters of the declaration.
325 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
John McCall3323fad2011-09-09 07:56:05 +0000327 // The kind of declaration. This is also an index into a %select in
328 // the diagnostic.
329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000332 numFormalParams = MD->param_size();
333 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000335 numFormalParams = FD->param_size();
336 calleeType = CT_Function;
337 } else if (isa<VarDecl>(D)) {
338 QualType type = cast<ValueDecl>(D)->getType();
339 const FunctionType *fn = 0;
340 if (const PointerType *ptr = type->getAs<PointerType>()) {
341 fn = ptr->getPointeeType()->getAs<FunctionType>();
342 if (!fn) return;
343 calleeType = CT_Function;
344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345 fn = ptr->getPointeeType()->castAs<FunctionType>();
346 calleeType = CT_Block;
347 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000348 return;
John McCall3323fad2011-09-09 07:56:05 +0000349 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000350
John McCall3323fad2011-09-09 07:56:05 +0000351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352 numFormalParams = proto->getNumArgs();
353 } else {
354 numFormalParams = 0;
355 }
356 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000357 return;
358 }
John McCall3323fad2011-09-09 07:56:05 +0000359
360 // "nullPos" is the number of formal parameters at the end which
361 // effectively count as part of the variadic arguments. This is
362 // useful if you would prefer to not have *any* formal parameters,
363 // but the language forces you to have at least one.
364 unsigned nullPos = attr->getNullPos();
365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367
368 // The number of arguments which should follow the sentinel.
369 unsigned numArgsAfterSentinel = attr->getSentinel();
370
371 // If there aren't enough arguments for all the formal parameters,
372 // the sentinel, and the args after the sentinel, complain.
373 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000375 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000376 return;
377 }
John McCall3323fad2011-09-09 07:56:05 +0000378
379 // Otherwise, find the sentinel expression.
380 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000381 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000382 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000383 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000384
John McCall3323fad2011-09-09 07:56:05 +0000385 // Pick a reasonable string to insert. Optimistically use 'nil' or
386 // 'NULL' if those are actually defined in the context. Only use
387 // 'nil' for ObjC methods, where it's much more likely that the
388 // variadic arguments form a list of object pointers.
389 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000390 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
391 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000392 if (calleeType == CT_Method &&
393 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000394 NullValue = "nil";
395 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
396 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000397 else
John McCall3323fad2011-09-09 07:56:05 +0000398 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000399
400 if (MissingNilLoc.isInvalid())
401 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
402 else
403 Diag(MissingNilLoc, diag::warn_missing_sentinel)
404 << calleeType
405 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000406 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000407}
408
Richard Trieuccd891a2011-09-09 01:45:06 +0000409SourceRange Sema::getExprRange(Expr *E) const {
410 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000411}
412
Chris Lattnere7a2e912008-07-25 21:10:04 +0000413//===----------------------------------------------------------------------===//
414// Standard Promotions and Conversions
415//===----------------------------------------------------------------------===//
416
Chris Lattnere7a2e912008-07-25 21:10:04 +0000417/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000418ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000419 // Handle any placeholder expressions which made it here.
420 if (E->getType()->isPlaceholderType()) {
421 ExprResult result = CheckPlaceholderExpr(E);
422 if (result.isInvalid()) return ExprError();
423 E = result.take();
424 }
425
Chris Lattnere7a2e912008-07-25 21:10:04 +0000426 QualType Ty = E->getType();
427 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
428
Chris Lattnere7a2e912008-07-25 21:10:04 +0000429 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000430 E = ImpCastExprToType(E, Context.getPointerType(Ty),
431 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000432 else if (Ty->isArrayType()) {
433 // In C90 mode, arrays only promote to pointers if the array expression is
434 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
435 // type 'array of type' is converted to an expression that has type 'pointer
436 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
437 // that has type 'array of type' ...". The relevant change is "an lvalue"
438 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000439 //
440 // C++ 4.2p1:
441 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
442 // T" can be converted to an rvalue of type "pointer to T".
443 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000444 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000445 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
446 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000447 }
John Wiegley429bb272011-04-08 18:41:53 +0000448 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000449}
450
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000451static void CheckForNullPointerDereference(Sema &S, Expr *E) {
452 // Check to see if we are dereferencing a null pointer. If so,
453 // and if not volatile-qualified, this is undefined behavior that the
454 // optimizer will delete, so warn about it. People sometimes try to use this
455 // to get a deterministic trap and are surprised by clang's behavior. This
456 // only handles the pattern "*null", which is a very syntactic check.
457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
458 if (UO->getOpcode() == UO_Deref &&
459 UO->getSubExpr()->IgnoreParenCasts()->
460 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
461 !UO->getType().isVolatileQualified()) {
462 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
463 S.PDiag(diag::warn_indirection_through_null)
464 << UO->getSubExpr()->getSourceRange());
465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
466 S.PDiag(diag::note_indirection_through_null));
467 }
468}
469
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000470static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanian0c701812013-04-02 18:57:54 +0000471 SourceLocation AssignLoc,
472 const Expr* RHS) {
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000473 const ObjCIvarDecl *IV = OIRE->getDecl();
474 if (!IV)
475 return;
476
477 DeclarationName MemberName = IV->getDeclName();
478 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
479 if (!Member || !Member->isStr("isa"))
480 return;
481
482 const Expr *Base = OIRE->getBase();
483 QualType BaseType = Base->getType();
484 if (OIRE->isArrow())
485 BaseType = BaseType->getPointeeType();
486 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
487 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
488 ObjCInterfaceDecl *ClassDeclared = 0;
489 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
490 if (!ClassDeclared->getSuperClass()
491 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanian0c701812013-04-02 18:57:54 +0000492 if (RHS) {
493 NamedDecl *ObjectSetClass =
494 S.LookupSingleName(S.TUScope,
495 &S.Context.Idents.get("object_setClass"),
496 SourceLocation(), S.LookupOrdinaryName);
497 if (ObjectSetClass) {
498 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
499 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
500 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
501 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
502 AssignLoc), ",") <<
503 FixItHint::CreateInsertion(RHSLocEnd, ")");
504 }
505 else
506 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
507 } else {
508 NamedDecl *ObjectGetClass =
509 S.LookupSingleName(S.TUScope,
510 &S.Context.Idents.get("object_getClass"),
511 SourceLocation(), S.LookupOrdinaryName);
512 if (ObjectGetClass)
513 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
514 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
515 FixItHint::CreateReplacement(
516 SourceRange(OIRE->getOpLoc(),
517 OIRE->getLocEnd()), ")");
518 else
519 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
520 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000521 S.Diag(IV->getLocation(), diag::note_ivar_decl);
522 }
523 }
524}
525
John Wiegley429bb272011-04-08 18:41:53 +0000526ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000527 // Handle any placeholder expressions which made it here.
528 if (E->getType()->isPlaceholderType()) {
529 ExprResult result = CheckPlaceholderExpr(E);
530 if (result.isInvalid()) return ExprError();
531 E = result.take();
532 }
533
John McCall0ae287a2010-12-01 04:43:34 +0000534 // C++ [conv.lval]p1:
535 // A glvalue of a non-function, non-array type T can be
536 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000537 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000538
John McCall409fa9a2010-12-06 20:48:59 +0000539 QualType T = E->getType();
540 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000541
John McCall409fa9a2010-12-06 20:48:59 +0000542 // We don't want to throw lvalue-to-rvalue casts on top of
543 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000544 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000545 (E->getType() == Context.OverloadTy ||
546 T->isDependentType() ||
547 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000548 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000549
550 // The C standard is actually really unclear on this point, and
551 // DR106 tells us what the result should be but not why. It's
552 // generally best to say that void types just doesn't undergo
553 // lvalue-to-rvalue at all. Note that expressions of unqualified
554 // 'void' type are never l-values, but qualified void can be.
555 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000556 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000557
John McCall9dd74c52013-02-12 01:29:43 +0000558 // OpenCL usually rejects direct accesses to values of 'half' type.
559 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
560 T->isHalfType()) {
561 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
562 << 0 << T;
563 return ExprError();
564 }
565
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000566 CheckForNullPointerDereference(*this, E);
Fariborz Jahanianec8deba2013-03-28 19:50:55 +0000567 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
568 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
569 &Context.Idents.get("object_getClass"),
570 SourceLocation(), LookupOrdinaryName);
571 if (ObjectGetClass)
572 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
573 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
574 FixItHint::CreateReplacement(
575 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
576 else
577 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
578 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000579 else if (const ObjCIvarRefExpr *OIRE =
580 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Fariborz Jahanian0c701812013-04-02 18:57:54 +0000581 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000582
John McCall409fa9a2010-12-06 20:48:59 +0000583 // C++ [conv.lval]p1:
584 // [...] If T is a non-class type, the type of the prvalue is the
585 // cv-unqualified version of T. Otherwise, the type of the
586 // rvalue is T.
587 //
588 // C99 6.3.2.1p2:
589 // If the lvalue has qualified type, the value has the unqualified
590 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000591 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000592 if (T.hasQualifiers())
593 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000594
Eli Friedmand2cce132012-02-02 23:15:15 +0000595 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +0000596
597 // Loading a __weak object implicitly retains the value, so we need a cleanup to
598 // balance that.
599 if (getLangOpts().ObjCAutoRefCount &&
600 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
601 ExprNeedsCleanups = true;
Eli Friedmand2cce132012-02-02 23:15:15 +0000602
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000603 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
604 E, 0, VK_RValue));
605
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000606 // C11 6.3.2.1p2:
607 // ... if the lvalue has atomic type, the value has the non-atomic version
608 // of the type of the lvalue ...
609 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
610 T = Atomic->getValueType().getUnqualifiedType();
611 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
612 Res.get(), 0, VK_RValue));
613 }
614
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000615 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000616}
617
John Wiegley429bb272011-04-08 18:41:53 +0000618ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
619 ExprResult Res = DefaultFunctionArrayConversion(E);
620 if (Res.isInvalid())
621 return ExprError();
622 Res = DefaultLvalueConversion(Res.take());
623 if (Res.isInvalid())
624 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000625 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000626}
627
628
Chris Lattnere7a2e912008-07-25 21:10:04 +0000629/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000630/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000631/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000632/// apply if the array is an argument to the sizeof or address (&) operators.
633/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000634ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000635 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000636 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
637 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000638 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000639 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000640
John McCall0ae287a2010-12-01 04:43:34 +0000641 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000642 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000643
Joey Gouly19dbb202013-01-23 11:56:20 +0000644 // Half FP have to be promoted to float unless it is natively supported
645 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000646 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
647
John McCall0ae287a2010-12-01 04:43:34 +0000648 // Try to perform integral promotions if the object has a theoretically
649 // promotable type.
650 if (Ty->isIntegralOrUnscopedEnumerationType()) {
651 // C99 6.3.1.1p2:
652 //
653 // The following may be used in an expression wherever an int or
654 // unsigned int may be used:
655 // - an object or expression with an integer type whose integer
656 // conversion rank is less than or equal to the rank of int
657 // and unsigned int.
658 // - A bit-field of type _Bool, int, signed int, or unsigned int.
659 //
660 // If an int can represent all values of the original type, the
661 // value is converted to an int; otherwise, it is converted to an
662 // unsigned int. These are called the integer promotions. All
663 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000664
John McCall0ae287a2010-12-01 04:43:34 +0000665 QualType PTy = Context.isPromotableBitField(E);
666 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000667 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
668 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000669 }
670 if (Ty->isPromotableIntegerType()) {
671 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000672 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
673 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000674 }
Eli Friedman04e83572009-08-20 04:21:42 +0000675 }
John Wiegley429bb272011-04-08 18:41:53 +0000676 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000677}
678
Chris Lattner05faf172008-07-25 22:25:12 +0000679/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000680/// do not have a prototype. Arguments that have type float or __fp16
681/// are promoted to double. All other argument types are converted by
682/// UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000683ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
684 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000685 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000686
John Wiegley429bb272011-04-08 18:41:53 +0000687 ExprResult Res = UsualUnaryConversions(E);
688 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000689 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000690 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000691
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000692 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
693 // double.
694 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
695 if (BTy && (BTy->getKind() == BuiltinType::Half ||
696 BTy->getKind() == BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000697 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
698
John McCall96a914a2011-08-27 22:06:17 +0000699 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000700 // promotion, even on class types, but note:
701 // C++11 [conv.lval]p2:
702 // When an lvalue-to-rvalue conversion occurs in an unevaluated
703 // operand or a subexpression thereof the value contained in the
704 // referenced object is not accessed. Otherwise, if the glvalue
705 // has a class type, the conversion copy-initializes a temporary
706 // of type T from the glvalue and the result of the conversion
707 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000708 // FIXME: add some way to gate this entire thing for correctness in
709 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000710 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000711 ExprResult Temp = PerformCopyInitialization(
712 InitializedEntity::InitializeTemporary(E->getType()),
713 E->getExprLoc(),
714 Owned(E));
715 if (Temp.isInvalid())
716 return ExprError();
717 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000718 }
719
John Wiegley429bb272011-04-08 18:41:53 +0000720 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000721}
722
Richard Smith831421f2012-06-25 20:30:08 +0000723/// Determine the degree of POD-ness for an expression.
724/// Incomplete types are considered POD, since this check can be performed
725/// when we're in an unevaluated context.
726Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000727 if (Ty->isIncompleteType()) {
728 if (Ty->isObjCObjectType())
729 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000730 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000731 }
732
733 if (Ty.isCXX98PODType(Context))
734 return VAK_Valid;
735
Richard Smith426391c2012-11-16 00:53:38 +0000736 // C++11 [expr.call]p7:
737 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith831421f2012-06-25 20:30:08 +0000738 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith426391c2012-11-16 00:53:38 +0000739 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith831421f2012-06-25 20:30:08 +0000740 // is conditionally-supported with implementation-defined semantics.
Richard Smith80ad52f2013-01-02 11:42:31 +0000741 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith831421f2012-06-25 20:30:08 +0000742 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith426391c2012-11-16 00:53:38 +0000743 if (!Record->hasNonTrivialCopyConstructor() &&
744 !Record->hasNonTrivialMoveConstructor() &&
745 !Record->hasNonTrivialDestructor())
Richard Smith831421f2012-06-25 20:30:08 +0000746 return VAK_ValidInCXX11;
747
748 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
749 return VAK_Valid;
750 return VAK_Invalid;
751}
752
753bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
754 // Don't allow one to pass an Objective-C interface to a vararg.
755 const QualType & Ty = E->getType();
756
757 // Complain about passing non-POD types through varargs.
758 switch (isValidVarArgType(Ty)) {
759 case VAK_Valid:
760 break;
761 case VAK_ValidInCXX11:
762 DiagRuntimeBehavior(E->getLocStart(), 0,
763 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
764 << E->getType() << CT);
765 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000766 case VAK_Invalid: {
767 if (Ty->isObjCObjectType())
768 return DiagRuntimeBehavior(E->getLocStart(), 0,
769 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
770 << Ty << CT);
771
Richard Smith831421f2012-06-25 20:30:08 +0000772 return DiagRuntimeBehavior(E->getLocStart(), 0,
773 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Richard Smith80ad52f2013-01-02 11:42:31 +0000774 << getLangOpts().CPlusPlus11 << Ty << CT);
Richard Smith831421f2012-06-25 20:30:08 +0000775 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000776 }
Richard Smith831421f2012-06-25 20:30:08 +0000777 // c++ rules are enforced elsewhere.
778 return false;
779}
780
Chris Lattner312531a2009-04-12 08:11:20 +0000781/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000782/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000783ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000784 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000785 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000786 // Strip the unbridged-cast placeholder expression off, if applicable.
787 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
788 (CT == VariadicMethod ||
789 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
790 E = stripARCUnbridgedCast(E);
791
792 // Otherwise, do normal placeholder checking.
793 } else {
794 ExprResult ExprRes = CheckPlaceholderExpr(E);
795 if (ExprRes.isInvalid())
796 return ExprError();
797 E = ExprRes.take();
798 }
799 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000800
John McCall5acb0c92011-10-17 18:40:02 +0000801 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000802 if (ExprRes.isInvalid())
803 return ExprError();
804 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Richard Smith831421f2012-06-25 20:30:08 +0000806 // Diagnostics regarding non-POD argument types are
807 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000808 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000809 // Turn this into a trap.
810 CXXScopeSpec SS;
811 SourceLocation TemplateKWLoc;
812 UnqualifiedId Name;
813 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
814 E->getLocStart());
815 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
816 Name, true, false);
817 if (TrapFn.isInvalid())
818 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000819
Richard Smith831421f2012-06-25 20:30:08 +0000820 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000821 E->getLocStart(), None,
Richard Smith831421f2012-06-25 20:30:08 +0000822 E->getLocEnd());
823 if (Call.isInvalid())
824 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000825
Richard Smith831421f2012-06-25 20:30:08 +0000826 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
827 Call.get(), E);
828 if (Comma.isInvalid())
829 return ExprError();
830 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000831 }
Richard Smith831421f2012-06-25 20:30:08 +0000832
David Blaikie4e4d0842012-03-11 07:00:24 +0000833 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000834 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000835 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000836 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000837
John Wiegley429bb272011-04-08 18:41:53 +0000838 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000839}
840
Richard Trieu8289f492011-09-02 20:58:51 +0000841/// \brief Converts an integer to complex float type. Helper function of
842/// UsualArithmeticConversions()
843///
844/// \return false if the integer expression is an integer type and is
845/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000846static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
847 ExprResult &ComplexExpr,
848 QualType IntTy,
849 QualType ComplexTy,
850 bool SkipCast) {
851 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
852 if (SkipCast) return false;
853 if (IntTy->isIntegerType()) {
854 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
855 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
856 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000857 CK_FloatingRealToComplex);
858 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000859 assert(IntTy->isComplexIntegerType());
860 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000861 CK_IntegralComplexToFloatingComplex);
862 }
863 return false;
864}
865
866/// \brief Takes two complex float types and converts them to the same type.
867/// Helper function of UsualArithmeticConversions()
868static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000869handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
870 ExprResult &RHS, QualType LHSType,
871 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000872 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000873 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000874
875 if (order < 0) {
876 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000877 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
879 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000880 }
881 if (order > 0)
882 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
884 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000885}
886
887/// \brief Converts otherExpr to complex float and promotes complexExpr if
888/// necessary. Helper function of UsualArithmeticConversions()
889static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000890 ExprResult &ComplexExpr,
891 ExprResult &OtherExpr,
892 QualType ComplexTy,
893 QualType OtherTy,
894 bool ConvertComplexExpr,
895 bool ConvertOtherExpr) {
896 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000897
898 // If just the complexExpr is complex, the otherExpr needs to be converted,
899 // and the complexExpr might need to be promoted.
900 if (order > 0) { // complexExpr is wider
901 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000902 if (ConvertOtherExpr) {
903 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
904 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000906 CK_FloatingRealToComplex);
907 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000909 }
910
911 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000912 QualType result = (order == 0 ? ComplexTy :
913 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000914
915 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000916 if (ConvertOtherExpr)
917 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000918 CK_FloatingRealToComplex);
919
920 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000921 if (ConvertComplexExpr && order < 0)
922 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000923 CK_FloatingComplexCast);
924
925 return result;
926}
927
928/// \brief Handle arithmetic conversion with complex types. Helper function of
929/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000930static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
931 ExprResult &RHS, QualType LHSType,
932 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000933 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000934 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000935 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000936 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000937 return LHSType;
938 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000939 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000940 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000941
942 // This handles complex/complex, complex/float, or float/complex.
943 // When both operands are complex, the shorter operand is converted to the
944 // type of the longer, and that is the type of the result. This corresponds
945 // to what is done when combining two real floating-point operands.
946 // The fun begins when size promotion occur across type domains.
947 // From H&S 6.3.4: When one operand is complex and the other is a real
948 // floating-point type, the less precise type is converted, within it's
949 // real or complex domain, to the precision of the other type. For example,
950 // when combining a "long double" with a "double _Complex", the
951 // "double _Complex" is promoted to "long double _Complex".
952
Richard Trieucafd30b2011-09-06 18:25:09 +0000953 bool LHSComplexFloat = LHSType->isComplexType();
954 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000955
956 // If both are complex, just cast to the more precise type.
957 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000958 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
959 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000960 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000961
962 // If only one operand is complex, promote it if necessary and convert the
963 // other operand to complex.
964 if (LHSComplexFloat)
965 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000966 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000967 /*convertOtherExpr*/ true);
968
969 assert(RHSComplexFloat);
970 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000971 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000972 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000973}
974
975/// \brief Hande arithmetic conversion from integer to float. Helper function
976/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000977static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
978 ExprResult &IntExpr,
979 QualType FloatTy, QualType IntTy,
980 bool ConvertFloat, bool ConvertInt) {
981 if (IntTy->isIntegerType()) {
982 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000983 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000984 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000985 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000986 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000987 }
988
989 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000990 assert(IntTy->isComplexIntegerType());
991 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000992
993 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000994 if (ConvertInt)
995 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000996 CK_IntegralComplexToFloatingComplex);
997
998 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000999 if (ConvertFloat)
1000 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +00001001 CK_FloatingRealToComplex);
1002
1003 return result;
1004}
1005
1006/// \brief Handle arithmethic conversion with floating point types. Helper
1007/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001008static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1009 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001010 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001011 bool LHSFloat = LHSType->isRealFloatingType();
1012 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +00001013
1014 // If we have two real floating types, convert the smaller operand
1015 // to the bigger result.
1016 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001017 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +00001018 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001019 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1020 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001021 }
1022
1023 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +00001024 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001025 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1026 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001027 }
1028
1029 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001030 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001031 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +00001032 /*convertInt=*/ true);
1033 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001034 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +00001035 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +00001036 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +00001037}
1038
Bill Schmidt57dab712013-02-01 15:34:29 +00001039typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu8289f492011-09-02 20:58:51 +00001040
Bill Schmidt57dab712013-02-01 15:34:29 +00001041namespace {
1042/// These helper callbacks are placed in an anonymous namespace to
1043/// permit their use as function template parameters.
1044ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1045 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1046}
Richard Trieu8289f492011-09-02 20:58:51 +00001047
Bill Schmidt57dab712013-02-01 15:34:29 +00001048ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1049 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1050 CK_IntegralComplexCast);
1051}
Richard Trieu8289f492011-09-02 20:58:51 +00001052}
1053
1054/// \brief Handle integer arithmetic conversions. Helper function of
1055/// UsualArithmeticConversions()
Bill Schmidt57dab712013-02-01 15:34:29 +00001056template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001057static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1058 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001059 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +00001060 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001061 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1062 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1063 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1064 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +00001065 // Same signedness; use the higher-ranked type
1066 if (order >= 0) {
Bill Schmidt57dab712013-02-01 15:34:29 +00001067 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001068 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001069 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001070 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001071 return RHSType;
1072 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001073 // The unsigned type has greater than or equal rank to the
1074 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001075 if (RHSSigned) {
Bill Schmidt57dab712013-02-01 15:34:29 +00001076 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001077 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001078 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001079 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001080 return RHSType;
1081 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001082 // The two types are different widths; if we are here, that
1083 // means the signed type is larger than the unsigned type, so
1084 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001085 if (LHSSigned) {
Bill Schmidt57dab712013-02-01 15:34:29 +00001086 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001087 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001088 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001089 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001090 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001091 } else {
1092 // The signed type is higher-ranked than the unsigned type,
1093 // but isn't actually any bigger (like unsigned int and long
1094 // on most 32-bit systems). Use the unsigned type corresponding
1095 // to the signed type.
1096 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001097 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Bill Schmidt57dab712013-02-01 15:34:29 +00001098 RHS = (*doRHSCast)(S, RHS.take(), result);
Richard Trieuccd891a2011-09-09 01:45:06 +00001099 if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001100 LHS = (*doLHSCast)(S, LHS.take(), result);
Richard Trieu8289f492011-09-02 20:58:51 +00001101 return result;
1102 }
1103}
1104
Bill Schmidt57dab712013-02-01 15:34:29 +00001105/// \brief Handle conversions with GCC complex int extension. Helper function
1106/// of UsualArithmeticConversions()
1107static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1108 ExprResult &RHS, QualType LHSType,
1109 QualType RHSType,
1110 bool IsCompAssign) {
1111 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1112 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1113
1114 if (LHSComplexInt && RHSComplexInt) {
1115 QualType LHSEltType = LHSComplexInt->getElementType();
1116 QualType RHSEltType = RHSComplexInt->getElementType();
1117 QualType ScalarType =
1118 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1119 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1120
1121 return S.Context.getComplexType(ScalarType);
1122 }
1123
1124 if (LHSComplexInt) {
1125 QualType LHSEltType = LHSComplexInt->getElementType();
1126 QualType ScalarType =
1127 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1128 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1129 QualType ComplexType = S.Context.getComplexType(ScalarType);
1130 RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1131 CK_IntegralRealToComplex);
1132
1133 return ComplexType;
1134 }
1135
1136 assert(RHSComplexInt);
1137
1138 QualType RHSEltType = RHSComplexInt->getElementType();
1139 QualType ScalarType =
1140 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1141 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1142 QualType ComplexType = S.Context.getComplexType(ScalarType);
1143
1144 if (!IsCompAssign)
1145 LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1146 CK_IntegralRealToComplex);
1147 return ComplexType;
1148}
1149
Chris Lattnere7a2e912008-07-25 21:10:04 +00001150/// UsualArithmeticConversions - Performs various conversions that are common to
1151/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001152/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001153/// responsible for emitting appropriate error diagnostics.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001154QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001155 bool IsCompAssign) {
1156 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001157 LHS = UsualUnaryConversions(LHS.take());
1158 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001159 return QualType();
1160 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001161
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001162 RHS = UsualUnaryConversions(RHS.take());
1163 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001164 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001165
Mike Stump1eb44332009-09-09 15:08:12 +00001166 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001167 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001168 QualType LHSType =
1169 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1170 QualType RHSType =
1171 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001172
Eli Friedman860a3192012-06-16 02:19:17 +00001173 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1174 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1175 LHSType = AtomicLHS->getValueType();
1176
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001177 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001178 if (LHSType == RHSType)
1179 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001180
1181 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1182 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001183 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001184 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001185
John McCallcf33b242010-11-13 08:17:45 +00001186 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001187 QualType LHSUnpromotedType = LHSType;
1188 if (LHSType->isPromotableIntegerType())
1189 LHSType = Context.getPromotedIntegerType(LHSType);
1190 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001191 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001192 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001193 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001194 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001195
John McCallcf33b242010-11-13 08:17:45 +00001196 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001197 if (LHSType == RHSType)
1198 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001199
1200 // At this point, we have two different arithmetic types.
1201
1202 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001203 if (LHSType->isComplexType() || RHSType->isComplexType())
1204 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001205 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001206
1207 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001208 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1209 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001210 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001211
1212 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001213 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001214 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001215 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001216
1217 // Finally, we have two differing integer types.
Bill Schmidt57dab712013-02-01 15:34:29 +00001218 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1219 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001220}
1221
Bill Schmidt57dab712013-02-01 15:34:29 +00001222
Chris Lattnere7a2e912008-07-25 21:10:04 +00001223//===----------------------------------------------------------------------===//
1224// Semantic Analysis for various Expression Types
1225//===----------------------------------------------------------------------===//
1226
1227
Peter Collingbournef111d932011-04-15 00:35:48 +00001228ExprResult
1229Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1230 SourceLocation DefaultLoc,
1231 SourceLocation RParenLoc,
1232 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001233 MultiTypeArg ArgTypes,
1234 MultiExprArg ArgExprs) {
1235 unsigned NumAssocs = ArgTypes.size();
1236 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001237
Benjamin Kramer5354e772012-08-23 23:38:35 +00001238 ParsedType *ParsedTypes = ArgTypes.data();
1239 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001240
1241 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1242 for (unsigned i = 0; i < NumAssocs; ++i) {
1243 if (ParsedTypes[i])
1244 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1245 else
1246 Types[i] = 0;
1247 }
1248
1249 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1250 ControllingExpr, Types, Exprs,
1251 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001252 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001253 return ER;
1254}
1255
1256ExprResult
1257Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1258 SourceLocation DefaultLoc,
1259 SourceLocation RParenLoc,
1260 Expr *ControllingExpr,
1261 TypeSourceInfo **Types,
1262 Expr **Exprs,
1263 unsigned NumAssocs) {
John McCalla2905ea2013-02-12 02:08:12 +00001264 if (ControllingExpr->getType()->isPlaceholderType()) {
1265 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1266 if (result.isInvalid()) return ExprError();
1267 ControllingExpr = result.take();
1268 }
1269
Peter Collingbournef111d932011-04-15 00:35:48 +00001270 bool TypeErrorFound = false,
1271 IsResultDependent = ControllingExpr->isTypeDependent(),
1272 ContainsUnexpandedParameterPack
1273 = ControllingExpr->containsUnexpandedParameterPack();
1274
1275 for (unsigned i = 0; i < NumAssocs; ++i) {
1276 if (Exprs[i]->containsUnexpandedParameterPack())
1277 ContainsUnexpandedParameterPack = true;
1278
1279 if (Types[i]) {
1280 if (Types[i]->getType()->containsUnexpandedParameterPack())
1281 ContainsUnexpandedParameterPack = true;
1282
1283 if (Types[i]->getType()->isDependentType()) {
1284 IsResultDependent = true;
1285 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001286 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001287 // complete object type other than a variably modified type."
1288 unsigned D = 0;
1289 if (Types[i]->getType()->isIncompleteType())
1290 D = diag::err_assoc_type_incomplete;
1291 else if (!Types[i]->getType()->isObjectType())
1292 D = diag::err_assoc_type_nonobject;
1293 else if (Types[i]->getType()->isVariablyModifiedType())
1294 D = diag::err_assoc_type_variably_modified;
1295
1296 if (D != 0) {
1297 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1298 << Types[i]->getTypeLoc().getSourceRange()
1299 << Types[i]->getType();
1300 TypeErrorFound = true;
1301 }
1302
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001303 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001304 // selection shall specify compatible types."
1305 for (unsigned j = i+1; j < NumAssocs; ++j)
1306 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1307 Context.typesAreCompatible(Types[i]->getType(),
1308 Types[j]->getType())) {
1309 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1310 diag::err_assoc_compatible_types)
1311 << Types[j]->getTypeLoc().getSourceRange()
1312 << Types[j]->getType()
1313 << Types[i]->getType();
1314 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1315 diag::note_compat_assoc)
1316 << Types[i]->getTypeLoc().getSourceRange()
1317 << Types[i]->getType();
1318 TypeErrorFound = true;
1319 }
1320 }
1321 }
1322 }
1323 if (TypeErrorFound)
1324 return ExprError();
1325
1326 // If we determined that the generic selection is result-dependent, don't
1327 // try to compute the result expression.
1328 if (IsResultDependent)
1329 return Owned(new (Context) GenericSelectionExpr(
1330 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001331 llvm::makeArrayRef(Types, NumAssocs),
1332 llvm::makeArrayRef(Exprs, NumAssocs),
1333 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001334
Chris Lattner5f9e2722011-07-23 10:55:15 +00001335 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001336 unsigned DefaultIndex = -1U;
1337 for (unsigned i = 0; i < NumAssocs; ++i) {
1338 if (!Types[i])
1339 DefaultIndex = i;
1340 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1341 Types[i]->getType()))
1342 CompatIndices.push_back(i);
1343 }
1344
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001345 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001346 // type compatible with at most one of the types named in its generic
1347 // association list."
1348 if (CompatIndices.size() > 1) {
1349 // We strip parens here because the controlling expression is typically
1350 // parenthesized in macro definitions.
1351 ControllingExpr = ControllingExpr->IgnoreParens();
1352 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1353 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1354 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001355 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001356 E = CompatIndices.end(); I != E; ++I) {
1357 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1358 diag::note_compat_assoc)
1359 << Types[*I]->getTypeLoc().getSourceRange()
1360 << Types[*I]->getType();
1361 }
1362 return ExprError();
1363 }
1364
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001365 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001366 // its controlling expression shall have type compatible with exactly one of
1367 // the types named in its generic association list."
1368 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1369 // We strip parens here because the controlling expression is typically
1370 // parenthesized in macro definitions.
1371 ControllingExpr = ControllingExpr->IgnoreParens();
1372 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1373 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1374 return ExprError();
1375 }
1376
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001377 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001378 // type name that is compatible with the type of the controlling expression,
1379 // then the result expression of the generic selection is the expression
1380 // in that generic association. Otherwise, the result expression of the
1381 // generic selection is the expression in the default generic association."
1382 unsigned ResultIndex =
1383 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1384
1385 return Owned(new (Context) GenericSelectionExpr(
1386 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001387 llvm::makeArrayRef(Types, NumAssocs),
1388 llvm::makeArrayRef(Exprs, NumAssocs),
1389 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001390 ResultIndex));
1391}
1392
Richard Smithdd66be72012-03-08 01:34:56 +00001393/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1394/// location of the token and the offset of the ud-suffix within it.
1395static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1396 unsigned Offset) {
1397 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001398 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001399}
1400
Richard Smith36f5cfe2012-03-09 08:00:36 +00001401/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1402/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1403static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1404 IdentifierInfo *UDSuffix,
1405 SourceLocation UDSuffixLoc,
1406 ArrayRef<Expr*> Args,
1407 SourceLocation LitEndLoc) {
1408 assert(Args.size() <= 2 && "too many arguments for literal operator");
1409
1410 QualType ArgTy[2];
1411 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1412 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1413 if (ArgTy[ArgIdx]->isArrayType())
1414 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1415 }
1416
1417 DeclarationName OpName =
1418 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1419 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1420 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1421
1422 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1423 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1424 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1425 return ExprError();
1426
1427 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1428}
1429
Steve Narofff69936d2007-09-16 03:34:24 +00001430/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001431/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1432/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1433/// multiple tokens. However, the common case is that StringToks points to one
1434/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001435///
John McCall60d7b3a2010-08-24 06:29:42 +00001436ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001437Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1438 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 assert(NumStringToks && "Must have at least one string!");
1440
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001441 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001443 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001444
Chris Lattner5f9e2722011-07-23 10:55:15 +00001445 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 for (unsigned i = 0; i != NumStringToks; ++i)
1447 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001448
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001449 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001450 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001451 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001452 else if (Literal.isUTF16())
1453 StrTy = Context.Char16Ty;
1454 else if (Literal.isUTF32())
1455 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001456 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001457 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001458
Douglas Gregor5cee1192011-07-27 05:40:30 +00001459 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1460 if (Literal.isWide())
1461 Kind = StringLiteral::Wide;
1462 else if (Literal.isUTF8())
1463 Kind = StringLiteral::UTF8;
1464 else if (Literal.isUTF16())
1465 Kind = StringLiteral::UTF16;
1466 else if (Literal.isUTF32())
1467 Kind = StringLiteral::UTF32;
1468
Douglas Gregor77a52232008-09-12 00:47:35 +00001469 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001470 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001471 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001472
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001473 // Get an array type for the string, according to C99 6.4.5. This includes
1474 // the nul terminator character as well as the string length for pascal
1475 // strings.
1476 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001477 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001478 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001481 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1482 Kind, Literal.Pascal, StrTy,
1483 &StringTokLocs[0],
1484 StringTokLocs.size());
1485 if (Literal.getUDSuffix().empty())
1486 return Owned(Lit);
1487
1488 // We're building a user-defined literal.
1489 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001490 SourceLocation UDSuffixLoc =
1491 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1492 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001493
Richard Smith36f5cfe2012-03-09 08:00:36 +00001494 // Make sure we're allowed user-defined literals here.
1495 if (!UDLScope)
1496 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1497
Richard Smith9fcce652012-03-07 08:35:16 +00001498 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1499 // operator "" X (str, len)
1500 QualType SizeType = Context.getSizeType();
1501 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1502 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1503 StringTokLocs[0]);
1504 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001505 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1506 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001507}
1508
John McCall60d7b3a2010-08-24 06:29:42 +00001509ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001510Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001511 SourceLocation Loc,
1512 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001513 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001514 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001515}
1516
John McCall76a40212011-02-09 01:13:10 +00001517/// BuildDeclRefExpr - Build an expression that references a
1518/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001519ExprResult
John McCall76a40212011-02-09 01:13:10 +00001520Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001521 const DeclarationNameInfo &NameInfo,
Daniel Jasper8ff563c2013-03-22 10:01:35 +00001522 const CXXScopeSpec *SS, NamedDecl *FoundD) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001523 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001524 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1525 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1526 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1527 CalleeTarget = IdentifyCUDATarget(Callee);
1528 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1529 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1530 << CalleeTarget << D->getIdentifier() << CallerTarget;
1531 Diag(D->getLocation(), diag::note_previous_decl)
1532 << D->getIdentifier();
1533 return ExprError();
1534 }
1535 }
1536
John McCallf4b88a42012-03-10 09:33:50 +00001537 bool refersToEnclosingScope =
1538 (CurContext != D->getDeclContext() &&
1539 D->getDeclContext()->isFunctionOrMethod());
1540
Eli Friedman5f2987c2012-02-02 03:46:19 +00001541 DeclRefExpr *E = DeclRefExpr::Create(Context,
1542 SS ? SS->getWithLocInContext(Context)
1543 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001544 SourceLocation(),
1545 D, refersToEnclosingScope,
Daniel Jasper8ff563c2013-03-22 10:01:35 +00001546 NameInfo, Ty, VK, FoundD);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Eli Friedman5f2987c2012-02-02 03:46:19 +00001548 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001549
Jordan Rose7a270482012-09-28 22:21:35 +00001550 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1551 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1552 DiagnosticsEngine::Level Level =
1553 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1554 E->getLocStart());
1555 if (Level != DiagnosticsEngine::Ignored)
1556 getCurFunction()->recordUseOfWeak(E);
1557 }
1558
John McCall7eb0a9e2010-11-24 05:12:34 +00001559 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001560 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1561 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001562 E->setObjectKind(OK_BitField);
1563
1564 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001565}
1566
Abramo Bagnara25777432010-08-11 22:01:17 +00001567/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001568/// possibly a list of template arguments.
1569///
1570/// If this produces template arguments, it is permitted to call
1571/// DecomposeTemplateName.
1572///
1573/// This actually loses a lot of source location information for
1574/// non-standard name kinds; we should consider preserving that in
1575/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001576void
1577Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1578 TemplateArgumentListInfo &Buffer,
1579 DeclarationNameInfo &NameInfo,
1580 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001581 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1582 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1583 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1584
Benjamin Kramer5354e772012-08-23 23:38:35 +00001585 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001586 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001587 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001588
John McCall2b5289b2010-08-23 07:28:44 +00001589 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001590 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001591 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001592 TemplateArgs = &Buffer;
1593 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001594 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001595 TemplateArgs = 0;
1596 }
1597}
1598
John McCall578b69b2009-12-16 08:11:27 +00001599/// Diagnose an empty lookup.
1600///
1601/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001602bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001603 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001604 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001605 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001606 DeclarationName Name = R.getLookupName();
1607
John McCall578b69b2009-12-16 08:11:27 +00001608 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001609 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001610 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1611 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001612 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001613 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001614 diagnostic_suggest = diag::err_undeclared_use_suggest;
1615 }
John McCall578b69b2009-12-16 08:11:27 +00001616
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001617 // If the original lookup was an unqualified lookup, fake an
1618 // unqualified lookup. This is useful when (for example) the
1619 // original lookup would not have found something because it was a
1620 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001621 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1622 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001623 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001624 if (isa<CXXRecordDecl>(DC)) {
1625 LookupQualifiedName(R, DC);
1626
1627 if (!R.empty()) {
1628 // Don't give errors about ambiguities in this lookup.
1629 R.suppressDiagnostics();
1630
Francois Pichete6226ae2011-11-17 03:44:24 +00001631 // During a default argument instantiation the CurContext points
1632 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1633 // function parameter list, hence add an explicit check.
1634 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1635 ActiveTemplateInstantiations.back().Kind ==
1636 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001637 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1638 bool isInstance = CurMethod &&
1639 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001640 DC == CurMethod->getParent() && !isDefaultArgument;
1641
John McCall578b69b2009-12-16 08:11:27 +00001642
1643 // Give a code modification hint to insert 'this->'.
1644 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1645 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001646 if (getLangOpts().MicrosoftMode)
1647 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001648 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001649 Diag(R.getNameLoc(), diagnostic) << Name
1650 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001651 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1652 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001653
Nico Weber94c4d612012-06-22 16:39:39 +00001654 CXXMethodDecl *DepMethod;
Douglas Gregore79ce292013-03-26 22:43:55 +00001655 if (CurMethod->isDependentContext())
1656 DepMethod = CurMethod;
1657 else if (CurMethod->getTemplatedKind() ==
Nico Weber94c4d612012-06-22 16:39:39 +00001658 FunctionDecl::TK_FunctionTemplateSpecialization)
1659 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1660 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1661 else
1662 DepMethod = cast<CXXMethodDecl>(
1663 CurMethod->getInstantiatedFromMemberFunction());
1664 assert(DepMethod && "No template pattern found");
1665
1666 QualType DepThisType = DepMethod->getThisType(Context);
1667 CheckCXXThisCapture(R.getNameLoc());
1668 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1669 R.getNameLoc(), DepThisType, false);
1670 TemplateArgumentListInfo TList;
1671 if (ULE->hasExplicitTemplateArgs())
1672 ULE->copyTemplateArgumentsInto(TList);
1673
1674 CXXScopeSpec SS;
1675 SS.Adopt(ULE->getQualifierLoc());
1676 CXXDependentScopeMemberExpr *DepExpr =
1677 CXXDependentScopeMemberExpr::Create(
1678 Context, DepThis, DepThisType, true, SourceLocation(),
1679 SS.getWithLocInContext(Context),
1680 ULE->getTemplateKeywordLoc(), 0,
1681 R.getLookupNameInfo(),
1682 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1683 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001684 } else {
John McCall578b69b2009-12-16 08:11:27 +00001685 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001686 }
John McCall578b69b2009-12-16 08:11:27 +00001687
1688 // Do we really want to note all of these?
1689 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1690 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1691
Francois Pichete6226ae2011-11-17 03:44:24 +00001692 // Return true if we are inside a default argument instantiation
1693 // and the found name refers to an instance member function, otherwise
1694 // the function calling DiagnoseEmptyLookup will try to create an
1695 // implicit member call and this is wrong for default argument.
1696 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1697 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1698 return true;
1699 }
1700
John McCall578b69b2009-12-16 08:11:27 +00001701 // Tell the callee to try to recover.
1702 return false;
1703 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001704
1705 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001706 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001707
1708 // In Microsoft mode, if we are performing lookup from within a friend
1709 // function definition declared at class scope then we must set
1710 // DC to the lexical parent to be able to search into the parent
1711 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001712 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001713 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1714 DC->getLexicalParent()->isRecord())
1715 DC = DC->getLexicalParent();
1716 else
1717 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001718 }
1719
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001720 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001721 TypoCorrection Corrected;
1722 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001723 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001724 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1725 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001726 R.setLookupName(Corrected.getCorrection());
1727
Hans Wennborg701d1e72011-07-12 08:45:31 +00001728 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001729 if (Corrected.isOverloaded()) {
1730 OverloadCandidateSet OCS(R.getNameLoc());
1731 OverloadCandidateSet::iterator Best;
1732 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1733 CDEnd = Corrected.end();
1734 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001735 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001736 dyn_cast<FunctionTemplateDecl>(*CD))
1737 AddTemplateOverloadCandidate(
1738 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001739 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001740 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1741 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1742 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001743 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001744 }
1745 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1746 case OR_Success:
1747 ND = Best->Function;
1748 break;
1749 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001750 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001751 }
1752 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001753 R.addDecl(ND);
1754 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001755 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001756 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1757 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001758 else
1759 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001760 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001761 << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00001762 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1763 CorrectedStr);
Ted Kremenek63631bd2013-02-21 21:40:44 +00001764
Ted Kremenek94f3f542013-02-21 22:10:49 +00001765 unsigned diag = isa<ImplicitParamDecl>(ND)
1766 ? diag::note_implicit_param_decl
1767 : diag::note_previous_decl;
1768
1769 Diag(ND->getLocation(), diag)
1770 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001771
1772 // Tell the callee to try to recover.
1773 return false;
1774 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001775
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001776 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001777 // FIXME: If we ended up with a typo for a type name or
1778 // Objective-C class name, we're in trouble because the parser
1779 // is in the wrong place to recover. Suggest the typo
1780 // correction, but don't make it a fix-it since we're not going
1781 // to recover well anyway.
1782 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001783 Diag(R.getNameLoc(), diagnostic_suggest)
1784 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001785 else
1786 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001787 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001788 << SS.getRange();
1789
1790 // Don't try to recover; it won't work.
1791 return true;
1792 }
1793 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001794 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001795 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001796 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001797 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001798 else
Douglas Gregord203a162010-01-01 00:15:04 +00001799 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001800 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001801 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001802 return true;
1803 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001804 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001805 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001806
1807 // Emit a special diagnostic for failed member lookups.
1808 // FIXME: computing the declaration context might fail here (?)
1809 if (!SS.isEmpty()) {
1810 Diag(R.getNameLoc(), diag::err_no_member)
1811 << Name << computeDeclContext(SS, false)
1812 << SS.getRange();
1813 return true;
1814 }
1815
John McCall578b69b2009-12-16 08:11:27 +00001816 // Give up, we can't recover.
1817 Diag(R.getNameLoc(), diagnostic) << Name;
1818 return true;
1819}
1820
John McCall60d7b3a2010-08-24 06:29:42 +00001821ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001822 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001823 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001824 UnqualifiedId &Id,
1825 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001826 bool IsAddressOfOperand,
1827 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001828 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001829 "cannot be direct & operand and have a trailing lparen");
1830
1831 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001832 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001833
John McCall129e2df2009-11-30 22:42:35 +00001834 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001835
1836 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001837 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001838 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001839 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001840
Abramo Bagnara25777432010-08-11 22:01:17 +00001841 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001842 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001843 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001844
John McCallf7a1a742009-11-24 19:00:30 +00001845 // C++ [temp.dep.expr]p3:
1846 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001847 // -- an identifier that was declared with a dependent type,
1848 // (note: handled after lookup)
1849 // -- a template-id that is dependent,
1850 // (note: handled in BuildTemplateIdExpr)
1851 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001852 // -- a nested-name-specifier that contains a class-name that
1853 // names a dependent type.
1854 // Determine whether this is a member of an unknown specialization;
1855 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001856 bool DependentID = false;
1857 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1858 Name.getCXXNameType()->isDependentType()) {
1859 DependentID = true;
1860 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001861 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001862 if (RequireCompleteDeclContext(SS, DC))
1863 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001864 } else {
1865 DependentID = true;
1866 }
1867 }
1868
Chris Lattner337e5502011-02-18 01:27:55 +00001869 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001870 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1871 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001872
John McCallf7a1a742009-11-24 19:00:30 +00001873 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001874 LookupResult R(*this, NameInfo,
1875 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1876 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001877 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001878 // Lookup the template name again to correctly establish the context in
1879 // which it was found. This is really unfortunate as we already did the
1880 // lookup to determine that it was a template name in the first place. If
1881 // this becomes a performance hit, we can work harder to preserve those
1882 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001883 bool MemberOfUnknownSpecialization;
1884 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1885 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001886
1887 if (MemberOfUnknownSpecialization ||
1888 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1890 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001891 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001892 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001893 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001895 // If the result might be in a dependent base class, this is a dependent
1896 // id-expression.
1897 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001898 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1899 IsAddressOfOperand, TemplateArgs);
1900
John McCallf7a1a742009-11-24 19:00:30 +00001901 // If this reference is in an Objective-C method, then we need to do
1902 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001903 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001904 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001905 if (E.isInvalid())
1906 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Chris Lattner337e5502011-02-18 01:27:55 +00001908 if (Expr *Ex = E.takeAs<Expr>())
1909 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001910 }
Chris Lattner8a934232008-03-31 00:36:02 +00001911 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001912
John McCallf7a1a742009-11-24 19:00:30 +00001913 if (R.isAmbiguous())
1914 return ExprError();
1915
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001916 // Determine whether this name might be a candidate for
1917 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001919
John McCallf7a1a742009-11-24 19:00:30 +00001920 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001922 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001923 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001924 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1925 if (D) R.addDecl(D);
1926 }
1927
1928 // If this name wasn't predeclared and if this is not a function
1929 // call, diagnose the problem.
1930 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001931 // In Microsoft mode, if we are inside a template class member function
Richard Smith97aea952013-04-29 08:45:27 +00001932 // whose parent class has dependent base classes, and we can't resolve
1933 // an identifier, then assume the identifier is type dependent. The
1934 // goal is to postpone name lookup to instantiation time to be able to
1935 // search into the type dependent base classes.
1936 if (getLangOpts().MicrosoftMode) {
1937 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
1938 if (MD && MD->getParent()->hasAnyDependentBases())
1939 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1940 IsAddressOfOperand, TemplateArgs);
1941 }
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001942
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001943 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001944 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001945 return ExprError();
1946
1947 assert(!R.empty() &&
1948 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001949
1950 // If we found an Objective-C instance variable, let
1951 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001952 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001953 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1954 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001955 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001956 // In a hopelessly buggy code, Objective-C instance variable
1957 // lookup fails and no expression will be built to reference it.
1958 if (!E.isInvalid() && !E.get())
1959 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001960 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001961 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 }
1963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
John McCallf7a1a742009-11-24 19:00:30 +00001965 // This is guaranteed from this point on.
1966 assert(!R.empty() || ADL);
1967
John McCallaa81e162009-12-01 22:10:20 +00001968 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001969 // C++ [class.mfct.non-static]p3:
1970 // When an id-expression that is not part of a class member access
1971 // syntax and not used to form a pointer to member is used in the
1972 // body of a non-static member function of class X, if name lookup
1973 // resolves the name in the id-expression to a non-static non-type
1974 // member of some class C, the id-expression is transformed into a
1975 // class member access expression using (*this) as the
1976 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001977 //
1978 // But we don't actually need to do this for '&' operands if R
1979 // resolved to a function or overloaded function set, because the
1980 // expression is ill-formed if it actually works out to be a
1981 // non-static member function:
1982 //
1983 // C++ [expr.ref]p4:
1984 // Otherwise, if E1.E2 refers to a non-static member function. . .
1985 // [t]he expression can be used only as the left-hand operand of a
1986 // member function call.
1987 //
1988 // There are other safeguards against such uses, but it's important
1989 // to get this right here so that we don't end up making a
1990 // spuriously dependent expression if we're inside a dependent
1991 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001992 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001993 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001994 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001995 MightBeImplicitMember = true;
1996 else if (!SS.isEmpty())
1997 MightBeImplicitMember = false;
1998 else if (R.isOverloadedResult())
1999 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00002000 else if (R.isUnresolvableResult())
2001 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00002002 else
Francois Pichet87c2e122010-11-21 06:08:52 +00002003 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2004 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00002005
2006 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002007 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2008 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002009 }
2010
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002011 if (TemplateArgs || TemplateKWLoc.isValid())
2012 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002013
John McCallf7a1a742009-11-24 19:00:30 +00002014 return BuildDeclarationNameExpr(SS, R, ADL);
2015}
2016
John McCall129e2df2009-11-30 22:42:35 +00002017/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2018/// declaration name, generally during template instantiation.
2019/// There's a large number of things which don't need to be done along
2020/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002021ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002022Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithefeeccf2012-10-21 03:28:35 +00002023 const DeclarationNameInfo &NameInfo,
2024 bool IsAddressOfOperand) {
Richard Smith713c2872012-10-23 19:56:01 +00002025 DeclContext *DC = computeDeclContext(SS, false);
2026 if (!DC)
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002027 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2028 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00002029
John McCall77bb1aa2010-05-01 00:40:08 +00002030 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002031 return ExprError();
2032
Abramo Bagnara25777432010-08-11 22:01:17 +00002033 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002034 LookupQualifiedName(R, DC);
2035
2036 if (R.isAmbiguous())
2037 return ExprError();
2038
Richard Smith713c2872012-10-23 19:56:01 +00002039 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2040 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2041 NameInfo, /*TemplateArgs=*/0);
2042
John McCallf7a1a742009-11-24 19:00:30 +00002043 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002044 Diag(NameInfo.getLoc(), diag::err_no_member)
2045 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002046 return ExprError();
2047 }
2048
Richard Smithefeeccf2012-10-21 03:28:35 +00002049 // Defend against this resolving to an implicit member access. We usually
2050 // won't get here if this might be a legitimate a class member (we end up in
2051 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2052 // a pointer-to-member or in an unevaluated context in C++11.
2053 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2054 return BuildPossibleImplicitMemberExpr(SS,
2055 /*TemplateKWLoc=*/SourceLocation(),
2056 R, /*TemplateArgs=*/0);
2057
2058 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00002059}
2060
2061/// LookupInObjCMethod - The parser has read a name in, and Sema has
2062/// detected that we're currently inside an ObjC method. Perform some
2063/// additional lookup.
2064///
2065/// Ideally, most of this would be done by lookup, but there's
2066/// actually quite a lot of extra work involved.
2067///
2068/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002069ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002070Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002071 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002072 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002073 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian0dc4ff22013-02-18 17:22:23 +00002074
2075 // Check for error condition which is already reported.
2076 if (!CurMethod)
2077 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002078
John McCallf7a1a742009-11-24 19:00:30 +00002079 // There are two cases to handle here. 1) scoped lookup could have failed,
2080 // in which case we should look for an ivar. 2) scoped lookup could have
2081 // found a decl, but that decl is outside the current instance method (i.e.
2082 // a global variable). In these two cases, we do a lookup for an ivar with
2083 // this name, if the lookup sucedes, we replace it our current decl.
2084
2085 // If we're in a class method, we don't normally want to look for
2086 // ivars. But if we don't find anything else, and there's an
2087 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002088 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002089
2090 bool LookForIvars;
2091 if (Lookup.empty())
2092 LookForIvars = true;
2093 else if (IsClassMethod)
2094 LookForIvars = false;
2095 else
2096 LookForIvars = (Lookup.isSingleResult() &&
2097 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002098 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002099 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002100 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002101 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00002102 ObjCIvarDecl *IV = 0;
2103 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00002104 // Diagnose using an ivar in a class method.
2105 if (IsClassMethod)
2106 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2107 << IV->getDeclName());
2108
2109 // If we're referencing an invalid decl, just return this as a silent
2110 // error node. The error diagnostic was already emitted on the decl.
2111 if (IV->isInvalidDecl())
2112 return ExprError();
2113
2114 // Check if referencing a field with __attribute__((deprecated)).
2115 if (DiagnoseUseOfDecl(IV, Loc))
2116 return ExprError();
2117
2118 // Diagnose the use of an ivar outside of the declaring class.
2119 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00002120 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002121 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00002122 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2123
2124 // FIXME: This should use a new expr for a direct reference, don't
2125 // turn this into Self->ivar, just return a BareIVarExpr or something.
2126 IdentifierInfo &II = Context.Idents.get("self");
2127 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002128 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00002129 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00002130 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002131 SourceLocation TemplateKWLoc;
2132 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002133 SelfName, false, false);
2134 if (SelfExpr.isInvalid())
2135 return ExprError();
2136
John Wiegley429bb272011-04-08 18:41:53 +00002137 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2138 if (SelfExpr.isInvalid())
2139 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002140
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +00002141 MarkAnyDeclReferenced(Loc, IV, true);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002142
2143 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahanian26202292013-02-14 19:07:19 +00002144 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2145 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002146 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002147
2148 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00002149 Loc, IV->getLocation(),
Jordan Rose7a270482012-09-28 22:21:35 +00002150 SelfExpr.take(),
2151 true, true);
2152
2153 if (getLangOpts().ObjCAutoRefCount) {
2154 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2155 DiagnosticsEngine::Level Level =
2156 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2157 if (Level != DiagnosticsEngine::Ignored)
2158 getCurFunction()->recordUseOfWeak(Result);
2159 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002160 if (CurContext->isClosure())
2161 Diag(Loc, diag::warn_implicitly_retains_self)
2162 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002163 }
2164
2165 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002166 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002167 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002168 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002169 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2170 ObjCInterfaceDecl *ClassDeclared;
2171 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2172 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002173 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002174 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2175 }
John McCallf7a1a742009-11-24 19:00:30 +00002176 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002177 } else if (Lookup.isSingleResult() &&
2178 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2179 // If accessing a stand-alone ivar in a class method, this is an error.
2180 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2181 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2182 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002183 }
2184
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002185 if (Lookup.empty() && II && AllowBuiltinCreation) {
2186 // FIXME. Consolidate this with similar code in LookupName.
2187 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002188 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002189 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2190 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2191 S, Lookup.isForRedeclaration(),
2192 Lookup.getNameLoc());
2193 if (D) Lookup.addDecl(D);
2194 }
2195 }
2196 }
John McCallf7a1a742009-11-24 19:00:30 +00002197 // Sentinel value saying that we didn't do anything special.
2198 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002199}
John McCallba135432009-11-21 08:51:07 +00002200
John McCall6bb80172010-03-30 21:47:33 +00002201/// \brief Cast a base object to a member's actual type.
2202///
2203/// Logically this happens in three phases:
2204///
2205/// * First we cast from the base type to the naming class.
2206/// The naming class is the class into which we were looking
2207/// when we found the member; it's the qualifier type if a
2208/// qualifier was provided, and otherwise it's the base type.
2209///
2210/// * Next we cast from the naming class to the declaring class.
2211/// If the member we found was brought into a class's scope by
2212/// a using declaration, this is that class; otherwise it's
2213/// the class declaring the member.
2214///
2215/// * Finally we cast from the declaring class to the "true"
2216/// declaring class of the member. This conversion does not
2217/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002218ExprResult
2219Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002220 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002221 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002222 NamedDecl *Member) {
2223 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2224 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002225 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002226
Douglas Gregor5fccd362010-03-03 23:55:11 +00002227 QualType DestRecordType;
2228 QualType DestType;
2229 QualType FromRecordType;
2230 QualType FromType = From->getType();
2231 bool PointerConversions = false;
2232 if (isa<FieldDecl>(Member)) {
2233 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002234
Douglas Gregor5fccd362010-03-03 23:55:11 +00002235 if (FromType->getAs<PointerType>()) {
2236 DestType = Context.getPointerType(DestRecordType);
2237 FromRecordType = FromType->getPointeeType();
2238 PointerConversions = true;
2239 } else {
2240 DestType = DestRecordType;
2241 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002242 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002243 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2244 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002245 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002246
Douglas Gregor5fccd362010-03-03 23:55:11 +00002247 DestType = Method->getThisType(Context);
2248 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002249
Douglas Gregor5fccd362010-03-03 23:55:11 +00002250 if (FromType->getAs<PointerType>()) {
2251 FromRecordType = FromType->getPointeeType();
2252 PointerConversions = true;
2253 } else {
2254 FromRecordType = FromType;
2255 DestType = DestRecordType;
2256 }
2257 } else {
2258 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002259 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002260 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002261
Douglas Gregor5fccd362010-03-03 23:55:11 +00002262 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002263 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002264
Douglas Gregor5fccd362010-03-03 23:55:11 +00002265 // If the unqualified types are the same, no conversion is necessary.
2266 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002267 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002268
John McCall6bb80172010-03-30 21:47:33 +00002269 SourceRange FromRange = From->getSourceRange();
2270 SourceLocation FromLoc = FromRange.getBegin();
2271
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002272 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002273
Douglas Gregor5fccd362010-03-03 23:55:11 +00002274 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002275 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002276 // class name.
2277 //
2278 // If the member was a qualified name and the qualified referred to a
2279 // specific base subobject type, we'll cast to that intermediate type
2280 // first and then to the object in which the member is declared. That allows
2281 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2282 //
2283 // class Base { public: int x; };
2284 // class Derived1 : public Base { };
2285 // class Derived2 : public Base { };
2286 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2287 //
2288 // void VeryDerived::f() {
2289 // x = 17; // error: ambiguous base subobjects
2290 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2291 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002292 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002293 QualType QType = QualType(Qualifier->getAsType(), 0);
2294 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2295 assert(QType->isRecordType() && "lookup done with non-record type");
2296
2297 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2298
2299 // In C++98, the qualifier type doesn't actually have to be a base
2300 // type of the object type, in which case we just ignore it.
2301 // Otherwise build the appropriate casts.
2302 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002303 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002304 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002305 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002306 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002307
Douglas Gregor5fccd362010-03-03 23:55:11 +00002308 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002309 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002310 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2311 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002312
2313 FromType = QType;
2314 FromRecordType = QRecordType;
2315
2316 // If the qualifier type was the same as the destination type,
2317 // we're done.
2318 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002319 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002320 }
2321 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002322
John McCall6bb80172010-03-30 21:47:33 +00002323 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002324
John McCall6bb80172010-03-30 21:47:33 +00002325 // If we actually found the member through a using declaration, cast
2326 // down to the using declaration's type.
2327 //
2328 // Pointer equality is fine here because only one declaration of a
2329 // class ever has member declarations.
2330 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2331 assert(isa<UsingShadowDecl>(FoundDecl));
2332 QualType URecordType = Context.getTypeDeclType(
2333 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2334
2335 // We only need to do this if the naming-class to declaring-class
2336 // conversion is non-trivial.
2337 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2338 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002339 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002340 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002341 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002342 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002343
John McCall6bb80172010-03-30 21:47:33 +00002344 QualType UType = URecordType;
2345 if (PointerConversions)
2346 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002347 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2348 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002349 FromType = UType;
2350 FromRecordType = URecordType;
2351 }
2352
2353 // We don't do access control for the conversion from the
2354 // declaring class to the true declaring class.
2355 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002356 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002357
John McCallf871d0c2010-08-07 06:22:56 +00002358 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002359 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2360 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002361 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002362 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002363
John Wiegley429bb272011-04-08 18:41:53 +00002364 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2365 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002366}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002367
John McCallf7a1a742009-11-24 19:00:30 +00002368bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002369 const LookupResult &R,
2370 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002371 // Only when used directly as the postfix-expression of a call.
2372 if (!HasTrailingLParen)
2373 return false;
2374
2375 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002376 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002377 return false;
2378
2379 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002380 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002381 return false;
2382
2383 // Turn off ADL when we find certain kinds of declarations during
2384 // normal lookup:
2385 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2386 NamedDecl *D = *I;
2387
2388 // C++0x [basic.lookup.argdep]p3:
2389 // -- a declaration of a class member
2390 // Since using decls preserve this property, we check this on the
2391 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002392 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002393 return false;
2394
2395 // C++0x [basic.lookup.argdep]p3:
2396 // -- a block-scope function declaration that is not a
2397 // using-declaration
2398 // NOTE: we also trigger this for function templates (in fact, we
2399 // don't check the decl type at all, since all other decl types
2400 // turn off ADL anyway).
2401 if (isa<UsingShadowDecl>(D))
2402 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2403 else if (D->getDeclContext()->isFunctionOrMethod())
2404 return false;
2405
2406 // C++0x [basic.lookup.argdep]p3:
2407 // -- a declaration that is neither a function or a function
2408 // template
2409 // And also for builtin functions.
2410 if (isa<FunctionDecl>(D)) {
2411 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2412
2413 // But also builtin functions.
2414 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2415 return false;
2416 } else if (!isa<FunctionTemplateDecl>(D))
2417 return false;
2418 }
2419
2420 return true;
2421}
2422
2423
John McCallba135432009-11-21 08:51:07 +00002424/// Diagnoses obvious problems with the use of the given declaration
2425/// as an expression. This is only actually called for lookups that
2426/// were not overloaded, and it doesn't promise that the declaration
2427/// will in fact be used.
2428static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002429 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002430 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2431 return true;
2432 }
2433
2434 if (isa<ObjCInterfaceDecl>(D)) {
2435 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2436 return true;
2437 }
2438
2439 if (isa<NamespaceDecl>(D)) {
2440 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2441 return true;
2442 }
2443
2444 return false;
2445}
2446
John McCall60d7b3a2010-08-24 06:29:42 +00002447ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002448Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002449 LookupResult &R,
2450 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002451 // If this is a single, fully-resolved result and we don't need ADL,
2452 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002453 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper8ff563c2013-03-22 10:01:35 +00002454 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2455 R.getRepresentativeDecl());
John McCallba135432009-11-21 08:51:07 +00002456
2457 // We only need to check the declaration if there's exactly one
2458 // result, because in the overloaded case the results can only be
2459 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002460 if (R.isSingleResult() &&
2461 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002462 return ExprError();
2463
John McCallc373d482010-01-27 01:50:18 +00002464 // Otherwise, just build an unresolved lookup expression. Suppress
2465 // any lookup-related diagnostics; we'll hash these out later, when
2466 // we've picked a target.
2467 R.suppressDiagnostics();
2468
John McCallba135432009-11-21 08:51:07 +00002469 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002470 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002471 SS.getWithLocInContext(Context),
2472 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002473 NeedsADL, R.isOverloadedResult(),
2474 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002475
2476 return Owned(ULE);
2477}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002478
John McCallba135432009-11-21 08:51:07 +00002479/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002480ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002481Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002482 const DeclarationNameInfo &NameInfo,
Daniel Jasper8ff563c2013-03-22 10:01:35 +00002483 NamedDecl *D, NamedDecl *FoundD) {
John McCallba135432009-11-21 08:51:07 +00002484 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002485 assert(!isa<FunctionTemplateDecl>(D) &&
2486 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002487
Abramo Bagnara25777432010-08-11 22:01:17 +00002488 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002489 if (CheckDeclInExpr(*this, Loc, D))
2490 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002491
Douglas Gregor9af2f522009-12-01 16:58:18 +00002492 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2493 // Specifically diagnose references to class templates that are missing
2494 // a template argument list.
2495 Diag(Loc, diag::err_template_decl_ref)
2496 << Template << SS.getRange();
2497 Diag(Template->getLocation(), diag::note_template_decl_here);
2498 return ExprError();
2499 }
2500
2501 // Make sure that we're referring to a value.
2502 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2503 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002504 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002505 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002506 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002507 return ExprError();
2508 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002509
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002510 // Check whether this declaration can be used. Note that we suppress
2511 // this check when we're going to perform argument-dependent lookup
2512 // on this function name, because this might not be the function
2513 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002514 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002515 return ExprError();
2516
Steve Naroffdd972f22008-09-05 22:11:13 +00002517 // Only create DeclRefExpr's for valid Decl's.
2518 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002519 return ExprError();
2520
John McCall5808ce42011-02-03 08:15:49 +00002521 // Handle members of anonymous structs and unions. If we got here,
2522 // and the reference is to a class member indirect field, then this
2523 // must be the subject of a pointer-to-member expression.
2524 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2525 if (!indirectField->isCXXClassMember())
2526 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2527 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002528
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002529 {
John McCall76a40212011-02-09 01:13:10 +00002530 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002531 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002532
2533 switch (D->getKind()) {
2534 // Ignore all the non-ValueDecl kinds.
2535#define ABSTRACT_DECL(kind)
2536#define VALUE(type, base)
2537#define DECL(type, base) \
2538 case Decl::type:
2539#include "clang/AST/DeclNodes.inc"
2540 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002541
2542 // These shouldn't make it here.
2543 case Decl::ObjCAtDefsField:
2544 case Decl::ObjCIvar:
2545 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002546
2547 // Enum constants are always r-values and never references.
2548 // Unresolved using declarations are dependent.
2549 case Decl::EnumConstant:
2550 case Decl::UnresolvedUsingValue:
2551 valueKind = VK_RValue;
2552 break;
2553
2554 // Fields and indirect fields that got here must be for
2555 // pointer-to-member expressions; we just call them l-values for
2556 // internal consistency, because this subexpression doesn't really
2557 // exist in the high-level semantics.
2558 case Decl::Field:
2559 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002560 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002561 "building reference to field in C?");
2562
2563 // These can't have reference type in well-formed programs, but
2564 // for internal consistency we do this anyway.
2565 type = type.getNonReferenceType();
2566 valueKind = VK_LValue;
2567 break;
2568
2569 // Non-type template parameters are either l-values or r-values
2570 // depending on the type.
2571 case Decl::NonTypeTemplateParm: {
2572 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2573 type = reftype->getPointeeType();
2574 valueKind = VK_LValue; // even if the parameter is an r-value reference
2575 break;
2576 }
2577
2578 // For non-references, we need to strip qualifiers just in case
2579 // the template parameter was declared as 'const int' or whatever.
2580 valueKind = VK_RValue;
2581 type = type.getUnqualifiedType();
2582 break;
2583 }
2584
2585 case Decl::Var:
2586 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002587 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002588 !type.hasQualifiers() &&
2589 type->isVoidType()) {
2590 valueKind = VK_RValue;
2591 break;
2592 }
2593 // fallthrough
2594
2595 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002596 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002597 // These are always l-values.
2598 valueKind = VK_LValue;
2599 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002600
Douglas Gregor68932842012-02-18 05:51:20 +00002601 // FIXME: Does the addition of const really only apply in
2602 // potentially-evaluated contexts? Since the variable isn't actually
2603 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002604 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002605 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2606 if (!CapturedType.isNull())
2607 type = CapturedType;
2608 }
2609
John McCall76a40212011-02-09 01:13:10 +00002610 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002611 }
2612
John McCall76a40212011-02-09 01:13:10 +00002613 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002614 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2615 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2616 type = Context.BuiltinFnTy;
2617 valueKind = VK_RValue;
2618 break;
2619 }
2620 }
2621
John McCall755d8492011-04-12 00:42:48 +00002622 const FunctionType *fty = type->castAs<FunctionType>();
2623
2624 // If we're referring to a function with an __unknown_anytype
2625 // result type, make the entire expression __unknown_anytype.
2626 if (fty->getResultType() == Context.UnknownAnyTy) {
2627 type = Context.UnknownAnyTy;
2628 valueKind = VK_RValue;
2629 break;
2630 }
2631
John McCall76a40212011-02-09 01:13:10 +00002632 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002633 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002634 valueKind = VK_LValue;
2635 break;
2636 }
2637
2638 // C99 DR 316 says that, if a function type comes from a
2639 // function definition (without a prototype), that type is only
2640 // used for checking compatibility. Therefore, when referencing
2641 // the function, we pretend that we don't have the full function
2642 // type.
John McCall755d8492011-04-12 00:42:48 +00002643 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2644 isa<FunctionProtoType>(fty))
2645 type = Context.getFunctionNoProtoType(fty->getResultType(),
2646 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002647
2648 // Functions are r-values in C.
2649 valueKind = VK_RValue;
2650 break;
2651 }
2652
John McCall76da55d2013-04-16 07:28:30 +00002653 case Decl::MSProperty:
2654 valueKind = VK_LValue;
2655 break;
2656
John McCall76a40212011-02-09 01:13:10 +00002657 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002658 // If we're referring to a method with an __unknown_anytype
2659 // result type, make the entire expression __unknown_anytype.
2660 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002661 if (const FunctionProtoType *proto
2662 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002663 if (proto->getResultType() == Context.UnknownAnyTy) {
2664 type = Context.UnknownAnyTy;
2665 valueKind = VK_RValue;
2666 break;
2667 }
2668
John McCall76a40212011-02-09 01:13:10 +00002669 // C++ methods are l-values if static, r-values if non-static.
2670 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2671 valueKind = VK_LValue;
2672 break;
2673 }
2674 // fallthrough
2675
2676 case Decl::CXXConversion:
2677 case Decl::CXXDestructor:
2678 case Decl::CXXConstructor:
2679 valueKind = VK_RValue;
2680 break;
2681 }
2682
Daniel Jasper8ff563c2013-03-22 10:01:35 +00002683 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD);
John McCall76a40212011-02-09 01:13:10 +00002684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002685}
2686
John McCall755d8492011-04-12 00:42:48 +00002687ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002688 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002689
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002691 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002692 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2693 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002694 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002695 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002697
Chris Lattnerfa28b302008-01-12 08:14:25 +00002698 // Pre-defined identifiers are of type char[x], where x is the length of the
2699 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Anders Carlsson3a082d82009-09-08 18:24:21 +00002701 Decl *currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer42427402012-12-06 15:42:21 +00002702 // Blocks and lambdas can occur at global scope. Don't emit a warning.
2703 if (!currentDecl) {
2704 if (const BlockScopeInfo *BSI = getCurBlock())
2705 currentDecl = BSI->TheDecl;
2706 else if (const LambdaScopeInfo *LSI = getCurLambda())
2707 currentDecl = LSI->CallOperator;
2708 }
2709
Anders Carlsson3a082d82009-09-08 18:24:21 +00002710 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002711 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002712 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002713 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002714
Anders Carlsson773f3972009-09-11 01:22:35 +00002715 QualType ResTy;
2716 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2717 ResTy = Context.DependentTy;
2718 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002719 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002720
Anders Carlsson773f3972009-09-11 01:22:35 +00002721 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002722 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002723 ResTy = Context.WCharTy.withConst();
2724 else
2725 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002726 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2727 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002728 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002729}
2730
Richard Smith36f5cfe2012-03-09 08:00:36 +00002731ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002732 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002733 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002734 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002735 if (Invalid)
2736 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002737
Benjamin Kramerddeea562010-02-27 13:44:12 +00002738 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002739 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002741 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002742
Chris Lattnere8337df2009-12-30 21:19:39 +00002743 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002744 if (Literal.isWide())
2745 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002746 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002747 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002748 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002749 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002750 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002751 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002752 else
2753 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002754
Douglas Gregor5cee1192011-07-27 05:40:30 +00002755 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2756 if (Literal.isWide())
2757 Kind = CharacterLiteral::Wide;
2758 else if (Literal.isUTF16())
2759 Kind = CharacterLiteral::UTF16;
2760 else if (Literal.isUTF32())
2761 Kind = CharacterLiteral::UTF32;
2762
Richard Smithdd66be72012-03-08 01:34:56 +00002763 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2764 Tok.getLocation());
2765
2766 if (Literal.getUDSuffix().empty())
2767 return Owned(Lit);
2768
2769 // We're building a user-defined literal.
2770 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2771 SourceLocation UDSuffixLoc =
2772 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2773
Richard Smith36f5cfe2012-03-09 08:00:36 +00002774 // Make sure we're allowed user-defined literals here.
2775 if (!UDLScope)
2776 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2777
Richard Smithdd66be72012-03-08 01:34:56 +00002778 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2779 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002780 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002781 Lit, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002782}
2783
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002784ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2785 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2786 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2787 Context.IntTy, Loc));
2788}
2789
Richard Smithb453ad32012-03-08 08:45:32 +00002790static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2791 QualType Ty, SourceLocation Loc) {
2792 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2793
2794 using llvm::APFloat;
2795 APFloat Val(Format);
2796
2797 APFloat::opStatus result = Literal.GetFloatValue(Val);
2798
2799 // Overflow is always an error, but underflow is only an error if
2800 // we underflowed to zero (APFloat reports denormals as underflow).
2801 if ((result & APFloat::opOverflow) ||
2802 ((result & APFloat::opUnderflow) && Val.isZero())) {
2803 unsigned diagnostic;
2804 SmallString<20> buffer;
2805 if (result & APFloat::opOverflow) {
2806 diagnostic = diag::warn_float_overflow;
2807 APFloat::getLargest(Format).toString(buffer);
2808 } else {
2809 diagnostic = diag::warn_float_underflow;
2810 APFloat::getSmallest(Format).toString(buffer);
2811 }
2812
2813 S.Diag(Loc, diagnostic)
2814 << Ty
2815 << StringRef(buffer.data(), buffer.size());
2816 }
2817
2818 bool isExact = (result == APFloat::opOK);
2819 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2820}
2821
Richard Smith36f5cfe2012-03-09 08:00:36 +00002822ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002823 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002824 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002826 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002827 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002828 }
Ted Kremenek28396602009-01-13 23:19:12 +00002829
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002830 SmallString<128> SpellingBuffer;
2831 // NumericLiteralParser wants to overread by one character. Add padding to
2832 // the buffer in case the token is copied to the buffer. If getSpelling()
2833 // returns a StringRef to the memory buffer, it should have a null char at
2834 // the EOF, so it is also safe.
2835 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002836
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002838 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002839 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002840 if (Invalid)
2841 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002842
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002843 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002845 return ExprError();
2846
Richard Smithb453ad32012-03-08 08:45:32 +00002847 if (Literal.hasUDSuffix()) {
2848 // We're building a user-defined literal.
2849 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2850 SourceLocation UDSuffixLoc =
2851 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2852
Richard Smith36f5cfe2012-03-09 08:00:36 +00002853 // Make sure we're allowed user-defined literals here.
2854 if (!UDLScope)
2855 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002856
Richard Smith36f5cfe2012-03-09 08:00:36 +00002857 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002858 if (Literal.isFloatingLiteral()) {
2859 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2860 // long double, the literal is treated as a call of the form
2861 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002862 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002863 } else {
2864 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2865 // unsigned long long, the literal is treated as a call of the form
2866 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002867 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002868 }
2869
Richard Smith36f5cfe2012-03-09 08:00:36 +00002870 DeclarationName OpName =
2871 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2872 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2873 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2874
2875 // Perform literal operator lookup to determine if we're building a raw
2876 // literal or a cooked one.
2877 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002878 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002879 /*AllowRawAndTemplate*/true)) {
2880 case LOLR_Error:
2881 return ExprError();
2882
2883 case LOLR_Cooked: {
2884 Expr *Lit;
2885 if (Literal.isFloatingLiteral()) {
2886 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2887 } else {
2888 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2889 if (Literal.GetIntegerValue(ResultVal))
2890 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2891 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2892 Tok.getLocation());
2893 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002894 return BuildLiteralOperatorCall(R, OpNameInfo, Lit,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002895 Tok.getLocation());
2896 }
2897
2898 case LOLR_Raw: {
2899 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2900 // literal is treated as a call of the form
2901 // operator "" X ("n")
2902 SourceLocation TokLoc = Tok.getLocation();
2903 unsigned Length = Literal.getUDSuffixOffset();
2904 QualType StrTy = Context.getConstantArrayType(
Richard Smith4ea6a642013-01-23 23:38:20 +00002905 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smith36f5cfe2012-03-09 08:00:36 +00002906 ArrayType::Normal, 0);
2907 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002908 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002909 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002910 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002911 }
2912
2913 case LOLR_Template:
2914 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2915 // template), L is treated as a call fo the form
2916 // operator "" X <'c1', 'c2', ... 'ck'>()
2917 // where n is the source character sequence c1 c2 ... ck.
2918 TemplateArgumentListInfo ExplicitArgs;
2919 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2920 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2921 llvm::APSInt Value(CharBits, CharIsUnsigned);
2922 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002923 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002924 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002925 TemplateArgumentLocInfo ArgInfo;
2926 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2927 }
Dmitri Gribenko55431692013-05-05 00:41:58 +00002928 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(),
2929 &ExplicitArgs);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002930 }
2931
2932 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002933 }
2934
Chris Lattner5d661452007-08-26 03:42:43 +00002935 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002936
Chris Lattner5d661452007-08-26 03:42:43 +00002937 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002938 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002939 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002940 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002941 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002942 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002943 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002944 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002945
Richard Smithb453ad32012-03-08 08:45:32 +00002946 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002947
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002948 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002949 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002950 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002951 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002952 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002953 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002954 }
2955 }
Chris Lattner5d661452007-08-26 03:42:43 +00002956 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002957 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002958 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002959 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002960
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002961 // 'long long' is a C99 or C++11 feature.
2962 if (!getLangOpts().C99 && Literal.isLongLong) {
2963 if (getLangOpts().CPlusPlus)
2964 Diag(Tok.getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002965 getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002966 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2967 else
2968 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2969 }
Neil Boothb9449512007-08-29 22:00:19 +00002970
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002972 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2973 // The microsoft literal suffix extensions support 128-bit literals, which
2974 // may be wider than [u]intmax_t.
Richard Smith84268902012-11-29 05:41:51 +00002975 // FIXME: Actually, they don't. We seem to have accidentally invented the
2976 // i128 suffix.
2977 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2978 PP.getTargetInfo().hasInt128Type())
Stephen Canonb9e05f12012-05-03 22:49:43 +00002979 MaxWidth = 128;
2980 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002981
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 if (Literal.GetIntegerValue(ResultVal)) {
2983 // If this value didn't fit into uintmax_t, warn and force to ull.
2984 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002985 Ty = Context.UnsignedLongLongTy;
2986 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002987 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002988 } else {
2989 // If this value fits into a ULL, try to figure out what else it fits into
2990 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002991
Reid Spencer5f016e22007-07-11 17:01:13 +00002992 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2993 // be an unsigned int.
2994 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2995
2996 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002997 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002998 if (!Literal.isLong && !Literal.isLongLong) {
2999 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003000 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003001
Reid Spencer5f016e22007-07-11 17:01:13 +00003002 // Does it fit in a unsigned int?
3003 if (ResultVal.isIntN(IntSize)) {
3004 // Does it fit in a signed int?
3005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003006 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003008 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003009 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003012
Reid Spencer5f016e22007-07-11 17:01:13 +00003013 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00003014 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003015 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003016
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 // Does it fit in a unsigned long?
3018 if (ResultVal.isIntN(LongSize)) {
3019 // Does it fit in a signed long?
3020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003021 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003023 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003024 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003026 }
3027
Stephen Canonb9e05f12012-05-03 22:49:43 +00003028 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003029 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003030 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003031
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 // Does it fit in a unsigned long long?
3033 if (ResultVal.isIntN(LongLongSize)) {
3034 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00003035 // To be compatible with MSVC, hex integer literals ending with the
3036 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00003037 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003038 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00003039 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003040 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003041 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003042 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 }
3044 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00003045
3046 // If it doesn't fit in unsigned long long, and we're using Microsoft
3047 // extensions, then its a 128-bit integer literal.
Richard Smith84268902012-11-29 05:41:51 +00003048 if (Ty.isNull() && Literal.isMicrosoftInteger &&
3049 PP.getTargetInfo().hasInt128Type()) {
Stephen Canonb9e05f12012-05-03 22:49:43 +00003050 if (Literal.isUnsigned)
3051 Ty = Context.UnsignedInt128Ty;
3052 else
3053 Ty = Context.Int128Ty;
3054 Width = 128;
3055 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003056
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 // If we still couldn't decide a type, we probably have something that
3058 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003059 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003061 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003062 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003064
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003065 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003066 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00003067 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003068 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003070
Chris Lattner5d661452007-08-26 03:42:43 +00003071 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3072 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003073 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003074 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003075
3076 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00003077}
3078
Richard Trieuccd891a2011-09-09 01:45:06 +00003079ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003080 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003081 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003082}
3083
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003084static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3085 SourceLocation Loc,
3086 SourceRange ArgRange) {
3087 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3088 // scalar or vector data type argument..."
3089 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3090 // type (C99 6.2.5p18) or void.
3091 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3092 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3093 << T << ArgRange;
3094 return true;
3095 }
3096
3097 assert((T->isVoidType() || !T->isIncompleteType()) &&
3098 "Scalar types should always be complete");
3099 return false;
3100}
3101
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003102static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3103 SourceLocation Loc,
3104 SourceRange ArgRange,
3105 UnaryExprOrTypeTrait TraitKind) {
3106 // C99 6.5.3.4p1:
Richard Smith7132be12013-03-18 23:37:25 +00003107 if (T->isFunctionType() &&
3108 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3109 // sizeof(function)/alignof(function) is allowed as an extension.
3110 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3111 << TraitKind << ArgRange;
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003112 return false;
3113 }
3114
3115 // Allow sizeof(void)/alignof(void) as an extension.
3116 if (T->isVoidType()) {
Richard Smith7132be12013-03-18 23:37:25 +00003117 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003118 return false;
3119 }
3120
3121 return true;
3122}
3123
3124static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3125 SourceLocation Loc,
3126 SourceRange ArgRange,
3127 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00003128 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3129 // runtime doesn't allow it.
3130 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003131 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3132 << T << (TraitKind == UETT_SizeOf)
3133 << ArgRange;
3134 return true;
3135 }
3136
3137 return false;
3138}
3139
Benjamin Kramer52b2e702013-03-29 21:43:21 +00003140/// \brief Check whether E is a pointer from a decayed array type (the decayed
3141/// pointer type is equal to T) and emit a warning if it is.
3142static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3143 Expr *E) {
3144 // Don't warn if the operation changed the type.
3145 if (T != E->getType())
3146 return;
3147
3148 // Now look for array decays.
3149 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3150 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3151 return;
3152
3153 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3154 << ICE->getType()
3155 << ICE->getSubExpr()->getType();
3156}
3157
Chandler Carruth9d342d02011-05-26 08:53:10 +00003158/// \brief Check the constrains on expression operands to unary type expression
3159/// and type traits.
3160///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003161/// Completes any types necessary and validates the constraints on the operand
3162/// expression. The logic mostly mirrors the type-based overload, but may modify
3163/// the expression as it completes the type for that expression through template
3164/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003165bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003166 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003167 QualType ExprTy = E->getType();
John McCall10f6f062013-05-06 07:40:34 +00003168 assert(!ExprTy->isReferenceType());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003169
3170 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003171 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3172 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003173
3174 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003175 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3176 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003177 return false;
3178
Richard Trieuccd891a2011-09-09 01:45:06 +00003179 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003180 diag::err_sizeof_alignof_incomplete_type,
3181 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003182 return true;
3183
John McCall10f6f062013-05-06 07:40:34 +00003184 // Completing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003185 ExprTy = E->getType();
John McCall10f6f062013-05-06 07:40:34 +00003186 assert(!ExprTy->isReferenceType());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003187
Richard Trieuccd891a2011-09-09 01:45:06 +00003188 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3189 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003190 return true;
3191
Nico Webercf739922011-06-15 02:47:03 +00003192 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003193 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003194 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3195 QualType OType = PVD->getOriginalType();
3196 QualType Type = PVD->getType();
3197 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003198 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003199 << Type << OType;
3200 Diag(PVD->getLocation(), diag::note_declared_at);
3201 }
3202 }
3203 }
Benjamin Kramer52b2e702013-03-29 21:43:21 +00003204
3205 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3206 // decays into a pointer and returns an unintended result. This is most
3207 // likely a typo for "sizeof(array) op x".
3208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3209 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3210 BO->getLHS());
3211 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3212 BO->getRHS());
3213 }
Nico Webercf739922011-06-15 02:47:03 +00003214 }
3215
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003216 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003217}
3218
3219/// \brief Check the constraints on operands to unary expression and type
3220/// traits.
3221///
3222/// This will complete any types necessary, and validate the various constraints
3223/// on those operands.
3224///
Reid Spencer5f016e22007-07-11 17:01:13 +00003225/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003226/// C99 6.3.2.1p[2-4] all state:
3227/// Except when it is the operand of the sizeof operator ...
3228///
3229/// C++ [expr.sizeof]p4
3230/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3231/// standard conversions are not applied to the operand of sizeof.
3232///
3233/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003234bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003235 SourceLocation OpLoc,
3236 SourceRange ExprRange,
3237 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003238 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003239 return false;
3240
Sebastian Redl5d484e82009-11-23 17:18:46 +00003241 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3242 // the result is the size of the referenced type."
3243 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3244 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003245 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3246 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003247
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003248 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003249 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003250
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003251 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003252 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003253 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003254 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Richard Trieuccd891a2011-09-09 01:45:06 +00003256 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003257 diag::err_sizeof_alignof_incomplete_type,
3258 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003259 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Richard Trieuccd891a2011-09-09 01:45:06 +00003261 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003262 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003263 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Chris Lattner1efaa952009-04-24 00:30:45 +00003265 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003266}
3267
Chandler Carruth9d342d02011-05-26 08:53:10 +00003268static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003269 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003270
Sebastian Redl28507842009-02-26 14:39:58 +00003271 // Cannot know anything else if the expression is dependent.
3272 if (E->isTypeDependent())
3273 return false;
3274
John McCall10f6f062013-05-06 07:40:34 +00003275 if (E->getObjectKind() == OK_BitField) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003276 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3277 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003278 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003279 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003280
John McCall10f6f062013-05-06 07:40:34 +00003281 ValueDecl *D = 0;
3282 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3283 D = DRE->getDecl();
3284 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3285 D = ME->getMemberDecl();
3286 }
3287
3288 // If it's a field, require the containing struct to have a
3289 // complete definition so that we can compute the layout.
3290 //
3291 // This requires a very particular set of circumstances. For a
3292 // field to be contained within an incomplete type, we must in the
3293 // process of parsing that type. To have an expression refer to a
3294 // field, it must be an id-expression or a member-expression, but
3295 // the latter are always ill-formed when the base type is
3296 // incomplete, including only being partially complete. An
3297 // id-expression can never refer to a field in C because fields
3298 // are not in the ordinary namespace. In C++, an id-expression
3299 // can implicitly be a member access, but only if there's an
3300 // implicit 'this' value, and all such contexts are subject to
3301 // delayed parsing --- except for trailing return types in C++11.
3302 // And if an id-expression referring to a field occurs in a
3303 // context that lacks a 'this' value, it's ill-formed --- except,
3304 // agian, in C++11, where such references are allowed in an
3305 // unevaluated context. So C++11 introduces some new complexity.
3306 //
3307 // For the record, since __alignof__ on expressions is a GCC
3308 // extension, GCC seems to permit this but always gives the
3309 // nonsensical answer 0.
3310 //
3311 // We don't really need the layout here --- we could instead just
3312 // directly check for all the appropriate alignment-lowing
3313 // attributes --- but that would require duplicating a lot of
3314 // logic that just isn't worth duplicating for such a marginal
3315 // use-case.
3316 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3317 // Fast path this check, since we at least know the record has a
3318 // definition if we can find a member of it.
3319 if (!FD->getParent()->isCompleteDefinition()) {
3320 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3321 << E->getSourceRange();
3322 return true;
3323 }
3324
3325 // Otherwise, if it's a field, and the field doesn't have
3326 // reference type, then it must have a complete type (or be a
3327 // flexible array member, which we explicitly want to
3328 // white-list anyway), which makes the following checks trivial.
3329 if (!FD->getType()->isReferenceType())
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003330 return false;
John McCall10f6f062013-05-06 07:40:34 +00003331 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003332
Chandler Carruth9d342d02011-05-26 08:53:10 +00003333 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003334}
3335
Chandler Carruth9d342d02011-05-26 08:53:10 +00003336bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003337 E = E->IgnoreParens();
3338
3339 // Cannot know anything else if the expression is dependent.
3340 if (E->isTypeDependent())
3341 return false;
3342
Chandler Carruth9d342d02011-05-26 08:53:10 +00003343 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003344}
3345
Douglas Gregorba498172009-03-13 21:01:28 +00003346/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003347ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003348Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3349 SourceLocation OpLoc,
3350 UnaryExprOrTypeTrait ExprKind,
3351 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003352 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003353 return ExprError();
3354
John McCalla93c9342009-12-07 02:54:59 +00003355 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003356
Douglas Gregorba498172009-03-13 21:01:28 +00003357 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003358 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003359 return ExprError();
3360
3361 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003362 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3363 Context.getSizeType(),
3364 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003365}
3366
3367/// \brief Build a sizeof or alignof expression given an expression
3368/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003369ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003370Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3371 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003372 ExprResult PE = CheckPlaceholderExpr(E);
3373 if (PE.isInvalid())
3374 return ExprError();
3375
3376 E = PE.get();
3377
Douglas Gregorba498172009-03-13 21:01:28 +00003378 // Verify that the operand is valid.
3379 bool isInvalid = false;
3380 if (E->isTypeDependent()) {
3381 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003382 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003383 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003384 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003385 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003386 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003387 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003388 isInvalid = true;
3389 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003390 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003391 }
3392
3393 if (isInvalid)
3394 return ExprError();
3395
Eli Friedman71b8fb52012-01-21 01:01:51 +00003396 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Krameraccaf192012-11-14 15:08:31 +00003397 PE = TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +00003398 if (PE.isInvalid()) return ExprError();
3399 E = PE.take();
3400 }
3401
Douglas Gregorba498172009-03-13 21:01:28 +00003402 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003403 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003404 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003405 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003406}
3407
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003408/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3409/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003410/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003411ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003412Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003413 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003414 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003415 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003416 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003417
Richard Trieuccd891a2011-09-09 01:45:06 +00003418 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003419 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003420 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003421 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003422 }
Sebastian Redl05189992008-11-11 17:56:53 +00003423
Douglas Gregorba498172009-03-13 21:01:28 +00003424 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003425 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003426 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003427}
3428
John Wiegley429bb272011-04-08 18:41:53 +00003429static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003430 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003431 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003432 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003433
John McCallf6a16482010-12-04 03:47:34 +00003434 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003435 if (V.get()->getObjectKind() != OK_Ordinary) {
3436 V = S.DefaultLvalueConversion(V.take());
3437 if (V.isInvalid())
3438 return QualType();
3439 }
John McCallf6a16482010-12-04 03:47:34 +00003440
Chris Lattnercc26ed72007-08-26 05:39:26 +00003441 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003442 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003443 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Chris Lattnercc26ed72007-08-26 05:39:26 +00003445 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003446 if (V.get()->getType()->isArithmeticType())
3447 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003448
John McCall2cd11fe2010-10-12 02:09:17 +00003449 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003450 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003451 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003452 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003453 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003454 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003455 }
3456
Chris Lattnercc26ed72007-08-26 05:39:26 +00003457 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003458 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003459 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003460 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003461}
3462
3463
Reid Spencer5f016e22007-07-11 17:01:13 +00003464
John McCall60d7b3a2010-08-24 06:29:42 +00003465ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003466Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003467 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003468 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003469 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003470 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003471 case tok::plusplus: Opc = UO_PostInc; break;
3472 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003473 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003474
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003475 // Since this might is a postfix expression, get rid of ParenListExprs.
3476 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3477 if (Result.isInvalid()) return ExprError();
3478 Input = Result.take();
3479
John McCall9ae2f072010-08-23 23:25:46 +00003480 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003481}
3482
John McCall1503f0d2012-07-31 05:14:30 +00003483/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3484///
3485/// \return true on error
3486static bool checkArithmeticOnObjCPointer(Sema &S,
3487 SourceLocation opLoc,
3488 Expr *op) {
3489 assert(op->getType()->isObjCObjectPointerType());
3490 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3491 return false;
3492
3493 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3494 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3495 << op->getSourceRange();
3496 return true;
3497}
3498
John McCall60d7b3a2010-08-24 06:29:42 +00003499ExprResult
John McCall7a534b92013-03-04 01:30:55 +00003500Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3501 Expr *idx, SourceLocation rbLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003502 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall7a534b92013-03-04 01:30:55 +00003503 if (isa<ParenListExpr>(base)) {
3504 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3505 if (result.isInvalid()) return ExprError();
3506 base = result.take();
3507 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003508
John McCall7a534b92013-03-04 01:30:55 +00003509 // Handle any non-overload placeholder types in the base and index
3510 // expressions. We can't handle overloads here because the other
3511 // operand might be an overloadable type, in which case the overload
3512 // resolution for the operator overload should get the first crack
3513 // at the overload.
3514 if (base->getType()->isNonOverloadPlaceholderType()) {
3515 ExprResult result = CheckPlaceholderExpr(base);
3516 if (result.isInvalid()) return ExprError();
3517 base = result.take();
3518 }
3519 if (idx->getType()->isNonOverloadPlaceholderType()) {
3520 ExprResult result = CheckPlaceholderExpr(idx);
3521 if (result.isInvalid()) return ExprError();
3522 idx = result.take();
3523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
John McCall7a534b92013-03-04 01:30:55 +00003525 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikie4e4d0842012-03-11 07:00:24 +00003526 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003527 (base->isTypeDependent() || idx->isTypeDependent())) {
3528 return Owned(new (Context) ArraySubscriptExpr(base, idx,
John McCallf89e55a2010-11-18 06:31:45 +00003529 Context.DependentTy,
3530 VK_LValue, OK_Ordinary,
John McCall7a534b92013-03-04 01:30:55 +00003531 rbLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003532 }
3533
John McCall7a534b92013-03-04 01:30:55 +00003534 // Use C++ overloaded-operator rules if either operand has record
3535 // type. The spec says to do this if either type is *overloadable*,
3536 // but enum types can't declare subscript operators or conversion
3537 // operators, so there's nothing interesting for overload resolution
3538 // to do if there aren't any record types involved.
3539 //
3540 // ObjC pointers have their own subscripting logic that is not tied
3541 // to overload resolution and so should not take this path.
David Blaikie4e4d0842012-03-11 07:00:24 +00003542 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003543 (base->getType()->isRecordType() ||
3544 (!base->getType()->isObjCObjectPointerType() &&
3545 idx->getType()->isRecordType()))) {
3546 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003547 }
3548
John McCall7a534b92013-03-04 01:30:55 +00003549 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003550}
3551
John McCall60d7b3a2010-08-24 06:29:42 +00003552ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003553Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003554 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003555 Expr *LHSExp = Base;
3556 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003557
Chris Lattner12d9ff62007-07-16 00:14:47 +00003558 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003559 if (!LHSExp->getType()->getAs<VectorType>()) {
3560 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3561 if (Result.isInvalid())
3562 return ExprError();
3563 LHSExp = Result.take();
3564 }
3565 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3566 if (Result.isInvalid())
3567 return ExprError();
3568 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003569
Chris Lattner12d9ff62007-07-16 00:14:47 +00003570 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003571 ExprValueKind VK = VK_LValue;
3572 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003573
Reid Spencer5f016e22007-07-11 17:01:13 +00003574 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003575 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003576 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003578 Expr *BaseExpr, *IndexExpr;
3579 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003580 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3581 BaseExpr = LHSExp;
3582 IndexExpr = RHSExp;
3583 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003584 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003585 BaseExpr = LHSExp;
3586 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003587 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003588 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003589 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003590 BaseExpr = LHSExp;
3591 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003592
3593 // Use custom logic if this should be the pseudo-object subscript
3594 // expression.
3595 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3596 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3597
Steve Naroff14108da2009-07-10 23:34:53 +00003598 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003599 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3600 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3601 << ResultType << BaseExpr->getSourceRange();
3602 return ExprError();
3603 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003604 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3605 // Handle the uncommon case of "123[Ptr]".
3606 BaseExpr = RHSExp;
3607 IndexExpr = LHSExp;
3608 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003609 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003610 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003611 // Handle the uncommon case of "123[Ptr]".
3612 BaseExpr = RHSExp;
3613 IndexExpr = LHSExp;
3614 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003615 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3616 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3617 << ResultType << BaseExpr->getSourceRange();
3618 return ExprError();
3619 }
John McCall183700f2009-09-21 23:43:11 +00003620 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003621 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003622 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003623 VK = LHSExp->getValueKind();
3624 if (VK != VK_RValue)
3625 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003626
Chris Lattner12d9ff62007-07-16 00:14:47 +00003627 // FIXME: need to deal with const...
3628 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003629 } else if (LHSTy->isArrayType()) {
3630 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003631 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003632 // wasn't promoted because of the C90 rule that doesn't
3633 // allow promoting non-lvalue arrays. Warn, then
3634 // force the promotion here.
3635 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3636 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003637 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3638 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003639 LHSTy = LHSExp->getType();
3640
3641 BaseExpr = LHSExp;
3642 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003643 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003644 } else if (RHSTy->isArrayType()) {
3645 // Same as previous, except for 123[f().a] case
3646 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3647 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003648 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3649 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003650 RHSTy = RHSExp->getType();
3651
3652 BaseExpr = RHSExp;
3653 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003654 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003655 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003656 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3657 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003658 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003659 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003660 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003661 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3662 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003663
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003664 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003665 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3666 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003667 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3668
Douglas Gregore7450f52009-03-24 19:52:54 +00003669 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003670 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3671 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003672 // incomplete types are not object types.
3673 if (ResultType->isFunctionType()) {
3674 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3675 << ResultType << BaseExpr->getSourceRange();
3676 return ExprError();
3677 }
Mike Stump1eb44332009-09-09 15:08:12 +00003678
David Blaikie4e4d0842012-03-11 07:00:24 +00003679 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003680 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003681 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3682 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003683
3684 // C forbids expressions of unqualified void type from being l-values.
3685 // See IsCForbiddenLValueType.
3686 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003687 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003688 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003689 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003690 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003691
John McCall09431682010-11-18 19:01:18 +00003692 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003693 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003694
Mike Stumpeed9cac2009-02-19 03:04:26 +00003695 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003696 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003697}
3698
John McCall60d7b3a2010-08-24 06:29:42 +00003699ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003700 FunctionDecl *FD,
3701 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003702 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003703 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003704 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003705 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003706 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003707 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003708 return ExprError();
3709 }
3710
3711 if (Param->hasUninstantiatedDefaultArg()) {
3712 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003713
Richard Smithadb1d4c2012-07-22 23:45:10 +00003714 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3715 Param);
3716
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003717 // Instantiate the expression.
Richard Smithc95d4132013-05-03 23:46:09 +00003718 MultiLevelTemplateArgumentList MutiLevelArgList
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003719 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003720
Richard Smith7e54fb52012-07-16 01:09:10 +00003721 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smithc95d4132013-05-03 23:46:09 +00003722 MutiLevelArgList.getInnermost());
Richard Smithab91ef12012-07-08 02:38:24 +00003723 if (Inst)
3724 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003725
Nico Weber08e41a62010-11-29 18:19:25 +00003726 ExprResult Result;
3727 {
3728 // C++ [dcl.fct.default]p5:
3729 // The names in the [default argument] expression are bound, and
3730 // the semantic constraints are checked, at the point where the
3731 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003732 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003733 LocalInstantiationScope Local(*this);
Richard Smithc95d4132013-05-03 23:46:09 +00003734 Result = SubstExpr(UninstExpr, MutiLevelArgList);
Nico Weber08e41a62010-11-29 18:19:25 +00003735 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003736 if (Result.isInvalid())
3737 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003739 // Check the expression as an initializer for the parameter.
3740 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003741 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003742 InitializationKind Kind
3743 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003744 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003745 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003746
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003747 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003748 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003749 if (Result.isInvalid())
3750 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003751
David Blaikiec1c07252012-04-30 18:21:31 +00003752 Expr *Arg = Result.takeAs<Expr>();
Richard Smith6c3af3d2013-01-17 01:17:56 +00003753 CheckCompletedExpr(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003754 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003755 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003756 }
3757
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003758 // If the default expression creates temporaries, we need to
3759 // push them to the current stack of expression temporaries so they'll
3760 // be properly destroyed.
3761 // FIXME: We should really be rebuilding the default argument with new
3762 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003763 // We don't need to do that with block decls, though, because
3764 // blocks in default argument expression can never capture anything.
3765 if (isa<ExprWithCleanups>(Param->getInit())) {
3766 // Set the "needs cleanups" bit regardless of whether there are
3767 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003768 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003769
3770 // Append all the objects to the cleanup list. Right now, this
3771 // should always be a no-op, because blocks in default argument
3772 // expressions should never be able to capture anything.
3773 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3774 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003775 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003776
3777 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003778 // Just mark all of the declarations in this potentially-evaluated expression
3779 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003780 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3781 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003782 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003783}
3784
Richard Smith831421f2012-06-25 20:30:08 +00003785
3786Sema::VariadicCallType
3787Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3788 Expr *Fn) {
3789 if (Proto && Proto->isVariadic()) {
3790 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3791 return VariadicConstructor;
3792 else if (Fn && Fn->getType()->isBlockPointerType())
3793 return VariadicBlock;
3794 else if (FDecl) {
3795 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3796 if (Method->isInstance())
3797 return VariadicMethod;
3798 }
3799 return VariadicFunction;
3800 }
3801 return VariadicDoesNotApply;
3802}
3803
Douglas Gregor88a35142008-12-22 05:46:06 +00003804/// ConvertArgumentsForCall - Converts the arguments specified in
3805/// Args/NumArgs to the parameter types of the function FDecl with
3806/// function prototype Proto. Call is the call expression itself, and
3807/// Fn is the function expression. For a C++ member function, this
3808/// routine does not attempt to convert the object argument. Returns
3809/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003810bool
3811Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003812 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003813 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003814 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003815 SourceLocation RParenLoc,
3816 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003817 // Bail out early if calling a builtin with custom typechecking.
3818 // We don't need to do this in the
3819 if (FDecl)
3820 if (unsigned ID = FDecl->getBuiltinID())
3821 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3822 return false;
3823
Mike Stumpeed9cac2009-02-19 03:04:26 +00003824 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003825 // assignment, to the types of the corresponding parameter, ...
3826 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003827 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003828 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003829 unsigned FnKind = Fn->getType()->isBlockPointerType()
3830 ? 1 /* block */
3831 : (IsExecConfig ? 3 /* kernel function (exec config) */
3832 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003833
Douglas Gregor88a35142008-12-22 05:46:06 +00003834 // If too few arguments are available (and we don't have default
3835 // arguments for the remaining parameters), don't make the call.
3836 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003837 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003838 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3839 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3840 ? diag::err_typecheck_call_too_few_args_one
3841 : diag::err_typecheck_call_too_few_args_at_least_one)
3842 << FnKind
3843 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3844 else
3845 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3846 ? diag::err_typecheck_call_too_few_args
3847 : diag::err_typecheck_call_too_few_args_at_least)
3848 << FnKind
3849 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003850
3851 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003852 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003853 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3854 << FDecl;
3855
3856 return true;
3857 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003858 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003859 }
3860
3861 // If too many are passed and not variadic, error on the extras and drop
3862 // them.
3863 if (NumArgs > NumArgsInProto) {
3864 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003865 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3866 Diag(Args[NumArgsInProto]->getLocStart(),
3867 MinArgs == NumArgsInProto
3868 ? diag::err_typecheck_call_too_many_args_one
3869 : diag::err_typecheck_call_too_many_args_at_most_one)
3870 << FnKind
3871 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3872 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3873 Args[NumArgs-1]->getLocEnd());
3874 else
3875 Diag(Args[NumArgsInProto]->getLocStart(),
3876 MinArgs == NumArgsInProto
3877 ? diag::err_typecheck_call_too_many_args
3878 : diag::err_typecheck_call_too_many_args_at_most)
3879 << FnKind
3880 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3881 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3882 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003883
3884 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003885 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003886 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3887 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003888
Douglas Gregor88a35142008-12-22 05:46:06 +00003889 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003890 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003891 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003892 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003893 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003894 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003895 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3896
Daniel Dunbar96a00142012-03-09 18:35:03 +00003897 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003898 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003899 if (Invalid)
3900 return true;
3901 unsigned TotalNumArgs = AllArgs.size();
3902 for (unsigned i = 0; i < TotalNumArgs; ++i)
3903 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003904
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003905 return false;
3906}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003907
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003908bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3909 FunctionDecl *FDecl,
3910 const FunctionProtoType *Proto,
3911 unsigned FirstProtoArg,
3912 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003913 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003914 VariadicCallType CallType,
Richard Smitha4dc51b2013-02-05 05:52:24 +00003915 bool AllowExplicit,
3916 bool IsListInitialization) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003917 unsigned NumArgsInProto = Proto->getNumArgs();
3918 unsigned NumArgsToCheck = NumArgs;
3919 bool Invalid = false;
3920 if (NumArgs != NumArgsInProto)
3921 // Use default arguments for missing arguments
3922 NumArgsToCheck = NumArgsInProto;
3923 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003924 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003925 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003926 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003927
Douglas Gregor88a35142008-12-22 05:46:06 +00003928 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003929 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003930 if (ArgIx < NumArgs) {
3931 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003932
Daniel Dunbar96a00142012-03-09 18:35:03 +00003933 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003934 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003935 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003936 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003937
Douglas Gregora188ff22009-12-22 16:09:06 +00003938 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003939 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003940 if (FDecl && i < FDecl->getNumParams())
3941 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003942
John McCall5acb0c92011-10-17 18:40:02 +00003943 // Strip the unbridged-cast placeholder expression off, if applicable.
3944 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3945 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3946 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3947 Arg = stripARCUnbridgedCast(Arg);
3948
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00003949 InitializedEntity Entity = Param ?
3950 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3951 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3952 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003953 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003954 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003955 Owned(Arg),
Richard Smitha4dc51b2013-02-05 05:52:24 +00003956 IsListInitialization,
Douglas Gregored878af2012-02-24 23:56:31 +00003957 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003958 if (ArgE.isInvalid())
3959 return true;
3960
3961 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003962 } else {
Jordan Rose62bbe072013-03-15 21:41:35 +00003963 assert(FDecl && "can't use default arguments without a known callee");
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003964 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003965
John McCall60d7b3a2010-08-24 06:29:42 +00003966 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003967 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003968 if (ArgExpr.isInvalid())
3969 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003970
Anders Carlsson56c5e332009-08-25 03:49:14 +00003971 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003972 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003973
3974 // Check for array bounds violations for each argument to the call. This
3975 // check only triggers warnings when the argument isn't a more complex Expr
3976 // with its own checking, such as a BinaryOperator.
3977 CheckArrayAccess(Arg);
3978
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003979 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3980 CheckStaticArrayArgument(CallLoc, Param, Arg);
3981
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003982 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003983 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003984
Douglas Gregor88a35142008-12-22 05:46:06 +00003985 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003986 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003987 // Assume that extern "C" functions with variadic arguments that
3988 // return __unknown_anytype aren't *really* variadic.
3989 if (Proto->getResultType() == Context.UnknownAnyTy &&
3990 FDecl && FDecl->isExternC()) {
3991 for (unsigned i = ArgIx; i != NumArgs; ++i) {
John McCall48f90422013-03-04 07:34:02 +00003992 QualType paramType; // ignored
3993 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
John McCall755d8492011-04-12 00:42:48 +00003994 Invalid |= arg.isInvalid();
3995 AllArgs.push_back(arg.take());
3996 }
3997
3998 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3999 } else {
4000 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00004001 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4002 FDecl);
John McCall755d8492011-04-12 00:42:48 +00004003 Invalid |= Arg.isInvalid();
4004 AllArgs.push_back(Arg.take());
4005 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004006 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00004007
4008 // Check for array bounds violations.
4009 for (unsigned i = ArgIx; i != NumArgs; ++i)
4010 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00004011 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004012 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004013}
4014
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004015static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4016 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00004017 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004018 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie39e6ab42013-02-18 22:06:02 +00004019 << ATL.getLocalSourceRange();
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004020}
4021
4022/// CheckStaticArrayArgument - If the given argument corresponds to a static
4023/// array parameter, check that it is non-null, and that if it is formed by
4024/// array-to-pointer decay, the underlying array is sufficiently large.
4025///
4026/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4027/// array type derivation, then for each call to the function, the value of the
4028/// corresponding actual argument shall provide access to the first element of
4029/// an array with at least as many elements as specified by the size expression.
4030void
4031Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4032 ParmVarDecl *Param,
4033 const Expr *ArgExpr) {
4034 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00004035 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004036 return;
4037
4038 QualType OrigTy = Param->getOriginalType();
4039
4040 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4041 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4042 return;
4043
4044 if (ArgExpr->isNullPointerConstant(Context,
4045 Expr::NPC_NeverValueDependent)) {
4046 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4047 DiagnoseCalleeStaticArrayParam(*this, Param);
4048 return;
4049 }
4050
4051 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4052 if (!CAT)
4053 return;
4054
4055 const ConstantArrayType *ArgCAT =
4056 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4057 if (!ArgCAT)
4058 return;
4059
4060 if (ArgCAT->getSize().ult(CAT->getSize())) {
4061 Diag(CallLoc, diag::warn_static_array_too_small)
4062 << ArgExpr->getSourceRange()
4063 << (unsigned) ArgCAT->getSize().getZExtValue()
4064 << (unsigned) CAT->getSize().getZExtValue();
4065 DiagnoseCalleeStaticArrayParam(*this, Param);
4066 }
4067}
4068
John McCall755d8492011-04-12 00:42:48 +00004069/// Given a function expression of unknown-any type, try to rebuild it
4070/// to have a function type.
4071static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4072
John McCall76da55d2013-04-16 07:28:30 +00004073/// Is the given type a placeholder that we need to lower out
4074/// immediately during argument processing?
4075static bool isPlaceholderToRemoveAsArg(QualType type) {
4076 // Placeholders are never sugared.
4077 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4078 if (!placeholder) return false;
4079
4080 switch (placeholder->getKind()) {
4081 // Ignore all the non-placeholder types.
4082#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4083#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4084#include "clang/AST/BuiltinTypes.def"
4085 return false;
4086
4087 // We cannot lower out overload sets; they might validly be resolved
4088 // by the call machinery.
4089 case BuiltinType::Overload:
4090 return false;
4091
4092 // Unbridged casts in ARC can be handled in some call positions and
4093 // should be left in place.
4094 case BuiltinType::ARCUnbridgedCast:
4095 return false;
4096
4097 // Pseudo-objects should be converted as soon as possible.
4098 case BuiltinType::PseudoObject:
4099 return true;
4100
4101 // The debugger mode could theoretically but currently does not try
4102 // to resolve unknown-typed arguments based on known parameter types.
4103 case BuiltinType::UnknownAny:
4104 return true;
4105
4106 // These are always invalid as call arguments and should be reported.
4107 case BuiltinType::BoundMember:
4108 case BuiltinType::BuiltinFn:
4109 return true;
4110 }
4111 llvm_unreachable("bad builtin type kind");
4112}
4113
4114/// Check an argument list for placeholders that we won't try to
4115/// handle later.
4116static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4117 // Apply this processing to all the arguments at once instead of
4118 // dying at the first failure.
4119 bool hasInvalid = false;
4120 for (size_t i = 0, e = args.size(); i != e; i++) {
4121 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4122 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4123 if (result.isInvalid()) hasInvalid = true;
4124 else args[i] = result.take();
4125 }
4126 }
4127 return hasInvalid;
4128}
4129
Steve Narofff69936d2007-09-16 03:34:24 +00004130/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004131/// This provides the location of the left/right parens and a list of comma
4132/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004133ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004134Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004135 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004136 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004137 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004138 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004139 if (Result.isInvalid()) return ExprError();
4140 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004141
John McCall76da55d2013-04-16 07:28:30 +00004142 if (checkArgsForPlaceholders(*this, ArgExprs))
4143 return ExprError();
4144
David Blaikie4e4d0842012-03-11 07:00:24 +00004145 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004146 // If this is a pseudo-destructor expression, build the call immediately.
4147 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004148 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004149 // Pseudo-destructor calls should not have any arguments.
4150 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004151 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004152 SourceRange(ArgExprs[0]->getLocStart(),
4153 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00004154 }
Mike Stump1eb44332009-09-09 15:08:12 +00004155
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00004156 return Owned(new (Context) CallExpr(Context, Fn, None,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004157 Context.VoidTy, VK_RValue,
4158 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004159 }
John McCall76da55d2013-04-16 07:28:30 +00004160 if (Fn->getType() == Context.PseudoObjectTy) {
4161 ExprResult result = CheckPlaceholderExpr(Fn);
4162 if (result.isInvalid()) return ExprError();
4163 Fn = result.take();
4164 }
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Douglas Gregor17330012009-02-04 15:01:18 +00004166 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004167 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004168 // FIXME: Will need to cache the results of name lookup (including ADL) in
4169 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004170 bool Dependent = false;
4171 if (Fn->isTypeDependent())
4172 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004173 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00004174 Dependent = true;
4175
Peter Collingbournee08ce652011-02-09 21:07:24 +00004176 if (Dependent) {
4177 if (ExecConfig) {
4178 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004179 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004180 Context.DependentTy, VK_RValue, RParenLoc));
4181 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004182 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004183 Context.DependentTy, VK_RValue,
4184 RParenLoc));
4185 }
4186 }
Douglas Gregor17330012009-02-04 15:01:18 +00004187
4188 // Determine whether this is a call to an object (C++ [over.call.object]).
4189 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004190 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4191 ArgExprs.data(),
4192 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004193
John McCall755d8492011-04-12 00:42:48 +00004194 if (Fn->getType() == Context.UnknownAnyTy) {
4195 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4196 if (result.isInvalid()) return ExprError();
4197 Fn = result.take();
4198 }
4199
John McCall864c0412011-04-26 20:42:42 +00004200 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004201 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4202 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004203 }
John McCall864c0412011-04-26 20:42:42 +00004204 }
John McCall129e2df2009-11-30 22:42:35 +00004205
John McCall864c0412011-04-26 20:42:42 +00004206 // Check for overloaded calls. This can happen even in C due to extensions.
4207 if (Fn->getType() == Context.OverloadTy) {
4208 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4209
Douglas Gregoree697e62011-10-13 18:10:35 +00004210 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00004211 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00004212 OverloadExpr *ovl = find.Expression;
4213 if (isa<UnresolvedLookupExpr>(ovl)) {
4214 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004215 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
4216 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00004217 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004218 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4219 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004220 }
4221 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004222 }
4223
Douglas Gregorfa047642009-02-04 00:32:51 +00004224 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00004225 if (Fn->getType() == Context.UnknownAnyTy) {
4226 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4227 if (result.isInvalid()) return ExprError();
4228 Fn = result.take();
4229 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004230
Eli Friedmanefa42f72009-12-26 03:35:45 +00004231 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004232
John McCall3b4294e2009-12-16 12:17:52 +00004233 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004234 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4235 if (UnOp->getOpcode() == UO_AddrOf)
4236 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4237
John McCall3b4294e2009-12-16 12:17:52 +00004238 if (isa<DeclRefExpr>(NakedFn))
4239 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00004240 else if (isa<MemberExpr>(NakedFn))
4241 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004242
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004243 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4244 ArgExprs.size(), RParenLoc, ExecConfig,
4245 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004246}
4247
4248ExprResult
4249Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004250 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00004251 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4252 if (!ConfigDecl)
4253 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4254 << "cudaConfigureCall");
4255 QualType ConfigQTy = ConfigDecl->getType();
4256
4257 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00004258 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00004259 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004260
Peter Collingbourne1f240762011-10-02 23:49:29 +00004261 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4262 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00004263}
4264
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004265/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4266///
4267/// __builtin_astype( value, dst type )
4268///
Richard Trieuccd891a2011-09-09 01:45:06 +00004269ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004270 SourceLocation BuiltinLoc,
4271 SourceLocation RParenLoc) {
4272 ExprValueKind VK = VK_RValue;
4273 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00004274 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4275 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004276 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4277 return ExprError(Diag(BuiltinLoc,
4278 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00004279 << DstTy
4280 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00004281 << E->getSourceRange());
4282 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00004283 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004284}
4285
John McCall3b4294e2009-12-16 12:17:52 +00004286/// BuildResolvedCallExpr - Build a call to a resolved expression,
4287/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004288/// unary-convert to an expression of function-pointer or
4289/// block-pointer type.
4290///
4291/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004292ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004293Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4294 SourceLocation LParenLoc,
4295 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004296 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004297 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004298 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004299 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004300
Chris Lattner04421082008-04-08 04:40:51 +00004301 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004302 // We special-case function promotion here because we only allow promoting
4303 // builtin functions to function pointers in the callee of a call.
4304 ExprResult Result;
4305 if (BuiltinID &&
4306 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4307 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4308 CK_BuiltinFnToFnPtr).take();
4309 } else {
4310 Result = UsualUnaryConversions(Fn);
4311 }
John Wiegley429bb272011-04-08 18:41:53 +00004312 if (Result.isInvalid())
4313 return ExprError();
4314 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004315
Chris Lattner925e60d2007-12-28 05:29:59 +00004316 // Make the call expr early, before semantic checks. This guarantees cleanup
4317 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004318 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004319 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004320 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4321 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004322 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004323 Context.BoolTy,
4324 VK_RValue,
4325 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004326 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004327 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004328 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004329 Context.BoolTy,
4330 VK_RValue,
4331 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004332
John McCall8e10f3b2011-02-26 05:39:39 +00004333 // Bail out early if calling a builtin with custom typechecking.
4334 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4335 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4336
John McCall1de4d4e2011-04-07 08:22:57 +00004337 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004338 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004339 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004340 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4341 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004342 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004343 if (FuncT == 0)
4344 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4345 << Fn->getType() << Fn->getSourceRange());
4346 } else if (const BlockPointerType *BPT =
4347 Fn->getType()->getAs<BlockPointerType>()) {
4348 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4349 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004350 // Handle calls to expressions of unknown-any type.
4351 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004352 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004353 if (rewrite.isInvalid()) return ExprError();
4354 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004355 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004356 goto retry;
4357 }
4358
Sebastian Redl0eb23302009-01-19 00:08:26 +00004359 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4360 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004361 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004362
David Blaikie4e4d0842012-03-11 07:00:24 +00004363 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004364 if (Config) {
4365 // CUDA: Kernel calls must be to global functions
4366 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4367 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4368 << FDecl->getName() << Fn->getSourceRange());
4369
4370 // CUDA: Kernel function must have 'void' return type
4371 if (!FuncT->getResultType()->isVoidType())
4372 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4373 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004374 } else {
4375 // CUDA: Calls to global functions must be configured
4376 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4377 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4378 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004379 }
4380 }
4381
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004382 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004383 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004384 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004385 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004386 return ExprError();
4387
Chris Lattner925e60d2007-12-28 05:29:59 +00004388 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004389 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004390 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004391
Richard Smith831421f2012-06-25 20:30:08 +00004392 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4393 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004394 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004395 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004396 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004397 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004398 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004399
Douglas Gregor74734d52009-04-02 15:37:10 +00004400 if (FDecl) {
4401 // Check if we have too few/too many template arguments, based
4402 // on our knowledge of the function definition.
4403 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004404 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004405 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004406 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004407 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4408 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004409 }
Douglas Gregor46542412010-10-25 20:39:23 +00004410
4411 // If the function we're calling isn't a function prototype, but we have
4412 // a function prototype from a prior declaratiom, use that prototype.
4413 if (!FDecl->hasPrototype())
4414 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004415 }
4416
Steve Naroffb291ab62007-08-28 23:30:39 +00004417 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004418 for (unsigned i = 0; i != NumArgs; i++) {
4419 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004420
4421 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004422 InitializedEntity Entity
4423 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004424 Proto->getArgType(i),
4425 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004426 ExprResult ArgE = PerformCopyInitialization(Entity,
4427 SourceLocation(),
4428 Owned(Arg));
4429 if (ArgE.isInvalid())
4430 return true;
4431
4432 Arg = ArgE.takeAs<Expr>();
4433
4434 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004435 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4436
4437 if (ArgE.isInvalid())
4438 return true;
4439
4440 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004441 }
4442
Daniel Dunbar96a00142012-03-09 18:35:03 +00004443 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004444 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004445 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004446 return ExprError();
4447
Chris Lattner925e60d2007-12-28 05:29:59 +00004448 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004449 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004450 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004451
Douglas Gregor88a35142008-12-22 05:46:06 +00004452 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4453 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004454 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4455 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004456
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004457 // Check for sentinels
4458 if (NDecl)
4459 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Chris Lattner59907c42007-08-10 20:18:51 +00004461 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004462 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004463 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004464 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004465
John McCall8e10f3b2011-02-26 05:39:39 +00004466 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004467 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004468 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004469 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004470 return ExprError();
4471 }
Chris Lattner59907c42007-08-10 20:18:51 +00004472
John McCall9ae2f072010-08-23 23:25:46 +00004473 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004474}
4475
John McCall60d7b3a2010-08-24 06:29:42 +00004476ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004477Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004478 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004479 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004480 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004481 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004482
4483 TypeSourceInfo *TInfo;
4484 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4485 if (!TInfo)
4486 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4487
John McCall9ae2f072010-08-23 23:25:46 +00004488 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004489}
4490
John McCall60d7b3a2010-08-24 06:29:42 +00004491ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004492Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004493 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004494 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004495
Eli Friedman6223c222008-05-20 05:22:08 +00004496 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004497 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004498 diag::err_illegal_decl_array_incomplete_type,
4499 SourceRange(LParenLoc,
4500 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004501 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004502 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004503 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004504 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004505 } else if (!literalType->isDependentType() &&
4506 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004507 diag::err_typecheck_decl_incomplete_type,
4508 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004509 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004510
Douglas Gregor99a2e602009-12-16 01:38:02 +00004511 InitializedEntity Entity
Jordan Rose2624b812013-05-06 16:48:12 +00004512 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004513 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004514 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004515 SourceRange(LParenLoc, RParenLoc),
4516 /*InitList=*/true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004517 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004518 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4519 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004520 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004521 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004522 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004523
Chris Lattner371f2582008-12-04 23:50:19 +00004524 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004525 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004526 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004527 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004528 }
Eli Friedman08544622009-12-22 02:35:53 +00004529
John McCallf89e55a2010-11-18 06:31:45 +00004530 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004531 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004532
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004533 return MaybeBindToTemporary(
4534 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004535 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004536}
4537
John McCall60d7b3a2010-08-24 06:29:42 +00004538ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004539Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004540 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004541 // Immediately handle non-overload placeholders. Overloads can be
4542 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004543 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4544 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4545 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004546
4547 // Ignore failures; dropping the entire initializer list because
4548 // of one failure would be terrible for indexing/etc.
4549 if (result.isInvalid()) continue;
4550
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004551 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004552 }
4553 }
4554
Steve Naroff08d92e42007-09-15 18:49:24 +00004555 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004556 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004557
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004558 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4559 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004560 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004561 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004562}
4563
John McCalldc05b112011-09-10 01:16:55 +00004564/// Do an explicit extend of the given block pointer if we're in ARC.
4565static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4566 assert(E.get()->getType()->isBlockPointerType());
4567 assert(E.get()->isRValue());
4568
4569 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004570 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004571
4572 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004573 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004574 /*base path*/ 0, VK_RValue);
4575 S.ExprNeedsCleanups = true;
4576}
4577
4578/// Prepare a conversion of the given expression to an ObjC object
4579/// pointer type.
4580CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4581 QualType type = E.get()->getType();
4582 if (type->isObjCObjectPointerType()) {
4583 return CK_BitCast;
4584 } else if (type->isBlockPointerType()) {
4585 maybeExtendBlockObject(*this, E);
4586 return CK_BlockPointerToObjCPointerCast;
4587 } else {
4588 assert(type->isPointerType());
4589 return CK_CPointerToObjCPointerCast;
4590 }
4591}
4592
John McCallf3ea8cf2010-11-14 08:17:51 +00004593/// Prepares for a scalar cast, performing all the necessary stages
4594/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004595CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004596 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4597 // Also, callers should have filtered out the invalid cases with
4598 // pointers. Everything else should be possible.
4599
John Wiegley429bb272011-04-08 18:41:53 +00004600 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004601 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004602 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004603
John McCall1d9b3b22011-09-09 05:25:32 +00004604 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004605 case Type::STK_MemberPointer:
4606 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004607
John McCall1d9b3b22011-09-09 05:25:32 +00004608 case Type::STK_CPointer:
4609 case Type::STK_BlockPointer:
4610 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004611 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004612 case Type::STK_CPointer:
4613 return CK_BitCast;
4614 case Type::STK_BlockPointer:
4615 return (SrcKind == Type::STK_BlockPointer
4616 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4617 case Type::STK_ObjCObjectPointer:
4618 if (SrcKind == Type::STK_ObjCObjectPointer)
4619 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004620 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004621 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004622 maybeExtendBlockObject(*this, Src);
4623 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004624 case Type::STK_Bool:
4625 return CK_PointerToBoolean;
4626 case Type::STK_Integral:
4627 return CK_PointerToIntegral;
4628 case Type::STK_Floating:
4629 case Type::STK_FloatingComplex:
4630 case Type::STK_IntegralComplex:
4631 case Type::STK_MemberPointer:
4632 llvm_unreachable("illegal cast from pointer");
4633 }
David Blaikie7530c032012-01-17 06:56:22 +00004634 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004635
John McCalldaa8e4e2010-11-15 09:13:47 +00004636 case Type::STK_Bool: // casting from bool is like casting from an integer
4637 case Type::STK_Integral:
4638 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004639 case Type::STK_CPointer:
4640 case Type::STK_ObjCObjectPointer:
4641 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004642 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004643 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004644 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004645 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004646 case Type::STK_Bool:
4647 return CK_IntegralToBoolean;
4648 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004649 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004650 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004651 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004652 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004653 Src = ImpCastExprToType(Src.take(),
4654 DestTy->castAs<ComplexType>()->getElementType(),
4655 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004656 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004657 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004658 Src = ImpCastExprToType(Src.take(),
4659 DestTy->castAs<ComplexType>()->getElementType(),
4660 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004661 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004662 case Type::STK_MemberPointer:
4663 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004664 }
David Blaikie7530c032012-01-17 06:56:22 +00004665 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004666
John McCalldaa8e4e2010-11-15 09:13:47 +00004667 case Type::STK_Floating:
4668 switch (DestTy->getScalarTypeKind()) {
4669 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004670 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004671 case Type::STK_Bool:
4672 return CK_FloatingToBoolean;
4673 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004674 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004675 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004676 Src = ImpCastExprToType(Src.take(),
4677 DestTy->castAs<ComplexType>()->getElementType(),
4678 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004679 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004680 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004681 Src = ImpCastExprToType(Src.take(),
4682 DestTy->castAs<ComplexType>()->getElementType(),
4683 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004684 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004685 case Type::STK_CPointer:
4686 case Type::STK_ObjCObjectPointer:
4687 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004688 llvm_unreachable("valid float->pointer cast?");
4689 case Type::STK_MemberPointer:
4690 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004691 }
David Blaikie7530c032012-01-17 06:56:22 +00004692 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004693
John McCalldaa8e4e2010-11-15 09:13:47 +00004694 case Type::STK_FloatingComplex:
4695 switch (DestTy->getScalarTypeKind()) {
4696 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004697 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004698 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004699 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004700 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004701 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4702 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004703 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004704 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004705 return CK_FloatingCast;
4706 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004707 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004708 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004709 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004710 Src = ImpCastExprToType(Src.take(),
4711 SrcTy->castAs<ComplexType>()->getElementType(),
4712 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004713 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004714 case Type::STK_CPointer:
4715 case Type::STK_ObjCObjectPointer:
4716 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004717 llvm_unreachable("valid complex float->pointer cast?");
4718 case Type::STK_MemberPointer:
4719 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004720 }
David Blaikie7530c032012-01-17 06:56:22 +00004721 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004722
John McCalldaa8e4e2010-11-15 09:13:47 +00004723 case Type::STK_IntegralComplex:
4724 switch (DestTy->getScalarTypeKind()) {
4725 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004726 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004727 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004728 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004729 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004730 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4731 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004732 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004733 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004734 return CK_IntegralCast;
4735 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004736 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004737 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004738 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004739 Src = ImpCastExprToType(Src.take(),
4740 SrcTy->castAs<ComplexType>()->getElementType(),
4741 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004742 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004743 case Type::STK_CPointer:
4744 case Type::STK_ObjCObjectPointer:
4745 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004746 llvm_unreachable("valid complex int->pointer cast?");
4747 case Type::STK_MemberPointer:
4748 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004749 }
David Blaikie7530c032012-01-17 06:56:22 +00004750 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004751 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004752
John McCallf3ea8cf2010-11-14 08:17:51 +00004753 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004754}
4755
Anders Carlssonc3516322009-10-16 02:48:28 +00004756bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004757 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004758 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004759
Anders Carlssona64db8f2007-11-27 05:51:55 +00004760 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004761 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004762 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004764 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004765 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004766 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004767 } else
4768 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004769 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004770 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004771
John McCall2de56d12010-08-25 11:45:40 +00004772 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004773 return false;
4774}
4775
John Wiegley429bb272011-04-08 18:41:53 +00004776ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4777 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004778 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004779
Anders Carlsson16a89042009-10-16 05:23:41 +00004780 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004781
Nate Begeman9b10da62009-06-27 22:05:55 +00004782 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4783 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004784 // In OpenCL, casts between vectors of different types are not allowed.
4785 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004786 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004787 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004788 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004789 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004790 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004791 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004792 return ExprError();
4793 }
John McCall2de56d12010-08-25 11:45:40 +00004794 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004795 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004796 }
4797
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004798 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004799 // conversion will take place first from scalar to elt type, and then
4800 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004801 if (SrcTy->isPointerType())
4802 return Diag(R.getBegin(),
4803 diag::err_invalid_conversion_between_vector_and_scalar)
4804 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004805
4806 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004807 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004808 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004809 if (CastExprRes.isInvalid())
4810 return ExprError();
4811 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004812
John McCall2de56d12010-08-25 11:45:40 +00004813 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004814 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004815}
4816
John McCall60d7b3a2010-08-24 06:29:42 +00004817ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004818Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4819 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004820 SourceLocation RParenLoc, Expr *CastExpr) {
4821 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004822 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004823
Richard Trieuccd891a2011-09-09 01:45:06 +00004824 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004825 if (D.isInvalidType())
4826 return ExprError();
4827
David Blaikie4e4d0842012-03-11 07:00:24 +00004828 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004829 // Check that there are no default arguments (C++ only).
4830 CheckExtraCXXDefaultArguments(D);
4831 }
4832
John McCalle82247a2011-10-01 05:17:03 +00004833 checkUnusedDeclAttributes(D);
4834
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004835 QualType castType = castTInfo->getType();
4836 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004838 bool isVectorLiteral = false;
4839
4840 // Check for an altivec or OpenCL literal,
4841 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004842 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4843 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004844 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004845 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004846 if (PLE && PLE->getNumExprs() == 0) {
4847 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4848 return ExprError();
4849 }
4850 if (PE || PLE->getNumExprs() == 1) {
4851 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4852 if (!E->getType()->isVectorType())
4853 isVectorLiteral = true;
4854 }
4855 else
4856 isVectorLiteral = true;
4857 }
4858
4859 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4860 // then handle it as such.
4861 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004862 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004863
Nate Begeman2ef13e52009-08-10 23:49:36 +00004864 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004865 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4866 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004867 if (isa<ParenListExpr>(CastExpr)) {
4868 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004869 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004870 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004871 }
John McCallb042fdf2010-01-15 18:56:44 +00004872
Richard Trieuccd891a2011-09-09 01:45:06 +00004873 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004874}
4875
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004876ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4877 SourceLocation RParenLoc, Expr *E,
4878 TypeSourceInfo *TInfo) {
4879 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4880 "Expected paren or paren list expression");
4881
4882 Expr **exprs;
4883 unsigned numExprs;
4884 Expr *subExpr;
Richard Smithafbcab82013-02-05 05:55:57 +00004885 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004886 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smithafbcab82013-02-05 05:55:57 +00004887 LiteralLParenLoc = PE->getLParenLoc();
4888 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004889 exprs = PE->getExprs();
4890 numExprs = PE->getNumExprs();
Richard Smithafbcab82013-02-05 05:55:57 +00004891 } else { // isa<ParenExpr> by assertion at function entrance
4892 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4893 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004894 subExpr = cast<ParenExpr>(E)->getSubExpr();
4895 exprs = &subExpr;
4896 numExprs = 1;
4897 }
4898
4899 QualType Ty = TInfo->getType();
4900 assert(Ty->isVectorType() && "Expected vector type");
4901
Chris Lattner5f9e2722011-07-23 10:55:15 +00004902 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004903 const VectorType *VTy = Ty->getAs<VectorType>();
4904 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4905
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004906 // '(...)' form of vector initialization in AltiVec: the number of
4907 // initializers must be one or must match the size of the vector.
4908 // If a single value is specified in the initializer then it will be
4909 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004910 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004911 // The number of initializers must be one or must match the size of the
4912 // vector. If a single value is specified in the initializer then it will
4913 // be replicated to all the components of the vector
4914 if (numExprs == 1) {
4915 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004916 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4917 if (Literal.isInvalid())
4918 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004919 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004920 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004921 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4922 }
4923 else if (numExprs < numElems) {
4924 Diag(E->getExprLoc(),
4925 diag::err_incorrect_number_of_vector_initializers);
4926 return ExprError();
4927 }
4928 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004929 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004930 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004931 else {
4932 // For OpenCL, when the number of initializers is a single value,
4933 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004934 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004935 VTy->getVectorKind() == VectorType::GenericVector &&
4936 numExprs == 1) {
4937 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004938 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4939 if (Literal.isInvalid())
4940 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004941 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004942 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004943 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4944 }
4945
Benjamin Kramer14c59822012-02-14 12:06:21 +00004946 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004947 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004948 // FIXME: This means that pretty-printing the final AST will produce curly
4949 // braces instead of the original commas.
Richard Smithafbcab82013-02-05 05:55:57 +00004950 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4951 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004952 initE->setType(Ty);
4953 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4954}
4955
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004956/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4957/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004958ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004959Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4960 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004961 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004962 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004963
John McCall60d7b3a2010-08-24 06:29:42 +00004964 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Nate Begeman2ef13e52009-08-10 23:49:36 +00004966 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004967 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4968 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004969
John McCall9ae2f072010-08-23 23:25:46 +00004970 if (Result.isInvalid()) return ExprError();
4971
4972 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004973}
4974
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004975ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4976 SourceLocation R,
4977 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004978 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004979 return Owned(expr);
4980}
4981
Chandler Carruth82214a82011-02-18 23:54:50 +00004982/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004983/// constant and the other is not a pointer. Returns true if a diagnostic is
4984/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004985bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004986 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004987 Expr *NullExpr = LHSExpr;
4988 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004989 Expr::NullPointerConstantKind NullKind =
4990 NullExpr->isNullPointerConstant(Context,
4991 Expr::NPC_ValueDependentIsNotNull);
4992
4993 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004994 NullExpr = RHSExpr;
4995 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004996 NullKind =
4997 NullExpr->isNullPointerConstant(Context,
4998 Expr::NPC_ValueDependentIsNotNull);
4999 }
5000
5001 if (NullKind == Expr::NPCK_NotNull)
5002 return false;
5003
David Blaikie50800fc2012-08-08 17:33:31 +00005004 if (NullKind == Expr::NPCK_ZeroExpression)
5005 return false;
5006
5007 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00005008 // In this case, check to make sure that we got here from a "NULL"
5009 // string in the source code.
5010 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005011 SourceLocation loc = NullExpr->getExprLoc();
5012 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005013 return false;
5014 }
5015
Richard Smith4e24f0f2013-01-02 12:01:23 +00005016 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carruth82214a82011-02-18 23:54:50 +00005017 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5018 << NonPointerExpr->getType() << DiagType
5019 << NonPointerExpr->getSourceRange();
5020 return true;
5021}
5022
Richard Trieu26f96072011-09-02 01:51:02 +00005023/// \brief Return false if the condition expression is valid, true otherwise.
5024static bool checkCondition(Sema &S, Expr *Cond) {
5025 QualType CondTy = Cond->getType();
5026
5027 // C99 6.5.15p2
5028 if (CondTy->isScalarType()) return false;
5029
Tanya Lattnerd1cc5142013-04-03 23:55:58 +00005030 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00005031 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00005032 return false;
5033
5034 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00005035 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00005036 diag::err_typecheck_cond_expect_scalar :
5037 diag::err_typecheck_cond_expect_scalar_or_vector)
5038 << CondTy;
5039 return true;
5040}
5041
5042/// \brief Return false if the two expressions can be converted to a vector,
5043/// true otherwise
5044static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5045 ExprResult &RHS,
5046 QualType CondTy) {
5047 // Both operands should be of scalar type.
5048 if (!LHS.get()->getType()->isScalarType()) {
5049 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5050 << CondTy;
5051 return true;
5052 }
5053 if (!RHS.get()->getType()->isScalarType()) {
5054 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5055 << CondTy;
5056 return true;
5057 }
5058
5059 // Implicity convert these scalars to the type of the condition.
5060 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5061 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5062 return false;
5063}
5064
5065/// \brief Handle when one or both operands are void type.
5066static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5067 ExprResult &RHS) {
5068 Expr *LHSExpr = LHS.get();
5069 Expr *RHSExpr = RHS.get();
5070
5071 if (!LHSExpr->getType()->isVoidType())
5072 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5073 << RHSExpr->getSourceRange();
5074 if (!RHSExpr->getType()->isVoidType())
5075 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5076 << LHSExpr->getSourceRange();
5077 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5078 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5079 return S.Context.VoidTy;
5080}
5081
5082/// \brief Return false if the NullExpr can be promoted to PointerTy,
5083/// true otherwise.
5084static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5085 QualType PointerTy) {
5086 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5087 !NullExpr.get()->isNullPointerConstant(S.Context,
5088 Expr::NPC_ValueDependentIsNull))
5089 return true;
5090
5091 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5092 return false;
5093}
5094
5095/// \brief Checks compatibility between two pointers and return the resulting
5096/// type.
5097static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5098 ExprResult &RHS,
5099 SourceLocation Loc) {
5100 QualType LHSTy = LHS.get()->getType();
5101 QualType RHSTy = RHS.get()->getType();
5102
5103 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5104 // Two identical pointers types are always compatible.
5105 return LHSTy;
5106 }
5107
5108 QualType lhptee, rhptee;
5109
5110 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00005111 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5112 lhptee = LHSBTy->getPointeeType();
5113 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00005114 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00005115 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5116 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00005117 }
5118
Eli Friedmanae916a12012-04-05 22:30:04 +00005119 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5120 // differently qualified versions of compatible types, the result type is
5121 // a pointer to an appropriately qualified version of the composite
5122 // type.
5123
5124 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5125 // clause doesn't make sense for our extensions. E.g. address space 2 should
5126 // be incompatible with address space 3: they may live on different devices or
5127 // anything.
5128 Qualifiers lhQual = lhptee.getQualifiers();
5129 Qualifiers rhQual = rhptee.getQualifiers();
5130
5131 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5132 lhQual.removeCVRQualifiers();
5133 rhQual.removeCVRQualifiers();
5134
5135 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5136 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5137
5138 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5139
5140 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005141 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5142 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5143 << RHS.get()->getSourceRange();
5144 // In this situation, we assume void* type. No especially good
5145 // reason, but this is what gcc does, and we do have to pick
5146 // to get a consistent AST.
5147 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5148 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5149 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5150 return incompatTy;
5151 }
5152
5153 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00005154 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5155 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00005156
Eli Friedmanae916a12012-04-05 22:30:04 +00005157 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5158 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5159 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005160}
5161
5162/// \brief Return the resulting type when the operands are both block pointers.
5163static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5164 ExprResult &LHS,
5165 ExprResult &RHS,
5166 SourceLocation Loc) {
5167 QualType LHSTy = LHS.get()->getType();
5168 QualType RHSTy = RHS.get()->getType();
5169
5170 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5171 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5172 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5173 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5174 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5175 return destType;
5176 }
5177 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5178 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5179 << RHS.get()->getSourceRange();
5180 return QualType();
5181 }
5182
5183 // We have 2 block pointer types.
5184 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5185}
5186
5187/// \brief Return the resulting type when the operands are both pointers.
5188static QualType
5189checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5190 ExprResult &RHS,
5191 SourceLocation Loc) {
5192 // get the pointer types
5193 QualType LHSTy = LHS.get()->getType();
5194 QualType RHSTy = RHS.get()->getType();
5195
5196 // get the "pointed to" types
5197 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5198 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5199
5200 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5201 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5202 // Figure out necessary qualifiers (C99 6.5.15p6)
5203 QualType destPointee
5204 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5205 QualType destType = S.Context.getPointerType(destPointee);
5206 // Add qualifiers if necessary.
5207 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5208 // Promote to void*.
5209 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5210 return destType;
5211 }
5212 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5213 QualType destPointee
5214 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5215 QualType destType = S.Context.getPointerType(destPointee);
5216 // Add qualifiers if necessary.
5217 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5218 // Promote to void*.
5219 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5220 return destType;
5221 }
5222
5223 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5224}
5225
5226/// \brief Return false if the first expression is not an integer and the second
5227/// expression is not a pointer, true otherwise.
5228static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5229 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005230 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00005231 if (!PointerExpr->getType()->isPointerType() ||
5232 !Int.get()->getType()->isIntegerType())
5233 return false;
5234
Richard Trieuccd891a2011-09-09 01:45:06 +00005235 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5236 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00005237
5238 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5239 << Expr1->getType() << Expr2->getType()
5240 << Expr1->getSourceRange() << Expr2->getSourceRange();
5241 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5242 CK_IntegralToPointer);
5243 return true;
5244}
5245
Richard Trieu33fc7572011-09-06 20:06:39 +00005246/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5247/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005248/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00005249QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5250 ExprResult &RHS, ExprValueKind &VK,
5251 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005252 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005253
Richard Trieu33fc7572011-09-06 20:06:39 +00005254 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5255 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005256 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005257
Richard Trieu33fc7572011-09-06 20:06:39 +00005258 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5259 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005260 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005261
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005262 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00005263 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005264 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005265
5266 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005267 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005268
John Wiegley429bb272011-04-08 18:41:53 +00005269 Cond = UsualUnaryConversions(Cond.take());
5270 if (Cond.isInvalid())
5271 return QualType();
5272 LHS = UsualUnaryConversions(LHS.take());
5273 if (LHS.isInvalid())
5274 return QualType();
5275 RHS = UsualUnaryConversions(RHS.take());
5276 if (RHS.isInvalid())
5277 return QualType();
5278
5279 QualType CondTy = Cond.get()->getType();
5280 QualType LHSTy = LHS.get()->getType();
5281 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005282
Reid Spencer5f016e22007-07-11 17:01:13 +00005283 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00005284 if (checkCondition(*this, Cond.get()))
5285 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005286
Chris Lattner70d67a92008-01-06 22:42:25 +00005287 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005288 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005289 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00005290
Tanya Lattnerd1cc5142013-04-03 23:55:58 +00005291 // If the condition is a vector, and both operands are scalar,
Nate Begeman6155d732010-09-20 22:41:17 +00005292 // attempt to implicity convert them to the vector type to act like the
Tanya Lattnerd1cc5142013-04-03 23:55:58 +00005293 // built in select. (OpenCL v1.1 s6.3.i)
David Blaikie4e4d0842012-03-11 07:00:24 +00005294 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00005295 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00005296 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00005297
Chris Lattner70d67a92008-01-06 22:42:25 +00005298 // If both operands have arithmetic type, do the usual arithmetic conversions
5299 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005300 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5301 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005302 if (LHS.isInvalid() || RHS.isInvalid())
5303 return QualType();
5304 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005305 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005306
Chris Lattner70d67a92008-01-06 22:42:25 +00005307 // If both operands are the same structure or union type, the result is that
5308 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005309 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5310 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005311 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005312 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005313 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005314 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005315 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005316 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005317
Chris Lattner70d67a92008-01-06 22:42:25 +00005318 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005319 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005320 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005321 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005322 }
Richard Trieu26f96072011-09-02 01:51:02 +00005323
Steve Naroffb6d54e52008-01-08 01:11:38 +00005324 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5325 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005326 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5327 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005328
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005329 // All objective-c pointer type analysis is done here.
5330 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5331 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005332 if (LHS.isInvalid() || RHS.isInvalid())
5333 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005334 if (!compositeType.isNull())
5335 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005336
5337
Steve Naroff7154a772009-07-01 14:36:47 +00005338 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005339 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5340 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5341 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005342
Steve Naroff7154a772009-07-01 14:36:47 +00005343 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005344 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5345 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5346 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005347
John McCall404cd162010-11-13 01:35:44 +00005348 // GCC compatibility: soften pointer/integer mismatch. Note that
5349 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005350 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5351 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005352 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005353 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5354 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005355 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005356
Chandler Carruth82214a82011-02-18 23:54:50 +00005357 // Emit a better diagnostic if one of the expressions is a null pointer
5358 // constant and the other is not a pointer type. In this case, the user most
5359 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005360 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005361 return QualType();
5362
Chris Lattner70d67a92008-01-06 22:42:25 +00005363 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005364 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005365 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5366 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005367 return QualType();
5368}
5369
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005370/// FindCompositeObjCPointerType - Helper method to find composite type of
5371/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005372QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005373 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005374 QualType LHSTy = LHS.get()->getType();
5375 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005376
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005377 // Handle things like Class and struct objc_class*. Here we case the result
5378 // to the pseudo-builtin, because that will be implicitly cast back to the
5379 // redefinition type if an attempt is made to access its fields.
5380 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005381 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005382 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005383 return LHSTy;
5384 }
5385 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005386 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005387 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005388 return RHSTy;
5389 }
5390 // And the same for struct objc_object* / id
5391 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005392 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005393 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005394 return LHSTy;
5395 }
5396 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005397 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005398 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005399 return RHSTy;
5400 }
5401 // And the same for struct objc_selector* / SEL
5402 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005403 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005404 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005405 return LHSTy;
5406 }
5407 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005408 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005409 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005410 return RHSTy;
5411 }
5412 // Check constraints for Objective-C object pointers types.
5413 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005414
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005415 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5416 // Two identical object pointer types are always compatible.
5417 return LHSTy;
5418 }
John McCall1d9b3b22011-09-09 05:25:32 +00005419 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5420 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005421 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005422
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005423 // If both operands are interfaces and either operand can be
5424 // assigned to the other, use that type as the composite
5425 // type. This allows
5426 // xxx ? (A*) a : (B*) b
5427 // where B is a subclass of A.
5428 //
5429 // Additionally, as for assignment, if either type is 'id'
5430 // allow silent coercion. Finally, if the types are
5431 // incompatible then make sure to use 'id' as the composite
5432 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005433
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005434 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5435 // It could return the composite type.
5436 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5437 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5438 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5439 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5440 } else if ((LHSTy->isObjCQualifiedIdType() ||
5441 RHSTy->isObjCQualifiedIdType()) &&
5442 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5443 // Need to handle "id<xx>" explicitly.
5444 // GCC allows qualified id and any Objective-C type to devolve to
5445 // id. Currently localizing to here until clear this should be
5446 // part of ObjCQualifiedIdTypesAreCompatible.
5447 compositeType = Context.getObjCIdType();
5448 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5449 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005450 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005451 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5452 ;
5453 else {
5454 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5455 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005456 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005457 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005458 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5459 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005460 return incompatTy;
5461 }
5462 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005463 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5464 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005465 return compositeType;
5466 }
5467 // Check Objective-C object pointer types and 'void *'
5468 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005469 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005470 // ARC forbids the implicit conversion of object pointers to 'void *',
5471 // so these types are not compatible.
5472 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5473 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5474 LHS = RHS = true;
5475 return QualType();
5476 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005477 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5478 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5479 QualType destPointee
5480 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5481 QualType destType = Context.getPointerType(destPointee);
5482 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005483 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005484 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005485 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005486 return destType;
5487 }
5488 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005489 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005490 // ARC forbids the implicit conversion of object pointers to 'void *',
5491 // so these types are not compatible.
5492 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5493 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5494 LHS = RHS = true;
5495 return QualType();
5496 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005497 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5498 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5499 QualType destPointee
5500 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5501 QualType destType = Context.getPointerType(destPointee);
5502 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005503 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005504 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005505 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005506 return destType;
5507 }
5508 return QualType();
5509}
5510
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005511/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005512/// ParenRange in parentheses.
5513static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005514 const PartialDiagnostic &Note,
5515 SourceRange ParenRange) {
5516 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5517 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5518 EndLoc.isValid()) {
5519 Self.Diag(Loc, Note)
5520 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5521 << FixItHint::CreateInsertion(EndLoc, ")");
5522 } else {
5523 // We can't display the parentheses, so just show the bare note.
5524 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005525 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005526}
5527
5528static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5529 return Opc >= BO_Mul && Opc <= BO_Shr;
5530}
5531
Hans Wennborg2f072b42011-06-09 17:06:51 +00005532/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5533/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005534/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5535/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005536static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005537 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005538 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5539 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005540 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005541 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005542
5543 // Built-in binary operator.
5544 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5545 if (IsArithmeticOp(OP->getOpcode())) {
5546 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005547 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005548 return true;
5549 }
5550 }
5551
5552 // Overloaded operator.
5553 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5554 if (Call->getNumArgs() != 2)
5555 return false;
5556
5557 // Make sure this is really a binary operator that is safe to pass into
5558 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5559 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer66dca6e2013-03-30 11:56:00 +00005560 if (OO < OO_Plus || OO > OO_Arrow ||
5561 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborg2f072b42011-06-09 17:06:51 +00005562 return false;
5563
5564 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5565 if (IsArithmeticOp(OpKind)) {
5566 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005567 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005568 return true;
5569 }
5570 }
5571
5572 return false;
5573}
5574
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005575static bool IsLogicOp(BinaryOperatorKind Opc) {
5576 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5577}
5578
Hans Wennborg2f072b42011-06-09 17:06:51 +00005579/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5580/// or is a logical expression such as (x==y) which has int type, but is
5581/// commonly interpreted as boolean.
5582static bool ExprLooksBoolean(Expr *E) {
5583 E = E->IgnoreParenImpCasts();
5584
5585 if (E->getType()->isBooleanType())
5586 return true;
5587 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5588 return IsLogicOp(OP->getOpcode());
5589 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5590 return OP->getOpcode() == UO_LNot;
5591
5592 return false;
5593}
5594
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005595/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5596/// and binary operator are mixed in a way that suggests the programmer assumed
5597/// the conditional operator has higher precedence, for example:
5598/// "int x = a + someBinaryCondition ? 1 : 2".
5599static void DiagnoseConditionalPrecedence(Sema &Self,
5600 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005601 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005602 Expr *LHSExpr,
5603 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005604 BinaryOperatorKind CondOpcode;
5605 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005606
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005607 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005608 return;
5609 if (!ExprLooksBoolean(CondRHS))
5610 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005611
Hans Wennborg2f072b42011-06-09 17:06:51 +00005612 // The condition is an arithmetic binary expression, with a right-
5613 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005614
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005615 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005616 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005617 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005618
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005619 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005620 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005621 << BinaryOperator::getOpcodeStr(CondOpcode),
5622 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005623
5624 SuggestParentheses(Self, OpLoc,
5625 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005626 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005627}
5628
Steve Narofff69936d2007-09-16 03:34:24 +00005629/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005630/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005631ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005632 SourceLocation ColonLoc,
5633 Expr *CondExpr, Expr *LHSExpr,
5634 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005635 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5636 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005637 OpaqueValueExpr *opaqueValue = 0;
5638 Expr *commonExpr = 0;
5639 if (LHSExpr == 0) {
5640 commonExpr = CondExpr;
5641
5642 // We usually want to apply unary conversions *before* saving, except
5643 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005644 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005645 && !commonExpr->isTypeDependent()
5646 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5647 && commonExpr->isGLValue()
5648 && commonExpr->isOrdinaryOrBitFieldObject()
5649 && RHSExpr->isOrdinaryOrBitFieldObject()
5650 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005651 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5652 if (commonRes.isInvalid())
5653 return ExprError();
5654 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005655 }
5656
5657 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5658 commonExpr->getType(),
5659 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005660 commonExpr->getObjectKind(),
5661 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005662 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005663 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005664
John McCallf89e55a2010-11-18 06:31:45 +00005665 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005666 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005667 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5668 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005669 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005670 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5671 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005672 return ExprError();
5673
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005674 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5675 RHS.get());
5676
John McCall56ca35d2011-02-17 10:25:35 +00005677 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005678 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5679 LHS.take(), ColonLoc,
5680 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005681
5682 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005683 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005684 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5685 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005686}
5687
John McCalle4be87e2011-01-31 23:13:11 +00005688// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005689// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005690// routine is it effectively iqnores the qualifiers on the top level pointee.
5691// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5692// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005693static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005694checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5695 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5696 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005697
Reid Spencer5f016e22007-07-11 17:01:13 +00005698 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005699 const Type *lhptee, *rhptee;
5700 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005701 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5702 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005703
John McCalle4be87e2011-01-31 23:13:11 +00005704 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005705
5706 // C99 6.5.16.1p1: This following citation is common to constraints
5707 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5708 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005709 Qualifiers lq;
5710
John McCallf85e1932011-06-15 23:02:42 +00005711 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5712 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5713 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5714 // Ignore lifetime for further calculation.
5715 lhq.removeObjCLifetime();
5716 rhq.removeObjCLifetime();
5717 }
5718
John McCall86c05f32011-02-01 00:10:29 +00005719 if (!lhq.compatiblyIncludes(rhq)) {
5720 // Treat address-space mismatches as fatal. TODO: address subspaces
5721 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5722 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5723
John McCallf85e1932011-06-15 23:02:42 +00005724 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005725 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005726 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005727 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005728 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005729 && (lhptee->isVoidType() || rhptee->isVoidType()))
5730 ; // keep old
5731
John McCallf85e1932011-06-15 23:02:42 +00005732 // Treat lifetime mismatches as fatal.
5733 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5734 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5735
John McCall86c05f32011-02-01 00:10:29 +00005736 // For GCC compatibility, other qualifier mismatches are treated
5737 // as still compatible in C.
5738 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5739 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005740
Mike Stumpeed9cac2009-02-19 03:04:26 +00005741 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5742 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005743 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005744 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005745 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005746 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005747
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005748 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005749 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005750 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005751 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005752
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005753 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005754 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005755 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005756
5757 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005758 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005759 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005760 }
John McCall86c05f32011-02-01 00:10:29 +00005761
Mike Stumpeed9cac2009-02-19 03:04:26 +00005762 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005763 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005764 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5765 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005766 // Check if the pointee types are compatible ignoring the sign.
5767 // We explicitly check for char so that we catch "char" vs
5768 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005769 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005770 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005771 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005772 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005773
Chris Lattner6a2b9262009-10-17 20:33:28 +00005774 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005775 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005776 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005777 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005778
John McCall86c05f32011-02-01 00:10:29 +00005779 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005780 // Types are compatible ignoring the sign. Qualifier incompatibility
5781 // takes priority over sign incompatibility because the sign
5782 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005783 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005784 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005785
John McCalle4be87e2011-01-31 23:13:11 +00005786 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005787 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005788
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005789 // If we are a multi-level pointer, it's possible that our issue is simply
5790 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5791 // the eventual target type is the same and the pointers have the same
5792 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005793 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005794 do {
John McCall86c05f32011-02-01 00:10:29 +00005795 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5796 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005797 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005798
John McCall86c05f32011-02-01 00:10:29 +00005799 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005800 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005801 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005802
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005803 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005804 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005805 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005806 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005807 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5808 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005809 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005810}
5811
John McCalle4be87e2011-01-31 23:13:11 +00005812/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005813/// block pointer types are compatible or whether a block and normal pointer
5814/// are compatible. It is more restrict than comparing two function pointer
5815// types.
John McCalle4be87e2011-01-31 23:13:11 +00005816static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005817checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5818 QualType RHSType) {
5819 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5820 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005821
Steve Naroff1c7d0672008-09-04 15:10:53 +00005822 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005823
Steve Naroff1c7d0672008-09-04 15:10:53 +00005824 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005825 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5826 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005827
John McCalle4be87e2011-01-31 23:13:11 +00005828 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005829 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005830 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005831
John McCalle4be87e2011-01-31 23:13:11 +00005832 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005833
Steve Naroff1c7d0672008-09-04 15:10:53 +00005834 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005835 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5836 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005837
Richard Trieu1da27a12011-09-06 20:21:22 +00005838 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005839 return Sema::IncompatibleBlockPointer;
5840
Steve Naroff1c7d0672008-09-04 15:10:53 +00005841 return ConvTy;
5842}
5843
John McCalle4be87e2011-01-31 23:13:11 +00005844/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005845/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005846static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005847checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5848 QualType RHSType) {
5849 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5850 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005851
Richard Trieu1da27a12011-09-06 20:21:22 +00005852 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005853 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005854 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5855 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005856 return Sema::IncompatiblePointer;
5857 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005858 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005859 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005860 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5861 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005862 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005863 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005864 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005865 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5866 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005867
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005868 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5869 // make an exception for id<P>
5870 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005871 return Sema::CompatiblePointerDiscardsQualifiers;
5872
Richard Trieu1da27a12011-09-06 20:21:22 +00005873 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005874 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005875 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005876 return Sema::IncompatibleObjCQualifiedId;
5877 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005878}
5879
John McCall1c23e912010-11-16 02:32:08 +00005880Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005881Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005882 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005883 // Fake up an opaque expression. We don't actually care about what
5884 // cast operations are required, so if CheckAssignmentConstraints
5885 // adds casts to this they'll be wasted, but fortunately that doesn't
5886 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005887 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5888 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005889 CastKind K = CK_Invalid;
5890
Richard Trieu1da27a12011-09-06 20:21:22 +00005891 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005892}
5893
Mike Stumpeed9cac2009-02-19 03:04:26 +00005894/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5895/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005896/// pointers. Here are some objectionable examples that GCC considers warnings:
5897///
5898/// int a, *pint;
5899/// short *pshort;
5900/// struct foo *pfoo;
5901///
5902/// pint = pshort; // warning: assignment from incompatible pointer type
5903/// a = pint; // warning: assignment makes integer from pointer without a cast
5904/// pint = a; // warning: assignment makes pointer from integer without a cast
5905/// pint = pfoo; // warning: assignment from incompatible pointer type
5906///
5907/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005908/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005909///
John McCalldaa8e4e2010-11-15 09:13:47 +00005910/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005911Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005912Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005913 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005914 QualType RHSType = RHS.get()->getType();
5915 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005916
Chris Lattnerfc144e22008-01-04 23:18:45 +00005917 // Get canonical types. We're not formatting these types, just comparing
5918 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005919 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5920 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005921
John McCallb6cfa242011-01-31 22:28:28 +00005922 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005923 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005924 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005925 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005926 }
5927
Eli Friedman860a3192012-06-16 02:19:17 +00005928 // If we have an atomic type, try a non-atomic assignment, then just add an
5929 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005930 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005931 Sema::AssignConvertType result =
5932 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5933 if (result != Compatible)
5934 return result;
5935 if (Kind != CK_NoOp)
5936 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5937 Kind = CK_NonAtomicToAtomic;
5938 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005939 }
5940
Douglas Gregor9d293df2008-10-28 00:22:11 +00005941 // If the left-hand side is a reference type, then we are in a
5942 // (rare!) case where we've allowed the use of references in C,
5943 // e.g., as a parameter type in a built-in function. In this case,
5944 // just make sure that the type referenced is compatible with the
5945 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005946 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005947 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005948 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5949 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005950 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005951 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005952 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005953 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005954 }
John McCallb6cfa242011-01-31 22:28:28 +00005955
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005956 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5957 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005958 if (LHSType->isExtVectorType()) {
5959 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005960 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005961 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005962 // CK_VectorSplat does T -> vector T, so first cast to the
5963 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005964 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5965 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005966 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005967 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005968 }
5969 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005970 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005971 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
John McCallb6cfa242011-01-31 22:28:28 +00005974 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005975 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5976 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005977 // Allow assignments of an AltiVec vector type to an equivalent GCC
5978 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005979 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005980 Kind = CK_BitCast;
5981 return Compatible;
5982 }
5983
Douglas Gregor255210e2010-08-06 10:14:59 +00005984 // If we are allowing lax vector conversions, and LHS and RHS are both
5985 // vectors, the total size only needs to be the same. This is a bitcast;
5986 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005987 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005988 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005989 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005990 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005991 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005992 }
5993 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005994 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005995
John McCallb6cfa242011-01-31 22:28:28 +00005996 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005997 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005998 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005999 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006000 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006001 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006002
John McCallb6cfa242011-01-31 22:28:28 +00006003 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006004 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006005 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00006006 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006007 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00006008 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006009 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006010
John McCallb6cfa242011-01-31 22:28:28 +00006011 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00006012 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006013 Kind = CK_IntegralToPointer; // FIXME: null?
6014 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006015 }
John McCallb6cfa242011-01-31 22:28:28 +00006016
6017 // C pointers are not compatible with ObjC object pointers,
6018 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00006019 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006020 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00006021 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006022 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00006023 return Compatible;
6024 }
6025
6026 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00006027 if (RHSType->isObjCClassType() &&
6028 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006029 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006030 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006031 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006032 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00006033
John McCallb6cfa242011-01-31 22:28:28 +00006034 Kind = CK_BitCast;
6035 return IncompatiblePointer;
6036 }
6037
6038 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00006039 if (RHSType->getAs<BlockPointerType>()) {
6040 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006041 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006042 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006043 }
Steve Naroffb4406862008-09-29 18:10:17 +00006044 }
John McCallb6cfa242011-01-31 22:28:28 +00006045
Steve Naroff1c7d0672008-09-04 15:10:53 +00006046 return Incompatible;
6047 }
6048
John McCallb6cfa242011-01-31 22:28:28 +00006049 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006050 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006051 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006052 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006053 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00006054 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00006055 }
6056
6057 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006058 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006059 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006060 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006061 }
6062
John McCallb6cfa242011-01-31 22:28:28 +00006063 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00006064 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006065 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006066 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006067 }
Steve Naroffb4406862008-09-29 18:10:17 +00006068
John McCallb6cfa242011-01-31 22:28:28 +00006069 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006070 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006071 if (RHSPT->getPointeeType()->isVoidType()) {
6072 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006073 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006074 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006075
Chris Lattnerfc144e22008-01-04 23:18:45 +00006076 return Incompatible;
6077 }
6078
John McCallb6cfa242011-01-31 22:28:28 +00006079 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006080 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006081 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00006082 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006083 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006084 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00006085 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00006086 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006087 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00006088 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006089 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006090 return result;
John McCallb6cfa242011-01-31 22:28:28 +00006091 }
6092
6093 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00006094 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006095 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006096 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006097 }
6098
John McCallb6cfa242011-01-31 22:28:28 +00006099 // In general, C pointers are not compatible with ObjC object pointers,
6100 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00006101 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00006102 Kind = CK_CPointerToObjCPointerCast;
6103
John McCallb6cfa242011-01-31 22:28:28 +00006104 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00006105 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006106 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006107 }
6108
6109 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00006110 if (LHSType->isObjCClassType() &&
6111 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006112 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00006113 return Compatible;
6114 }
6115
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006116 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006117 }
John McCallb6cfa242011-01-31 22:28:28 +00006118
6119 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00006120 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00006121 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00006122 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006123 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006124 }
6125
Steve Naroff14108da2009-07-10 23:34:53 +00006126 return Incompatible;
6127 }
John McCallb6cfa242011-01-31 22:28:28 +00006128
6129 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00006130 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006131 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00006132 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006133 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006134 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006135 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006136
John McCallb6cfa242011-01-31 22:28:28 +00006137 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00006138 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006139 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006140 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006141 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006142
Chris Lattnerfc144e22008-01-04 23:18:45 +00006143 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006144 }
John McCallb6cfa242011-01-31 22:28:28 +00006145
6146 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00006147 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006148 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00006149 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006150 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006151 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006152 }
Steve Naroff14108da2009-07-10 23:34:53 +00006153
John McCallb6cfa242011-01-31 22:28:28 +00006154 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00006155 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006156 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006157 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006158 }
6159
Steve Naroff14108da2009-07-10 23:34:53 +00006160 return Incompatible;
6161 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006162
John McCallb6cfa242011-01-31 22:28:28 +00006163 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00006164 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6165 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006166 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006167 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006168 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006169 }
John McCallb6cfa242011-01-31 22:28:28 +00006170
Reid Spencer5f016e22007-07-11 17:01:13 +00006171 return Incompatible;
6172}
6173
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006174/// \brief Constructs a transparent union from an expression that is
6175/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00006176static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6177 ExprResult &EResult, QualType UnionType,
6178 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006179 // Build an initializer list that designates the appropriate member
6180 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006181 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006182 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00006183 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006184 Initializer->setType(UnionType);
6185 Initializer->setInitializedFieldInUnion(Field);
6186
6187 // Build a compound literal constructing a value of the transparent
6188 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006189 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006190 EResult = S.Owned(
6191 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6192 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006193}
6194
6195Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00006196Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00006197 ExprResult &RHS) {
6198 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006199
Mike Stump1eb44332009-09-09 15:08:12 +00006200 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006201 // transparent_union GCC extension.
6202 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006203 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006204 return Incompatible;
6205
6206 // The field to initialize within the transparent union.
6207 RecordDecl *UD = UT->getDecl();
6208 FieldDecl *InitField = 0;
6209 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006210 for (RecordDecl::field_iterator it = UD->field_begin(),
6211 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006212 it != itend; ++it) {
6213 if (it->getType()->isPointerType()) {
6214 // If the transparent union contains a pointer type, we allow:
6215 // 1) void pointer
6216 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00006217 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00006218 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00006219 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00006220 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006221 break;
6222 }
Mike Stump1eb44332009-09-09 15:08:12 +00006223
Richard Trieuf7720da2011-09-06 20:40:12 +00006224 if (RHS.get()->isNullPointerConstant(Context,
6225 Expr::NPC_ValueDependentIsNull)) {
6226 RHS = ImpCastExprToType(RHS.take(), it->getType(),
6227 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00006228 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006229 break;
6230 }
6231 }
6232
John McCalldaa8e4e2010-11-15 09:13:47 +00006233 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00006234 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006235 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00006236 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00006237 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006238 break;
6239 }
6240 }
6241
6242 if (!InitField)
6243 return Incompatible;
6244
Richard Trieuf7720da2011-09-06 20:40:12 +00006245 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006246 return Compatible;
6247}
6248
Chris Lattner5cf216b2008-01-04 18:04:52 +00006249Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00006250Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6251 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006252 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00006253 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006254 // C++ 5.17p3: If the left operand is not of class type, the
6255 // expression is implicitly converted (C++ 4) to the
6256 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00006257 ExprResult Res;
6258 if (Diagnose) {
6259 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6260 AA_Assigning);
6261 } else {
6262 ImplicitConversionSequence ICS =
6263 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6264 /*SuppressUserConversions=*/false,
6265 /*AllowExplicit=*/false,
6266 /*InOverloadResolution=*/false,
6267 /*CStyle=*/false,
6268 /*AllowObjCWritebackConversion=*/false);
6269 if (ICS.isFailure())
6270 return Incompatible;
6271 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6272 ICS, AA_Assigning);
6273 }
John Wiegley429bb272011-04-08 18:41:53 +00006274 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006275 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006276 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00006277 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00006278 !CheckObjCARCUnavailableWeakConversion(LHSType,
6279 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006280 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006281 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006282 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006283 }
6284
6285 // FIXME: Currently, we fall through and treat C++ classes like C
6286 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00006287 // FIXME: We also fall through for atomics; not sure what should
6288 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00006289 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006290
Steve Naroff529a4ad2007-11-27 17:58:44 +00006291 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6292 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00006293 if ((LHSType->isPointerType() ||
6294 LHSType->isObjCObjectPointerType() ||
6295 LHSType->isBlockPointerType())
6296 && RHS.get()->isNullPointerConstant(Context,
6297 Expr::NPC_ValueDependentIsNull)) {
6298 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006299 return Compatible;
6300 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006301
Chris Lattner943140e2007-10-16 02:55:40 +00006302 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006303 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006304 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006305 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006306 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006307 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006308 if (!LHSType->isReferenceType()) {
6309 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6310 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006311 return Incompatible;
6312 }
Steve Narofff1120de2007-08-24 22:33:52 +00006313
John McCalldaa8e4e2010-11-15 09:13:47 +00006314 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006315 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006316 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006317
Steve Narofff1120de2007-08-24 22:33:52 +00006318 // C99 6.5.16.1p2: The value of the right operand is converted to the
6319 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006320 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6321 // so that we can use references in built-in functions even in C.
6322 // The getNonReferenceType() call makes sure that the resulting expression
6323 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006324 if (result != Incompatible && RHS.get()->getType() != LHSType)
6325 RHS = ImpCastExprToType(RHS.take(),
6326 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006327 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006328}
6329
Richard Trieuf7720da2011-09-06 20:40:12 +00006330QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6331 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006332 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006333 << LHS.get()->getType() << RHS.get()->getType()
6334 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006335 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006336}
6337
Richard Trieu08062aa2011-09-06 21:01:04 +00006338QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006339 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006340 if (!IsCompAssign) {
6341 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6342 if (LHS.isInvalid())
6343 return QualType();
6344 }
6345 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6346 if (RHS.isInvalid())
6347 return QualType();
6348
Mike Stumpeed9cac2009-02-19 03:04:26 +00006349 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006350 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006351 QualType LHSType =
6352 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6353 QualType RHSType =
6354 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006355
Nate Begemanbe2341d2008-07-14 18:02:46 +00006356 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006357 if (LHSType == RHSType)
6358 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006359
Douglas Gregor255210e2010-08-06 10:14:59 +00006360 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006361 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6362 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6363 if (LHSType->isExtVectorType()) {
6364 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6365 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006366 }
6367
Richard Trieuccd891a2011-09-09 01:45:06 +00006368 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006369 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6370 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006371 }
6372
David Blaikie4e4d0842012-03-11 07:00:24 +00006373 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006374 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006375 // If we are allowing lax vector conversions, and LHS and RHS are both
6376 // vectors, the total size only needs to be the same. This is a
6377 // bitcast; no bits are changed but the result type is different.
6378 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006379 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6380 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006381 }
6382
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006383 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6384 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6385 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006386 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006387 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006388 std::swap(RHS, LHS);
6389 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006390 }
Mike Stump1eb44332009-09-09 15:08:12 +00006391
Nate Begemandde25982009-06-28 19:12:57 +00006392 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006393 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006394 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006395 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6396 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006397 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006398 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006399 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006400 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6401 if (swapped) std::swap(RHS, LHS);
6402 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006403 }
6404 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006405 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6406 RHSType->isRealFloatingType()) {
6407 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006408 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006409 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006410 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006411 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6412 if (swapped) std::swap(RHS, LHS);
6413 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006414 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006415 }
6416 }
Mike Stump1eb44332009-09-09 15:08:12 +00006417
Nate Begemandde25982009-06-28 19:12:57 +00006418 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006419 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006420 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006421 << LHS.get()->getType() << RHS.get()->getType()
6422 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006423 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006424}
6425
Richard Trieu481037f2011-09-16 00:53:10 +00006426// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6427// expression. These are mainly cases where the null pointer is used as an
6428// integer instead of a pointer.
6429static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6430 SourceLocation Loc, bool IsCompare) {
6431 // The canonical way to check for a GNU null is with isNullPointerConstant,
6432 // but we use a bit of a hack here for speed; this is a relatively
6433 // hot path, and isNullPointerConstant is slow.
6434 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6435 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6436
6437 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6438
6439 // Avoid analyzing cases where the result will either be invalid (and
6440 // diagnosed as such) or entirely valid and not something to warn about.
6441 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6442 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6443 return;
6444
6445 // Comparison operations would not make sense with a null pointer no matter
6446 // what the other expression is.
6447 if (!IsCompare) {
6448 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6449 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6450 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6451 return;
6452 }
6453
6454 // The rest of the operations only make sense with a null pointer
6455 // if the other expression is a pointer.
6456 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6457 NonNullType->canDecayToPointerType())
6458 return;
6459
6460 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6461 << LHSNull /* LHS is NULL */ << NonNullType
6462 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6463}
6464
Richard Trieu08062aa2011-09-06 21:01:04 +00006465QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006466 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006467 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006468 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6469
Richard Trieu08062aa2011-09-06 21:01:04 +00006470 if (LHS.get()->getType()->isVectorType() ||
6471 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006472 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006473
Richard Trieuccd891a2011-09-09 01:45:06 +00006474 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006475 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006476 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006477
David Chisnall7a7ee302012-01-16 17:27:18 +00006478
Eli Friedman860a3192012-06-16 02:19:17 +00006479 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006480 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006481
Chris Lattner7ef655a2010-01-12 21:23:57 +00006482 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006483 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006484 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006485 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006486 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6487 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006488
Chris Lattner7ef655a2010-01-12 21:23:57 +00006489 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006490}
6491
Chris Lattner7ef655a2010-01-12 21:23:57 +00006492QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006493 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006494 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6495
Richard Trieu08062aa2011-09-06 21:01:04 +00006496 if (LHS.get()->getType()->isVectorType() ||
6497 RHS.get()->getType()->isVectorType()) {
6498 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6499 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006500 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006501 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006502 }
Steve Naroff90045e82007-07-13 23:32:42 +00006503
Richard Trieuccd891a2011-09-09 01:45:06 +00006504 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006505 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006506 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006507
Eli Friedman860a3192012-06-16 02:19:17 +00006508 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006509 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006510
Chris Lattner7ef655a2010-01-12 21:23:57 +00006511 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006512 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006513 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006514 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6515 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006516
Chris Lattner7ef655a2010-01-12 21:23:57 +00006517 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006518}
6519
Chandler Carruth13b21be2011-06-27 08:02:19 +00006520/// \brief Diagnose invalid arithmetic on two void pointers.
6521static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006522 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006523 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006524 ? diag::err_typecheck_pointer_arith_void_type
6525 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006526 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6527 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006528}
6529
6530/// \brief Diagnose invalid arithmetic on a void pointer.
6531static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6532 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006533 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006534 ? diag::err_typecheck_pointer_arith_void_type
6535 : diag::ext_gnu_void_ptr)
6536 << 0 /* one pointer */ << Pointer->getSourceRange();
6537}
6538
6539/// \brief Diagnose invalid arithmetic on two function pointers.
6540static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6541 Expr *LHS, Expr *RHS) {
6542 assert(LHS->getType()->isAnyPointerType());
6543 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006544 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006545 ? diag::err_typecheck_pointer_arith_function_type
6546 : diag::ext_gnu_ptr_func_arith)
6547 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6548 // We only show the second type if it differs from the first.
6549 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6550 RHS->getType())
6551 << RHS->getType()->getPointeeType()
6552 << LHS->getSourceRange() << RHS->getSourceRange();
6553}
6554
6555/// \brief Diagnose invalid arithmetic on a function pointer.
6556static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6557 Expr *Pointer) {
6558 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006559 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006560 ? diag::err_typecheck_pointer_arith_function_type
6561 : diag::ext_gnu_ptr_func_arith)
6562 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6563 << 0 /* one pointer, so only one type */
6564 << Pointer->getSourceRange();
6565}
6566
Richard Trieud9f19342011-09-12 18:08:02 +00006567/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006568///
6569/// \returns True if pointer has incomplete type
6570static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6571 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006572 assert(Operand->getType()->isAnyPointerType() &&
6573 !Operand->getType()->isDependentType());
6574 QualType PointeeTy = Operand->getType()->getPointeeType();
6575 return S.RequireCompleteType(Loc, PointeeTy,
6576 diag::err_typecheck_arithmetic_incomplete_type,
6577 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006578}
6579
Chandler Carruth13b21be2011-06-27 08:02:19 +00006580/// \brief Check the validity of an arithmetic pointer operand.
6581///
6582/// If the operand has pointer type, this code will check for pointer types
6583/// which are invalid in arithmetic operations. These will be diagnosed
6584/// appropriately, including whether or not the use is supported as an
6585/// extension.
6586///
6587/// \returns True when the operand is valid to use (even if as an extension).
6588static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6589 Expr *Operand) {
6590 if (!Operand->getType()->isAnyPointerType()) return true;
6591
6592 QualType PointeeTy = Operand->getType()->getPointeeType();
6593 if (PointeeTy->isVoidType()) {
6594 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006595 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006596 }
6597 if (PointeeTy->isFunctionType()) {
6598 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006599 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006600 }
6601
Richard Trieu097ecd22011-09-02 02:15:37 +00006602 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006603
6604 return true;
6605}
6606
6607/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6608/// operands.
6609///
6610/// This routine will diagnose any invalid arithmetic on pointer operands much
6611/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6612/// for emitting a single diagnostic even for operations where both LHS and RHS
6613/// are (potentially problematic) pointers.
6614///
6615/// \returns True when the operand is valid to use (even if as an extension).
6616static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006617 Expr *LHSExpr, Expr *RHSExpr) {
6618 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6619 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006620 if (!isLHSPointer && !isRHSPointer) return true;
6621
6622 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006623 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6624 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006625
6626 // Check for arithmetic on pointers to incomplete types.
6627 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6628 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6629 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006630 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6631 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6632 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006633
David Blaikie4e4d0842012-03-11 07:00:24 +00006634 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006635 }
6636
6637 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6638 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6639 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006640 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6641 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6642 RHSExpr);
6643 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006644
David Blaikie4e4d0842012-03-11 07:00:24 +00006645 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006646 }
6647
John McCall1503f0d2012-07-31 05:14:30 +00006648 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6649 return false;
6650 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6651 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006652
Chandler Carruth13b21be2011-06-27 08:02:19 +00006653 return true;
6654}
6655
Nico Weber1cb2d742012-03-02 22:01:22 +00006656/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6657/// literal.
6658static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6659 Expr *LHSExpr, Expr *RHSExpr) {
6660 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6661 Expr* IndexExpr = RHSExpr;
6662 if (!StrExpr) {
6663 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6664 IndexExpr = LHSExpr;
6665 }
6666
6667 bool IsStringPlusInt = StrExpr &&
6668 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6669 if (!IsStringPlusInt)
6670 return;
6671
6672 llvm::APSInt index;
6673 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6674 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6675 if (index.isNonNegative() &&
6676 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6677 index.isUnsigned()))
6678 return;
6679 }
6680
6681 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6682 Self.Diag(OpLoc, diag::warn_string_plus_int)
6683 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6684
6685 // Only print a fixit for "str" + int, not for int + "str".
6686 if (IndexExpr == RHSExpr) {
6687 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6688 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6689 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6690 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6691 << FixItHint::CreateInsertion(EndLoc, "]");
6692 } else
6693 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6694}
6695
Richard Trieud9f19342011-09-12 18:08:02 +00006696/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006697static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006698 Expr *LHSExpr, Expr *RHSExpr) {
6699 assert(LHSExpr->getType()->isAnyPointerType());
6700 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006701 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006702 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6703 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006704}
6705
Chris Lattner7ef655a2010-01-12 21:23:57 +00006706QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006707 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6708 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006709 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6710
Richard Trieudef75842011-09-06 21:13:51 +00006711 if (LHS.get()->getType()->isVectorType() ||
6712 RHS.get()->getType()->isVectorType()) {
6713 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006714 if (CompLHSTy) *CompLHSTy = compType;
6715 return compType;
6716 }
Steve Naroff49b45262007-07-13 16:58:59 +00006717
Richard Trieudef75842011-09-06 21:13:51 +00006718 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6719 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006720 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006721
Nico Weber1cb2d742012-03-02 22:01:22 +00006722 // Diagnose "string literal" '+' int.
6723 if (Opc == BO_Add)
6724 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6725
Reid Spencer5f016e22007-07-11 17:01:13 +00006726 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006727 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006728 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006729 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006730 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006731
John McCall1503f0d2012-07-31 05:14:30 +00006732 // Type-checking. Ultimately the pointer's going to be in PExp;
6733 // note that we bias towards the LHS being the pointer.
6734 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006735
John McCall1503f0d2012-07-31 05:14:30 +00006736 bool isObjCPointer;
6737 if (PExp->getType()->isPointerType()) {
6738 isObjCPointer = false;
6739 } else if (PExp->getType()->isObjCObjectPointerType()) {
6740 isObjCPointer = true;
6741 } else {
6742 std::swap(PExp, IExp);
6743 if (PExp->getType()->isPointerType()) {
6744 isObjCPointer = false;
6745 } else if (PExp->getType()->isObjCObjectPointerType()) {
6746 isObjCPointer = true;
6747 } else {
6748 return InvalidOperands(Loc, LHS, RHS);
6749 }
6750 }
6751 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006752
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006753 if (!IExp->getType()->isIntegerType())
6754 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006755
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006756 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6757 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006758
John McCall1503f0d2012-07-31 05:14:30 +00006759 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006760 return QualType();
6761
6762 // Check array bounds for pointer arithemtic
6763 CheckArrayAccess(PExp, IExp);
6764
6765 if (CompLHSTy) {
6766 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6767 if (LHSTy.isNull()) {
6768 LHSTy = LHS.get()->getType();
6769 if (LHSTy->isPromotableIntegerType())
6770 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006771 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006772 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006773 }
6774
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006775 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006776}
6777
Chris Lattnereca7be62008-04-07 05:30:13 +00006778// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006779QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006780 SourceLocation Loc,
6781 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006782 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6783
Richard Trieudef75842011-09-06 21:13:51 +00006784 if (LHS.get()->getType()->isVectorType() ||
6785 RHS.get()->getType()->isVectorType()) {
6786 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006787 if (CompLHSTy) *CompLHSTy = compType;
6788 return compType;
6789 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006790
Richard Trieudef75842011-09-06 21:13:51 +00006791 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6792 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006793 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006794
Chris Lattner6e4ab612007-12-09 21:53:25 +00006795 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006796
Chris Lattner6e4ab612007-12-09 21:53:25 +00006797 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006798 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006799 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006800 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006801 }
Mike Stump1eb44332009-09-09 15:08:12 +00006802
Chris Lattner6e4ab612007-12-09 21:53:25 +00006803 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006804 if (LHS.get()->getType()->isAnyPointerType()) {
6805 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006806
Chris Lattnerb5f15622009-04-24 23:50:08 +00006807 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006808 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6809 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006810 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006811
Chris Lattner6e4ab612007-12-09 21:53:25 +00006812 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006813 if (RHS.get()->getType()->isIntegerType()) {
6814 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006815 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006816
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006817 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006818 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6819 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006820
Richard Trieudef75842011-09-06 21:13:51 +00006821 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6822 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006823 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006824
Chris Lattner6e4ab612007-12-09 21:53:25 +00006825 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006826 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006827 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006828 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006829
David Blaikie4e4d0842012-03-11 07:00:24 +00006830 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006831 // Pointee types must be the same: C++ [expr.add]
6832 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006833 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006834 }
6835 } else {
6836 // Pointee types must be compatible C99 6.5.6p3
6837 if (!Context.typesAreCompatible(
6838 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6839 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006840 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006841 return QualType();
6842 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006843 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006844
Chandler Carruth13b21be2011-06-27 08:02:19 +00006845 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006846 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006847 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006848
Richard Trieudef75842011-09-06 21:13:51 +00006849 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006850 return Context.getPointerDiffType();
6851 }
6852 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006853
Richard Trieudef75842011-09-06 21:13:51 +00006854 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006855}
6856
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006857static bool isScopedEnumerationType(QualType T) {
6858 if (const EnumType *ET = dyn_cast<EnumType>(T))
6859 return ET->getDecl()->isScoped();
6860 return false;
6861}
6862
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006863static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006864 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006865 QualType LHSType) {
David Tweed7a834212013-01-07 16:43:27 +00006866 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6867 // so skip remaining warnings as we don't want to modify values within Sema.
6868 if (S.getLangOpts().OpenCL)
6869 return;
6870
Chandler Carruth21206d52011-02-23 23:34:11 +00006871 llvm::APSInt Right;
6872 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006873 if (RHS.get()->isValueDependent() ||
6874 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006875 return;
6876
6877 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006878 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006879 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006880 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006881 return;
6882 }
6883 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006884 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006885 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006886 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006887 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006888 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006889 return;
6890 }
6891 if (Opc != BO_Shl)
6892 return;
6893
6894 // When left shifting an ICE which is signed, we can check for overflow which
6895 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6896 // integers have defined behavior modulo one more than the maximum value
6897 // representable in the result type, so never warn for those.
6898 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006899 if (LHS.get()->isValueDependent() ||
6900 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6901 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006902 return;
6903 llvm::APInt ResultBits =
6904 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6905 if (LeftBits.uge(ResultBits))
6906 return;
6907 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6908 Result = Result.shl(Right);
6909
Ted Kremenekfa821382011-06-15 00:54:52 +00006910 // Print the bit representation of the signed integer as an unsigned
6911 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006912 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006913 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6914
Chandler Carruth21206d52011-02-23 23:34:11 +00006915 // If we are only missing a sign bit, this is less likely to result in actual
6916 // bugs -- if the result is cast back to an unsigned type, it will have the
6917 // expected value. Thus we place this behind a different warning that can be
6918 // turned off separately if needed.
6919 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006920 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006921 << HexResult.str() << LHSType
6922 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006923 return;
6924 }
6925
6926 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006927 << HexResult.str() << Result.getMinSignedBits() << LHSType
6928 << Left.getBitWidth() << LHS.get()->getSourceRange()
6929 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006930}
6931
Chris Lattnereca7be62008-04-07 05:30:13 +00006932// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006933QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006934 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006935 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006936 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6937
Nate Begeman2207d792009-10-25 02:26:48 +00006938 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006939 if (LHS.get()->getType()->isVectorType() ||
6940 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006941 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006942
Chris Lattnerca5eede2007-12-12 05:47:28 +00006943 // Shifts don't perform usual arithmetic conversions, they just do integer
6944 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006945
John McCall1bc80af2010-12-16 19:28:59 +00006946 // For the LHS, do usual unary conversions, but then reset them away
6947 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006948 ExprResult OldLHS = LHS;
6949 LHS = UsualUnaryConversions(LHS.take());
6950 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006951 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006952 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006953 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006954
6955 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006956 RHS = UsualUnaryConversions(RHS.take());
6957 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006958 return QualType();
Douglas Gregor236d9d162013-04-16 15:41:08 +00006959 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006960
Douglas Gregor236d9d162013-04-16 15:41:08 +00006961 // C99 6.5.7p2: Each of the operands shall have integer type.
6962 if (!LHSType->hasIntegerRepresentation() ||
6963 !RHSType->hasIntegerRepresentation())
6964 return InvalidOperands(Loc, LHS, RHS);
6965
6966 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6967 // hasIntegerRepresentation() above instead of this.
6968 if (isScopedEnumerationType(LHSType) ||
6969 isScopedEnumerationType(RHSType)) {
6970 return InvalidOperands(Loc, LHS, RHS);
6971 }
Ryan Flynnd0439682009-08-07 16:20:20 +00006972 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006973 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006974
Chris Lattnerca5eede2007-12-12 05:47:28 +00006975 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006976 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006977}
6978
Chandler Carruth99919472010-07-10 12:30:03 +00006979static bool IsWithinTemplateSpecialization(Decl *D) {
6980 if (DeclContext *DC = D->getDeclContext()) {
6981 if (isa<ClassTemplateSpecializationDecl>(DC))
6982 return true;
6983 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6984 return FD->isFunctionTemplateSpecialization();
6985 }
6986 return false;
6987}
6988
Richard Trieue648ac32011-09-02 03:48:46 +00006989/// If two different enums are compared, raise a warning.
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00006990static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6991 Expr *RHS) {
6992 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6993 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006994
6995 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6996 if (!LHSEnumType)
6997 return;
6998 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6999 if (!RHSEnumType)
7000 return;
7001
7002 // Ignore anonymous enums.
7003 if (!LHSEnumType->getDecl()->getIdentifier())
7004 return;
7005 if (!RHSEnumType->getDecl()->getIdentifier())
7006 return;
7007
7008 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7009 return;
7010
7011 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7012 << LHSStrippedType << RHSStrippedType
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00007013 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00007014}
7015
Richard Trieu7be1be02011-09-02 02:55:45 +00007016/// \brief Diagnose bad pointer comparisons.
7017static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00007018 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00007019 bool IsError) {
7020 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00007021 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00007022 << LHS.get()->getType() << RHS.get()->getType()
7023 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00007024}
7025
7026/// \brief Returns false if the pointers are converted to a composite type,
7027/// true otherwise.
7028static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00007029 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007030 // C++ [expr.rel]p2:
7031 // [...] Pointer conversions (4.10) and qualification
7032 // conversions (4.4) are performed on pointer operands (or on
7033 // a pointer operand and a null pointer constant) to bring
7034 // them to their composite pointer type. [...]
7035 //
7036 // C++ [expr.eq]p1 uses the same notion for (in)equality
7037 // comparisons of pointers.
7038
7039 // C++ [expr.eq]p2:
7040 // In addition, pointers to members can be compared, or a pointer to
7041 // member and a null pointer constant. Pointer to member conversions
7042 // (4.11) and qualification conversions (4.4) are performed to bring
7043 // them to a common type. If one operand is a null pointer constant,
7044 // the common type is the type of the other operand. Otherwise, the
7045 // common type is a pointer to member type similar (4.4) to the type
7046 // of one of the operands, with a cv-qualification signature (4.4)
7047 // that is the union of the cv-qualification signatures of the operand
7048 // types.
7049
Richard Trieuba261492011-09-06 21:27:33 +00007050 QualType LHSType = LHS.get()->getType();
7051 QualType RHSType = RHS.get()->getType();
7052 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7053 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00007054
7055 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00007056 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00007057 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00007058 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00007059 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00007060 return true;
7061 }
7062
7063 if (NonStandardCompositeType)
7064 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00007065 << LHSType << RHSType << T << LHS.get()->getSourceRange()
7066 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00007067
Richard Trieuba261492011-09-06 21:27:33 +00007068 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7069 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00007070 return false;
7071}
7072
7073static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00007074 ExprResult &LHS,
7075 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00007076 bool IsError) {
7077 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7078 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00007079 << LHS.get()->getType() << RHS.get()->getType()
7080 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00007081}
7082
Jordan Rose9f63a452012-06-08 21:14:25 +00007083static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rose87da0b72012-11-09 23:55:21 +00007084 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rose9f63a452012-06-08 21:14:25 +00007085 case Stmt::ObjCArrayLiteralClass:
7086 case Stmt::ObjCDictionaryLiteralClass:
7087 case Stmt::ObjCStringLiteralClass:
7088 case Stmt::ObjCBoxedExprClass:
7089 return true;
7090 default:
7091 // Note that ObjCBoolLiteral is NOT an object literal!
7092 return false;
7093 }
7094}
7095
Jordan Rose8d872ca2012-07-17 17:46:40 +00007096static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer2e85e742013-02-15 15:17:50 +00007097 const ObjCObjectPointerType *Type =
7098 LHS->getType()->getAs<ObjCObjectPointerType>();
7099
7100 // If this is not actually an Objective-C object, bail out.
7101 if (!Type)
Jordan Rose8d872ca2012-07-17 17:46:40 +00007102 return false;
Benjamin Kramer2e85e742013-02-15 15:17:50 +00007103
7104 // Get the LHS object's interface type.
7105 QualType InterfaceType = Type->getPointeeType();
7106 if (const ObjCObjectType *iQFaceTy =
7107 InterfaceType->getAsObjCQualifiedInterfaceType())
7108 InterfaceType = iQFaceTy->getBaseType();
Jordan Rose8d872ca2012-07-17 17:46:40 +00007109
7110 // If the RHS isn't an Objective-C object, bail out.
7111 if (!RHS->getType()->isObjCObjectPointerType())
7112 return false;
7113
7114 // Try to find the -isEqual: method.
7115 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7116 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7117 InterfaceType,
7118 /*instance=*/true);
7119 if (!Method) {
7120 if (Type->isObjCIdType()) {
7121 // For 'id', just check the global pool.
7122 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7123 /*receiverId=*/true,
7124 /*warn=*/false);
7125 } else {
7126 // Check protocols.
Benjamin Kramer2e85e742013-02-15 15:17:50 +00007127 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose8d872ca2012-07-17 17:46:40 +00007128 /*instance=*/true);
7129 }
7130 }
7131
7132 if (!Method)
7133 return false;
7134
7135 QualType T = Method->param_begin()[0]->getType();
7136 if (!T->isObjCObjectPointerType())
7137 return false;
7138
7139 QualType R = Method->getResultType();
7140 if (!R->isScalarType())
7141 return false;
7142
7143 return true;
7144}
7145
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007146Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7147 FromE = FromE->IgnoreParenImpCasts();
7148 switch (FromE->getStmtClass()) {
7149 default:
7150 break;
7151 case Stmt::ObjCStringLiteralClass:
7152 // "string literal"
7153 return LK_String;
7154 case Stmt::ObjCArrayLiteralClass:
7155 // "array literal"
7156 return LK_Array;
7157 case Stmt::ObjCDictionaryLiteralClass:
7158 // "dictionary literal"
7159 return LK_Dictionary;
Ted Kremenekd3292c82012-12-21 22:46:35 +00007160 case Stmt::BlockExprClass:
7161 return LK_Block;
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007162 case Stmt::ObjCBoxedExprClass: {
Ted Kremenekf530ff72012-12-21 21:59:39 +00007163 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007164 switch (Inner->getStmtClass()) {
7165 case Stmt::IntegerLiteralClass:
7166 case Stmt::FloatingLiteralClass:
7167 case Stmt::CharacterLiteralClass:
7168 case Stmt::ObjCBoolLiteralExprClass:
7169 case Stmt::CXXBoolLiteralExprClass:
7170 // "numeric literal"
7171 return LK_Numeric;
7172 case Stmt::ImplicitCastExprClass: {
7173 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7174 // Boolean literals can be represented by implicit casts.
7175 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7176 return LK_Numeric;
7177 break;
7178 }
7179 default:
7180 break;
7181 }
7182 return LK_Boxed;
7183 }
7184 }
7185 return LK_None;
7186}
7187
Jordan Rose8d872ca2012-07-17 17:46:40 +00007188static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7189 ExprResult &LHS, ExprResult &RHS,
7190 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00007191 Expr *Literal;
7192 Expr *Other;
7193 if (isObjCObjectLiteral(LHS)) {
7194 Literal = LHS.get();
7195 Other = RHS.get();
7196 } else {
7197 Literal = RHS.get();
7198 Other = LHS.get();
7199 }
7200
7201 // Don't warn on comparisons against nil.
7202 Other = Other->IgnoreParenCasts();
7203 if (Other->isNullPointerConstant(S.getASTContext(),
7204 Expr::NPC_ValueDependentIsNotNull))
7205 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00007206
Jordan Roseeec207f2012-07-17 17:46:44 +00007207 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007208 // LK_String should always be after the other literals, since it has its own
7209 // warning flag.
7210 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenekd3292c82012-12-21 22:46:35 +00007211 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007212 if (LiteralKind == Sema::LK_None) {
Jordan Rose9f63a452012-06-08 21:14:25 +00007213 llvm_unreachable("Unknown Objective-C object literal kind");
7214 }
7215
Ted Kremenek3ee069b2012-12-21 21:59:36 +00007216 if (LiteralKind == Sema::LK_String)
Jordan Roseeec207f2012-07-17 17:46:44 +00007217 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7218 << Literal->getSourceRange();
7219 else
7220 S.Diag(Loc, diag::warn_objc_literal_comparison)
7221 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00007222
Jordan Rose8d872ca2012-07-17 17:46:40 +00007223 if (BinaryOperator::isEqualityOp(Opc) &&
7224 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7225 SourceLocation Start = LHS.get()->getLocStart();
7226 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00007227 CharSourceRange OpRange =
7228 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00007229
Jordan Rose8d872ca2012-07-17 17:46:40 +00007230 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7231 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00007232 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose8d872ca2012-07-17 17:46:40 +00007233 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00007234 }
Jordan Rose9f63a452012-06-08 21:14:25 +00007235}
7236
Douglas Gregor0c6db942009-05-04 06:07:12 +00007237// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00007238QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00007239 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007240 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00007241 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7242
John McCall2de56d12010-08-25 11:45:40 +00007243 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007244
Chris Lattner02dd4b12009-12-05 05:40:13 +00007245 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007246 if (LHS.get()->getType()->isVectorType() ||
7247 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00007248 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007249
Richard Trieuf1775fb2011-09-06 21:43:51 +00007250 QualType LHSType = LHS.get()->getType();
7251 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00007252
Richard Trieuf1775fb2011-09-06 21:43:51 +00007253 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7254 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007255
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00007256 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Chandler Carruth543cb652011-02-17 08:37:06 +00007257
Richard Trieuf1775fb2011-09-06 21:43:51 +00007258 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00007259 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007260 !LHS.get()->getLocStart().isMacroID() &&
7261 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007262 // For non-floating point types, check for self-comparisons of the form
7263 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7264 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007265 //
7266 // NOTE: Don't warn about comparison expressions resulting from macro
7267 // expansion. Also don't warn about comparisons which are only self
7268 // comparisons within a template specialization. The warnings should catch
7269 // obvious cases in the definition of the template anyways. The idea is to
7270 // warn when the typed comparison operator will always evaluate to the same
7271 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007272 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007273 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007274 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007275 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007276 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007277 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007278 << (Opc == BO_EQ
7279 || Opc == BO_LE
7280 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00007281 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00007282 !DRL->getDecl()->getType()->isReferenceType() &&
7283 !DRR->getDecl()->getType()->isReferenceType()) {
7284 // what is it always going to eval to?
7285 char always_evals_to;
7286 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007287 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007288 always_evals_to = 0; // false
7289 break;
John McCall2de56d12010-08-25 11:45:40 +00007290 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007291 always_evals_to = 1; // true
7292 break;
7293 default:
7294 // best we can say is 'a constant'
7295 always_evals_to = 2; // e.g. array1 <= array2
7296 break;
7297 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007298 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007299 << 1 // array
7300 << always_evals_to);
7301 }
7302 }
Chandler Carruth99919472010-07-10 12:30:03 +00007303 }
Mike Stump1eb44332009-09-09 15:08:12 +00007304
Chris Lattner55660a72009-03-08 19:39:53 +00007305 if (isa<CastExpr>(LHSStripped))
7306 LHSStripped = LHSStripped->IgnoreParenCasts();
7307 if (isa<CastExpr>(RHSStripped))
7308 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007309
Chris Lattner55660a72009-03-08 19:39:53 +00007310 // Warn about comparisons against a string constant (unless the other
7311 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007312 Expr *literalString = 0;
7313 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007314 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007315 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007316 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007317 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007318 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007319 } else if ((isa<StringLiteral>(RHSStripped) ||
7320 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007321 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007322 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007323 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007324 literalStringStripped = RHSStripped;
7325 }
7326
7327 if (literalString) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007328 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007329 PDiag(diag::warn_stringcompare)
7330 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007331 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007332 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007333 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007334
Douglas Gregord64fdd02010-06-08 19:50:34 +00007335 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007336 if (LHS.get()->getType()->isArithmeticType() &&
7337 RHS.get()->getType()->isArithmeticType()) {
7338 UsualArithmeticConversions(LHS, RHS);
7339 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007340 return QualType();
7341 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007342 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007343 LHS = UsualUnaryConversions(LHS.take());
7344 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007345 return QualType();
7346
Richard Trieuf1775fb2011-09-06 21:43:51 +00007347 RHS = UsualUnaryConversions(RHS.take());
7348 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007349 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007350 }
7351
Richard Trieuf1775fb2011-09-06 21:43:51 +00007352 LHSType = LHS.get()->getType();
7353 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007354
Douglas Gregor447b69e2008-11-19 03:25:36 +00007355 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007356 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007357
Richard Trieuccd891a2011-09-09 01:45:06 +00007358 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007359 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007360 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007361 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007362 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007363 if (LHSType->hasFloatingRepresentation())
7364 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007365
Richard Trieuf1775fb2011-09-06 21:43:51 +00007366 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007367 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007368 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007369
Richard Trieuf1775fb2011-09-06 21:43:51 +00007370 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007371 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007372 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007373 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007374
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007375 // All of the following pointer-related warnings are GCC extensions, except
7376 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007377 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007378 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007379 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007380 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007381 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007382
David Blaikie4e4d0842012-03-11 07:00:24 +00007383 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007384 if (LCanPointeeTy == RCanPointeeTy)
7385 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007386 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007387 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7388 // Valid unless comparison between non-null pointer and function pointer
7389 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007390 // In a SFINAE context, we treat this as a hard error to maintain
7391 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007392 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7393 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007394 diagnoseFunctionPointerToVoidComparison(
David Blaikie0adb1752013-02-21 06:05:05 +00007395 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007396
7397 if (isSFINAEContext())
7398 return QualType();
7399
Richard Trieuf1775fb2011-09-06 21:43:51 +00007400 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007401 return ResultTy;
7402 }
7403 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007404
Richard Trieuf1775fb2011-09-06 21:43:51 +00007405 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007406 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007407 else
7408 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007409 }
Eli Friedman3075e762009-08-23 00:27:47 +00007410 // C99 6.5.9p2 and C99 6.5.8p2
7411 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7412 RCanPointeeTy.getUnqualifiedType())) {
7413 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007414 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007415 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007416 << LHSType << RHSType << LHS.get()->getSourceRange()
7417 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007418 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007419 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007420 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7421 // Valid unless comparison between non-null pointer and function pointer
7422 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007423 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007424 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007425 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007426 } else {
7427 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007428 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007429 }
John McCall34d6f932011-03-11 04:25:25 +00007430 if (LCanPointeeTy != RCanPointeeTy) {
7431 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007432 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007433 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007434 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007435 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007436 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007437 }
Mike Stump1eb44332009-09-09 15:08:12 +00007438
David Blaikie4e4d0842012-03-11 07:00:24 +00007439 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007440 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007441 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007442 return ResultTy;
7443
Mike Stump1eb44332009-09-09 15:08:12 +00007444 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007445 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007446 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007447 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007448 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007449 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7450 RHS = ImpCastExprToType(RHS.take(), LHSType,
7451 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007452 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007453 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007454 return ResultTy;
7455 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007456 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007457 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007458 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007459 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7460 LHS = ImpCastExprToType(LHS.take(), RHSType,
7461 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007462 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007463 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007464 return ResultTy;
7465 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007466
7467 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007468 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007469 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7470 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007471 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007472 else
7473 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007474 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007475
7476 // Handle scoped enumeration types specifically, since they don't promote
7477 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007478 if (LHS.get()->getType()->isEnumeralType() &&
7479 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7480 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007481 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007482 }
Mike Stump1eb44332009-09-09 15:08:12 +00007483
Steve Naroff1c7d0672008-09-04 15:10:53 +00007484 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007485 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007486 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007487 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7488 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007489
Steve Naroff1c7d0672008-09-04 15:10:53 +00007490 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007491 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007492 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007493 << LHSType << RHSType << LHS.get()->getSourceRange()
7494 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007495 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007496 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007497 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007498 }
John Wiegley429bb272011-04-08 18:41:53 +00007499
Steve Naroff59f53942008-09-28 01:11:11 +00007500 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007501 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007502 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7503 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007504 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007505 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007506 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007507 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007508 ->getPointeeType()->isVoidType())))
7509 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007510 << LHSType << RHSType << LHS.get()->getSourceRange()
7511 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007512 }
John McCall34d6f932011-03-11 04:25:25 +00007513 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007514 LHS = ImpCastExprToType(LHS.take(), RHSType,
7515 RHSType->isPointerType() ? CK_BitCast
7516 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007517 else
John McCall1d9b3b22011-09-09 05:25:32 +00007518 RHS = ImpCastExprToType(RHS.take(), LHSType,
7519 LHSType->isPointerType() ? CK_BitCast
7520 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007521 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007522 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007523
Richard Trieuf1775fb2011-09-06 21:43:51 +00007524 if (LHSType->isObjCObjectPointerType() ||
7525 RHSType->isObjCObjectPointerType()) {
7526 const PointerType *LPT = LHSType->getAs<PointerType>();
7527 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007528 if (LPT || RPT) {
7529 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7530 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007531
Steve Naroffa8069f12008-11-17 19:49:16 +00007532 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007533 !Context.typesAreCompatible(LHSType, RHSType)) {
7534 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007535 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007536 }
John McCall34d6f932011-03-11 04:25:25 +00007537 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007538 LHS = ImpCastExprToType(LHS.take(), RHSType,
7539 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007540 else
John McCall1d9b3b22011-09-09 05:25:32 +00007541 RHS = ImpCastExprToType(RHS.take(), LHSType,
7542 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007543 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007544 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007545 if (LHSType->isObjCObjectPointerType() &&
7546 RHSType->isObjCObjectPointerType()) {
7547 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7548 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007549 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007550 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007551 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007552
John McCall34d6f932011-03-11 04:25:25 +00007553 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007554 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007555 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007556 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007557 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007558 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007559 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007560 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7561 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007562 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007563 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007564 if (LangOpts.DebuggerSupport) {
7565 // Under a debugger, allow the comparison of pointers to integers,
7566 // since users tend to want to compare addresses.
7567 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007568 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007569 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007570 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007571 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007572 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007573 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007574 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7575 isError = true;
7576 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007577 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007578
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007579 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007580 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007581 << LHSType << RHSType << LHS.get()->getSourceRange()
7582 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007583 if (isError)
7584 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007585 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007586
Richard Trieuf1775fb2011-09-06 21:43:51 +00007587 if (LHSType->isIntegerType())
7588 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007589 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007590 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007591 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007592 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007593 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007594 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007595
Steve Naroff39218df2008-09-04 16:56:14 +00007596 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007597 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007598 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7599 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007600 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007601 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007602 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007603 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7604 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007605 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007606 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007607
Richard Trieuf1775fb2011-09-06 21:43:51 +00007608 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007609}
7610
Tanya Lattner4f692c22012-01-16 21:02:28 +00007611
7612// Return a signed type that is of identical size and number of elements.
7613// For floating point vectors, return an integer type of identical size
7614// and number of elements.
7615QualType Sema::GetSignedVectorType(QualType V) {
7616 const VectorType *VTy = V->getAs<VectorType>();
7617 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7618 if (TypeSize == Context.getTypeSize(Context.CharTy))
7619 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7620 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7621 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7622 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7623 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7624 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7625 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7626 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7627 "Unhandled vector element size in vector compare");
7628 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7629}
7630
Nate Begemanbe2341d2008-07-14 18:02:46 +00007631/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007632/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007633/// like a scalar comparison, a vector comparison produces a vector of integer
7634/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007635QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007636 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007637 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007638 // Check to make sure we're operating on vectors of the same type and width,
7639 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007640 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007641 if (vType.isNull())
7642 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007643
Richard Trieu9f60dee2011-09-07 01:19:57 +00007644 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007645
Anton Yartsev7870b132011-03-27 15:36:07 +00007646 // If AltiVec, the comparison results in a numeric type, i.e.
7647 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007648 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007649 return Context.getLogicalOperationType();
7650
Nate Begemanbe2341d2008-07-14 18:02:46 +00007651 // For non-floating point types, check for self-comparisons of the form
7652 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7653 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007654 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007655 if (DeclRefExpr* DRL
7656 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7657 if (DeclRefExpr* DRR
7658 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007659 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007660 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007661 PDiag(diag::warn_comparison_always)
7662 << 0 // self-
7663 << 2 // "a constant"
7664 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007665 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007666
Nate Begemanbe2341d2008-07-14 18:02:46 +00007667 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007668 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007669 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007670 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007671 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007672
7673 // Return a signed type for the vector.
7674 return GetSignedVectorType(LHSType);
7675}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007676
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007677QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7678 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007679 // Ensure that either both operands are of the same vector type, or
7680 // one operand is of a vector type and the other is of its element type.
7681 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
Joey Gouly52e933b2013-02-21 11:49:56 +00007682 if (vType.isNull())
7683 return InvalidOperands(Loc, LHS, RHS);
7684 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7685 vType->hasFloatingRepresentation())
Tanya Lattner4f692c22012-01-16 21:02:28 +00007686 return InvalidOperands(Loc, LHS, RHS);
7687
7688 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007689}
7690
Reid Spencer5f016e22007-07-11 17:01:13 +00007691inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007692 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007693 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7694
Richard Trieu9f60dee2011-09-07 01:19:57 +00007695 if (LHS.get()->getType()->isVectorType() ||
7696 RHS.get()->getType()->isVectorType()) {
7697 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7698 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007699 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007700
Richard Trieu9f60dee2011-09-07 01:19:57 +00007701 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007702 }
Steve Naroff90045e82007-07-13 23:32:42 +00007703
Richard Trieu9f60dee2011-09-07 01:19:57 +00007704 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7705 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007706 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007707 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007708 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007709 LHS = LHSResult.take();
7710 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007711
Eli Friedman860a3192012-06-16 02:19:17 +00007712 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007713 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007714 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007715}
7716
7717inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007718 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007719
Tanya Lattner4f692c22012-01-16 21:02:28 +00007720 // Check vector operands differently.
7721 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7722 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7723
Chris Lattner90a8f272010-07-13 19:41:32 +00007724 // Diagnose cases where the user write a logical and/or but probably meant a
7725 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7726 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007727 if (LHS.get()->getType()->isIntegerType() &&
7728 !LHS.get()->getType()->isBooleanType() &&
7729 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007730 // Don't warn in macros or template instantiations.
7731 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007732 // If the RHS can be constant folded, and if it constant folds to something
7733 // that isn't 0 or 1 (which indicate a potential logical operation that
7734 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007735 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007736 llvm::APSInt Result;
7737 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007738 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007739 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007740 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007741 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007742 << (Opc == BO_LAnd ? "&&" : "||");
7743 // Suggest replacing the logical operator with the bitwise version
7744 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7745 << (Opc == BO_LAnd ? "&" : "|")
7746 << FixItHint::CreateReplacement(SourceRange(
7747 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007748 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007749 Opc == BO_LAnd ? "&" : "|");
7750 if (Opc == BO_LAnd)
7751 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7752 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7753 << FixItHint::CreateRemoval(
7754 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007755 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007756 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007757 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007758 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007759 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007760 }
Joey Gouly52e933b2013-02-21 11:49:56 +00007761
David Blaikie4e4d0842012-03-11 07:00:24 +00007762 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly52e933b2013-02-21 11:49:56 +00007763 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7764 // not operate on the built-in scalar and vector float types.
7765 if (Context.getLangOpts().OpenCL &&
7766 Context.getLangOpts().OpenCLVersion < 120) {
7767 if (LHS.get()->getType()->isFloatingType() ||
7768 RHS.get()->getType()->isFloatingType())
7769 return InvalidOperands(Loc, LHS, RHS);
7770 }
7771
Richard Trieu9f60dee2011-09-07 01:19:57 +00007772 LHS = UsualUnaryConversions(LHS.take());
7773 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007774 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007775
Richard Trieu9f60dee2011-09-07 01:19:57 +00007776 RHS = UsualUnaryConversions(RHS.take());
7777 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007778 return QualType();
7779
Richard Trieu9f60dee2011-09-07 01:19:57 +00007780 if (!LHS.get()->getType()->isScalarType() ||
7781 !RHS.get()->getType()->isScalarType())
7782 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007783
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007784 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007785 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007786
John McCall75f7c0f2010-06-04 00:29:51 +00007787 // The following is safe because we only use this method for
7788 // non-overloadable operands.
7789
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007790 // C++ [expr.log.and]p1
7791 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007792 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007793 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7794 if (LHSRes.isInvalid())
7795 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007796 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007797
Richard Trieu9f60dee2011-09-07 01:19:57 +00007798 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7799 if (RHSRes.isInvalid())
7800 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007801 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007802
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007803 // C++ [expr.log.and]p2
7804 // C++ [expr.log.or]p2
7805 // The result is a bool.
7806 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007807}
7808
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007809/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7810/// is a read-only property; return true if so. A readonly property expression
7811/// depends on various declarations and thus must be treated specially.
7812///
Mike Stump1eb44332009-09-09 15:08:12 +00007813static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007814 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7815 if (!PropExpr) return false;
7816 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007817
John McCall3c3b7f92011-10-25 17:37:35 +00007818 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7819 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007820 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007821 PropExpr->getBase()->getType();
7822
John McCall3c3b7f92011-10-25 17:37:35 +00007823 if (const ObjCObjectPointerType *OPT =
7824 BaseType->getAsObjCInterfacePointerType())
7825 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7826 if (S.isPropertyReadonly(PDecl, IFace))
7827 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007828 return false;
7829}
7830
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007831static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007832 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7833 if (!ME) return false;
7834 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7835 ObjCMessageExpr *Base =
7836 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7837 if (!Base) return false;
7838 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007839}
7840
John McCall78dae242012-03-13 00:37:01 +00007841/// Is the given expression (which must be 'const') a reference to a
7842/// variable which was originally non-const, but which has become
7843/// 'const' due to being captured within a block?
7844enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7845static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7846 assert(E->isLValue() && E->getType().isConstQualified());
7847 E = E->IgnoreParens();
7848
7849 // Must be a reference to a declaration from an enclosing scope.
7850 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7851 if (!DRE) return NCCK_None;
7852 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7853
7854 // The declaration must be a variable which is not declared 'const'.
7855 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7856 if (!var) return NCCK_None;
7857 if (var->getType().isConstQualified()) return NCCK_None;
7858 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7859
7860 // Decide whether the first capture was for a block or a lambda.
7861 DeclContext *DC = S.CurContext;
7862 while (DC->getParent() != var->getDeclContext())
7863 DC = DC->getParent();
7864 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7865}
7866
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007867/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7868/// emit an error and return true. If so, return false.
7869static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007870 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007871 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007872 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007873 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007874 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7875 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007876 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7877 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007878 if (IsLV == Expr::MLV_Valid)
7879 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007880
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007881 unsigned Diag = 0;
7882 bool NeedType = false;
7883 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007884 case Expr::MLV_ConstQualified:
7885 Diag = diag::err_typecheck_assign_const;
7886
John McCall78dae242012-03-13 00:37:01 +00007887 // Use a specialized diagnostic when we're assigning to an object
7888 // from an enclosing function or block.
7889 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7890 if (NCCK == NCCK_Block)
7891 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7892 else
7893 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7894 break;
7895 }
7896
John McCall7acddac2011-06-17 06:42:21 +00007897 // In ARC, use some specialized diagnostics for occasions where we
7898 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007899 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007900 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7901 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7902 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7903
John McCall7acddac2011-06-17 06:42:21 +00007904 // Use the normal diagnostic if it's pseudo-__strong but the
7905 // user actually wrote 'const'.
7906 if (var->isARCPseudoStrong() &&
7907 (!var->getTypeSourceInfo() ||
7908 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7909 // There are two pseudo-strong cases:
7910 // - self
John McCallf85e1932011-06-15 23:02:42 +00007911 ObjCMethodDecl *method = S.getCurMethodDecl();
7912 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007913 Diag = method->isClassMethod()
7914 ? diag::err_typecheck_arc_assign_self_class_method
7915 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007916
7917 // - fast enumeration variables
7918 else
John McCallf85e1932011-06-15 23:02:42 +00007919 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007920
John McCallf85e1932011-06-15 23:02:42 +00007921 SourceRange Assign;
7922 if (Loc != OrigLoc)
7923 Assign = SourceRange(OrigLoc, OrigLoc);
7924 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7925 // We need to preserve the AST regardless, so migration tool
7926 // can do its job.
7927 return false;
7928 }
7929 }
7930 }
7931
7932 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007933 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007934 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007935 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7936 NeedType = true;
7937 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007938 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007939 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7940 NeedType = true;
7941 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007942 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007943 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7944 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007945 case Expr::MLV_Valid:
7946 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007947 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007948 case Expr::MLV_MemberFunction:
7949 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007950 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7951 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007952 case Expr::MLV_IncompleteType:
7953 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007954 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007955 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007956 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007957 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7958 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007959 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007960 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007961 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007962 case Expr::MLV_InvalidMessageExpression:
7963 Diag = diag::error_readonly_message_assignment;
7964 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007965 case Expr::MLV_SubObjCPropertySetting:
7966 Diag = diag::error_no_subobject_property_setting;
7967 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007968 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007969
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007970 SourceRange Assign;
7971 if (Loc != OrigLoc)
7972 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007973 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007974 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007975 else
Mike Stump1eb44332009-09-09 15:08:12 +00007976 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007977 return true;
7978}
7979
Nico Weber7c81b432012-07-03 02:03:06 +00007980static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7981 SourceLocation Loc,
7982 Sema &Sema) {
7983 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007984 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7985 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7986 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7987 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007988 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007989 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007990
Nico Weber7c81b432012-07-03 02:03:06 +00007991 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007992 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7993 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7994 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7995 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7996 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7997 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007998 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007999 }
8000}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008001
8002// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00008003QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008004 SourceLocation Loc,
8005 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00008006 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8007
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008008 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00008009 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008010 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008011
Richard Trieu268942b2011-09-07 01:33:52 +00008012 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00008013 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8014 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008015 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008016 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00008017 Expr *RHSCheck = RHS.get();
8018
Nico Weber7c81b432012-07-03 02:03:06 +00008019 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00008020
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008021 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008022 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00008023 if (RHS.isInvalid())
8024 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008025 // Special case of NSObject attributes on c-style pointer types.
8026 if (ConvTy == IncompatiblePointer &&
8027 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008028 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008029 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008030 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008031 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008032
John McCallf89e55a2010-11-18 06:31:45 +00008033 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00008034 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00008035 Diag(Loc, diag::err_objc_object_assignment)
8036 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00008037
Chris Lattner2c156472008-08-21 18:04:13 +00008038 // If the RHS is a unary plus or minus, check to see if they = and + are
8039 // right next to each other. If so, the user may have typo'd "x =+ 4"
8040 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00008041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8042 RHSCheck = ICE->getSubExpr();
8043 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00008044 if ((UO->getOpcode() == UO_Plus ||
8045 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008046 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00008047 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00008048 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00008049 // And there is a space or other character before the subexpr of the
8050 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00008051 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00008052 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008053 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00008054 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008055 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00008056 }
Chris Lattner2c156472008-08-21 18:04:13 +00008057 }
John McCallf85e1932011-06-15 23:02:42 +00008058
8059 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00008060 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8061 // Warn about retain cycles where a block captures the LHS, but
8062 // not if the LHS is a simple variable into which the block is
8063 // being stored...unless that variable can be captured by reference!
8064 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8065 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8066 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8067 checkRetainCycles(LHSExpr, RHS.get());
8068
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008069 // It is safe to assign a weak reference into a strong variable.
8070 // Although this code can still have problems:
8071 // id x = self.weakProp;
8072 // id y = self.weakProp;
8073 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8074 // paths through the function. This should be revisited if
8075 // -Wrepeated-use-of-weak is made flow-sensitive.
8076 DiagnosticsEngine::Level Level =
8077 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8078 RHS.get()->getLocStart());
8079 if (Level != DiagnosticsEngine::Ignored)
8080 getCurFunction()->markSafeWeakUse(RHS.get());
8081
Jordan Rosee10f4d32012-09-15 02:48:31 +00008082 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00008083 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00008084 }
John McCallf85e1932011-06-15 23:02:42 +00008085 }
Chris Lattner2c156472008-08-21 18:04:13 +00008086 } else {
8087 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00008088 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008089 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008090
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008091 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00008092 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00008093 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008094
Richard Trieu268942b2011-09-07 01:33:52 +00008095 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008096
Reid Spencer5f016e22007-07-11 17:01:13 +00008097 // C99 6.5.16p3: The type of an assignment expression is the type of the
8098 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00008099 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00008100 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8101 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008102 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008103 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00008104 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00008105 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008106}
8107
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008108// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008109static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008110 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00008111 LHS = S.CheckPlaceholderExpr(LHS.take());
8112 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008113 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008114 return QualType();
8115
John McCallcf2e5062010-10-12 07:14:40 +00008116 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8117 // operands, but not unary promotions.
8118 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008119
John McCallf6a16482010-12-04 03:47:34 +00008120 // So we treat the LHS as a ignored value, and in C++ we allow the
8121 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008122 LHS = S.IgnoredValueConversions(LHS.take());
8123 if (LHS.isInvalid())
8124 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008125
Eli Friedmana6115062012-05-24 00:47:05 +00008126 S.DiagnoseUnusedExprResult(LHS.get());
8127
David Blaikie4e4d0842012-03-11 07:00:24 +00008128 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008129 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8130 if (RHS.isInvalid())
8131 return QualType();
8132 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00008133 S.RequireCompleteType(Loc, RHS.get()->getType(),
8134 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008135 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008136
John Wiegley429bb272011-04-08 18:41:53 +00008137 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008138}
8139
Steve Naroff49b45262007-07-13 16:58:59 +00008140/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8141/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008142static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8143 ExprValueKind &VK,
8144 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008145 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008146 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008147 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008148
Chris Lattner3528d352008-11-21 07:05:48 +00008149 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00008150 // Atomic types can be used for increment / decrement where the non-atomic
8151 // versions can, so ignore the _Atomic() specifier for the purpose of
8152 // checking.
8153 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8154 ResType = ResAtomicType->getValueType();
8155
Chris Lattner3528d352008-11-21 07:05:48 +00008156 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008157
David Blaikie4e4d0842012-03-11 07:00:24 +00008158 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008159 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00008160 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00008161 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008162 return QualType();
8163 }
8164 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008165 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008166 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008167 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00008168 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008169 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00008170 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008171 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00008172 } else if (ResType->isObjCObjectPointerType()) {
8173 // On modern runtimes, ObjC pointer arithmetic is forbidden.
8174 // Otherwise, we just need a complete type.
8175 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8176 checkArithmeticOnObjCPointer(S, OpLoc, Op))
8177 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00008178 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008179 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008180 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008181 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008182 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008183 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008184 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008185 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008186 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00008187 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00008188 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008189 } else {
John McCall09431682010-11-18 19:01:18 +00008190 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00008191 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008192 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008193 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008194 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008195 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008196 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008197 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008198 // In C++, a prefix increment is the same type as the operand. Otherwise
8199 // (in C or with postfix), the increment is the unqualified type of the
8200 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00008201 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00008202 VK = VK_LValue;
8203 return ResType;
8204 } else {
8205 VK = VK_RValue;
8206 return ResType.getUnqualifiedType();
8207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008208}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008209
8210
Anders Carlsson369dee42008-02-01 07:15:58 +00008211/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008212/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008213/// where the declaration is needed for type checking. We only need to
8214/// handle cases when the expression references a function designator
8215/// or is an lvalue. Here are some examples:
8216/// - &(x) => x
8217/// - &*****f => f for f a function designator.
8218/// - &s.xx => s
8219/// - &s.zz[1].yy -> s, if zz is an array
8220/// - *(x + 1) -> x, if x is an array
8221/// - &"123"[2] -> 0
8222/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008223static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008224 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008225 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008226 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008227 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008228 // If this is an arrow operator, the address is an offset from
8229 // the base's value, so the object the base refers to is
8230 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008231 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008232 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008233 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008234 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008235 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008236 // FIXME: This code shouldn't be necessary! We should catch the implicit
8237 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008238 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8239 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8240 if (ICE->getSubExpr()->getType()->isArrayType())
8241 return getPrimaryDecl(ICE->getSubExpr());
8242 }
8243 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008244 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008245 case Stmt::UnaryOperatorClass: {
8246 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008247
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008248 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008249 case UO_Real:
8250 case UO_Imag:
8251 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008252 return getPrimaryDecl(UO->getSubExpr());
8253 default:
8254 return 0;
8255 }
8256 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008257 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008258 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008259 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008260 // If the result of an implicit cast is an l-value, we care about
8261 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008262 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008263 default:
8264 return 0;
8265 }
8266}
8267
Richard Trieu5520f232011-09-07 21:46:33 +00008268namespace {
8269 enum {
8270 AO_Bit_Field = 0,
8271 AO_Vector_Element = 1,
8272 AO_Property_Expansion = 2,
8273 AO_Register_Variable = 3,
8274 AO_No_Error = 4
8275 };
8276}
Richard Trieu09a26ad2011-09-02 00:47:55 +00008277/// \brief Diagnose invalid operand for address of operations.
8278///
8279/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00008280static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8281 Expr *E, unsigned Type) {
8282 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8283}
8284
Reid Spencer5f016e22007-07-11 17:01:13 +00008285/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008286/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008287/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008288/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008289/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008290/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008291/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00008292static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00008293 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00008294 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8295 if (PTy->getKind() == BuiltinType::Overload) {
8296 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
Richard Smith3fa3fea2013-02-02 02:14:45 +00008297 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8298 == UO_AddrOf);
8299 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008300 << OrigOp.get()->getSourceRange();
8301 return QualType();
8302 }
8303
8304 return S.Context.OverloadTy;
8305 }
8306
8307 if (PTy->getKind() == BuiltinType::UnknownAny)
8308 return S.Context.UnknownAnyTy;
8309
8310 if (PTy->getKind() == BuiltinType::BoundMember) {
8311 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8312 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008313 return QualType();
8314 }
John McCall3c3b7f92011-10-25 17:37:35 +00008315
8316 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8317 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008318 }
John McCall9c72c602010-08-27 09:08:28 +00008319
John McCall3c3b7f92011-10-25 17:37:35 +00008320 if (OrigOp.get()->isTypeDependent())
8321 return S.Context.DependentTy;
8322
8323 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008324
John McCall9c72c602010-08-27 09:08:28 +00008325 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008326 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008327
David Blaikie4e4d0842012-03-11 07:00:24 +00008328 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008329 // Implement C99-only parts of addressof rules.
8330 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008331 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008332 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8333 // (assuming the deref expression is valid).
8334 return uOp->getSubExpr()->getType();
8335 }
8336 // Technically, there should be a check for array subscript
8337 // expressions here, but the result of one is always an lvalue anyway.
8338 }
John McCall5808ce42011-02-03 08:15:49 +00008339 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008340 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008341 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008342
Richard Smith3fa3fea2013-02-02 02:14:45 +00008343 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
David Blaikie0adb1752013-02-21 06:05:05 +00008344 bool sfinae = (bool)S.isSFINAEContext();
8345 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
Richard Smith3fa3fea2013-02-02 02:14:45 +00008346 : diag::ext_typecheck_addrof_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008347 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008348 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008349 return QualType();
Richard Smitha07a6c32013-05-01 19:00:39 +00008350 // Materialize the temporary as an lvalue so that we can take its address.
8351 OrigOp = op = new (S.Context)
8352 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true);
John McCall9c72c602010-08-27 09:08:28 +00008353 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008354 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008355 } else if (lval == Expr::LV_MemberFunction) {
8356 // If it's an instance method, make a member pointer.
8357 // The expression must have exactly the form &A::foo.
8358
8359 // If the underlying expression isn't a decl ref, give up.
8360 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008361 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008362 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008363 return QualType();
8364 }
8365 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8366 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8367
8368 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008369 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008370 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008371 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008372
8373 // The method was named without a qualifier.
8374 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008375 if (MD->getParent()->getName().empty())
8376 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8377 << op->getSourceRange();
8378 else {
8379 SmallString<32> Str;
8380 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8381 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8382 << op->getSourceRange()
8383 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8384 }
John McCall9c72c602010-08-27 09:08:28 +00008385 }
8386
John McCall09431682010-11-18 19:01:18 +00008387 return S.Context.getMemberPointerType(op->getType(),
8388 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008389 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008390 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008391 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008392 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008393 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008394 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008395 AddressOfError = AO_Property_Expansion;
8396 } else {
John McCall3c3b7f92011-10-25 17:37:35 +00008397 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smith3fa3fea2013-02-02 02:14:45 +00008398 << op->getType() << op->getSourceRange();
John McCall3c3b7f92011-10-25 17:37:35 +00008399 return QualType();
8400 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008401 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008402 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008403 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008404 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008405 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008406 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008407 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008408 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008409 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008410 // with the register storage-class specifier.
8411 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008412 // in C++ it is not error to take address of a register
8413 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008414 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008415 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008416 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008417 }
John McCallba135432009-11-21 08:51:07 +00008418 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008419 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008420 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008421 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008422 // Could be a pointer to member, though, if there is an explicit
8423 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008424 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008425 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008426 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008427 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008428 S.Diag(OpLoc,
8429 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008430 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008431 return QualType();
8432 }
Mike Stump1eb44332009-09-09 15:08:12 +00008433
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008434 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8435 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008436 return S.Context.getMemberPointerType(op->getType(),
8437 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008438 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008439 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008440 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008441 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008442 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008443
Richard Trieu5520f232011-09-07 21:46:33 +00008444 if (AddressOfError != AO_No_Error) {
8445 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8446 return QualType();
8447 }
8448
Eli Friedman441cf102009-05-16 23:27:50 +00008449 if (lval == Expr::LV_IncompleteVoidType) {
8450 // Taking the address of a void variable is technically illegal, but we
8451 // allow it in cases which are otherwise valid.
8452 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008453 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008454 }
8455
Reid Spencer5f016e22007-07-11 17:01:13 +00008456 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008457 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008458 return S.Context.getObjCObjectPointerType(op->getType());
8459 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008460}
8461
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008462/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008463static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8464 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008465 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008466 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008467
John Wiegley429bb272011-04-08 18:41:53 +00008468 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8469 if (ConvResult.isInvalid())
8470 return QualType();
8471 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008472 QualType OpTy = Op->getType();
8473 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008474
8475 if (isa<CXXReinterpretCastExpr>(Op)) {
8476 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8477 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8478 Op->getSourceRange());
8479 }
8480
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008481 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8482 // is an incomplete type or void. It would be possible to warn about
8483 // dereferencing a void pointer, but it's completely well-defined, and such a
8484 // warning is unlikely to catch any mistakes.
8485 if (const PointerType *PT = OpTy->getAs<PointerType>())
8486 Result = PT->getPointeeType();
8487 else if (const ObjCObjectPointerType *OPT =
8488 OpTy->getAs<ObjCObjectPointerType>())
8489 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008490 else {
John McCallfb8721c2011-04-10 19:13:55 +00008491 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008492 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008493 if (PR.take() != Op)
8494 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008495 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008496
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008497 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008498 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008499 << OpTy << Op->getSourceRange();
8500 return QualType();
8501 }
John McCall09431682010-11-18 19:01:18 +00008502
8503 // Dereferences are usually l-values...
8504 VK = VK_LValue;
8505
8506 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008507 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008508 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008509
8510 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008511}
8512
John McCall2de56d12010-08-25 11:45:40 +00008513static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008514 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008515 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008516 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008517 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008518 case tok::periodstar: Opc = BO_PtrMemD; break;
8519 case tok::arrowstar: Opc = BO_PtrMemI; break;
8520 case tok::star: Opc = BO_Mul; break;
8521 case tok::slash: Opc = BO_Div; break;
8522 case tok::percent: Opc = BO_Rem; break;
8523 case tok::plus: Opc = BO_Add; break;
8524 case tok::minus: Opc = BO_Sub; break;
8525 case tok::lessless: Opc = BO_Shl; break;
8526 case tok::greatergreater: Opc = BO_Shr; break;
8527 case tok::lessequal: Opc = BO_LE; break;
8528 case tok::less: Opc = BO_LT; break;
8529 case tok::greaterequal: Opc = BO_GE; break;
8530 case tok::greater: Opc = BO_GT; break;
8531 case tok::exclaimequal: Opc = BO_NE; break;
8532 case tok::equalequal: Opc = BO_EQ; break;
8533 case tok::amp: Opc = BO_And; break;
8534 case tok::caret: Opc = BO_Xor; break;
8535 case tok::pipe: Opc = BO_Or; break;
8536 case tok::ampamp: Opc = BO_LAnd; break;
8537 case tok::pipepipe: Opc = BO_LOr; break;
8538 case tok::equal: Opc = BO_Assign; break;
8539 case tok::starequal: Opc = BO_MulAssign; break;
8540 case tok::slashequal: Opc = BO_DivAssign; break;
8541 case tok::percentequal: Opc = BO_RemAssign; break;
8542 case tok::plusequal: Opc = BO_AddAssign; break;
8543 case tok::minusequal: Opc = BO_SubAssign; break;
8544 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8545 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8546 case tok::ampequal: Opc = BO_AndAssign; break;
8547 case tok::caretequal: Opc = BO_XorAssign; break;
8548 case tok::pipeequal: Opc = BO_OrAssign; break;
8549 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008550 }
8551 return Opc;
8552}
8553
John McCall2de56d12010-08-25 11:45:40 +00008554static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008555 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008556 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008557 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008558 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008559 case tok::plusplus: Opc = UO_PreInc; break;
8560 case tok::minusminus: Opc = UO_PreDec; break;
8561 case tok::amp: Opc = UO_AddrOf; break;
8562 case tok::star: Opc = UO_Deref; break;
8563 case tok::plus: Opc = UO_Plus; break;
8564 case tok::minus: Opc = UO_Minus; break;
8565 case tok::tilde: Opc = UO_Not; break;
8566 case tok::exclaim: Opc = UO_LNot; break;
8567 case tok::kw___real: Opc = UO_Real; break;
8568 case tok::kw___imag: Opc = UO_Imag; break;
8569 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008570 }
8571 return Opc;
8572}
8573
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008574/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8575/// This warning is only emitted for builtin assignment operations. It is also
8576/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008577static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008578 SourceLocation OpLoc) {
8579 if (!S.ActiveTemplateInstantiations.empty())
8580 return;
8581 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8582 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008583 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8584 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8585 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8586 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8587 if (!LHSDeclRef || !RHSDeclRef ||
8588 LHSDeclRef->getLocation().isMacroID() ||
8589 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008590 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008591 const ValueDecl *LHSDecl =
8592 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8593 const ValueDecl *RHSDecl =
8594 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8595 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008596 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008597 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008598 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008599 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008600 if (RefTy->getPointeeType().isVolatileQualified())
8601 return;
8602
8603 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008604 << LHSDeclRef->getType()
8605 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008606}
8607
Ted Kremenek3aaf41a2013-04-22 22:46:52 +00008608/// Check if a bitwise-& is performed on an Objective-C pointer. This
8609/// is usually indicative of introspection within the Objective-C pointer.
8610static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8611 SourceLocation OpLoc) {
8612 if (!S.getLangOpts().ObjC1)
8613 return;
8614
8615 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8616 const Expr *LHS = L.get();
8617 const Expr *RHS = R.get();
8618
8619 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8620 ObjCPointerExpr = LHS;
8621 OtherExpr = RHS;
8622 }
8623 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8624 ObjCPointerExpr = RHS;
8625 OtherExpr = LHS;
8626 }
8627
8628 // This warning is deliberately made very specific to reduce false
8629 // positives with logic that uses '&' for hashing. This logic mainly
8630 // looks for code trying to introspect into tagged pointers, which
8631 // code should generally never do.
8632 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
8633 S.Diag(OpLoc, diag::warn_objc_pointer_masking)
8634 << ObjCPointerExpr->getSourceRange();
8635 }
8636}
8637
Douglas Gregoreaebc752008-11-06 23:29:22 +00008638/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8639/// operator @p Opc at location @c TokLoc. This routine only supports
8640/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008641ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008642 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008643 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008644 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008645 // The syntax only allows initializer lists on the RHS of assignment,
8646 // so we don't need to worry about accepting invalid code for
8647 // non-assignment operators.
8648 // C++11 5.17p9:
8649 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8650 // of x = {} is x = T().
8651 InitializationKind Kind =
8652 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8653 InitializedEntity Entity =
8654 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008655 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008656 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008657 if (Init.isInvalid())
8658 return Init;
8659 RHSExpr = Init.take();
8660 }
8661
Richard Trieu78ea78b2011-09-07 01:49:20 +00008662 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008663 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008664 // The following two variables are used for compound assignment operators
8665 QualType CompLHSTy; // Type of LHS after promotions for computation
8666 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008667 ExprValueKind VK = VK_RValue;
8668 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008669
8670 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008671 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008672 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008673 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008674 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8675 VK = LHS.get()->getValueKind();
8676 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008677 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008678 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008679 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008680 break;
John McCall2de56d12010-08-25 11:45:40 +00008681 case BO_PtrMemD:
8682 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008683 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008684 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008685 break;
John McCall2de56d12010-08-25 11:45:40 +00008686 case BO_Mul:
8687 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008688 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008689 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008690 break;
John McCall2de56d12010-08-25 11:45:40 +00008691 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008692 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008693 break;
John McCall2de56d12010-08-25 11:45:40 +00008694 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008695 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008696 break;
John McCall2de56d12010-08-25 11:45:40 +00008697 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008698 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008699 break;
John McCall2de56d12010-08-25 11:45:40 +00008700 case BO_Shl:
8701 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008702 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008703 break;
John McCall2de56d12010-08-25 11:45:40 +00008704 case BO_LE:
8705 case BO_LT:
8706 case BO_GE:
8707 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008708 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008709 break;
John McCall2de56d12010-08-25 11:45:40 +00008710 case BO_EQ:
8711 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008712 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008713 break;
John McCall2de56d12010-08-25 11:45:40 +00008714 case BO_And:
Ted Kremenek3aaf41a2013-04-22 22:46:52 +00008715 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCall2de56d12010-08-25 11:45:40 +00008716 case BO_Xor:
8717 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008718 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008719 break;
John McCall2de56d12010-08-25 11:45:40 +00008720 case BO_LAnd:
8721 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008722 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008723 break;
John McCall2de56d12010-08-25 11:45:40 +00008724 case BO_MulAssign:
8725 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008726 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008727 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008728 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008729 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8730 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008731 break;
John McCall2de56d12010-08-25 11:45:40 +00008732 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008733 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008734 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008735 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8736 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008737 break;
John McCall2de56d12010-08-25 11:45:40 +00008738 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008739 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008740 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8741 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008742 break;
John McCall2de56d12010-08-25 11:45:40 +00008743 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008744 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8745 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8746 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008747 break;
John McCall2de56d12010-08-25 11:45:40 +00008748 case BO_ShlAssign:
8749 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008750 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008751 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008752 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8753 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008754 break;
John McCall2de56d12010-08-25 11:45:40 +00008755 case BO_AndAssign:
8756 case BO_XorAssign:
8757 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008758 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008759 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008760 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8761 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008762 break;
John McCall2de56d12010-08-25 11:45:40 +00008763 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008764 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008765 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008766 VK = RHS.get()->getValueKind();
8767 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008768 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008769 break;
8770 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008771 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008772 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008773
8774 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008775 CheckArrayAccess(LHS.get());
8776 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008777
Fariborz Jahanianec8deba2013-03-28 19:50:55 +00008778 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
8779 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
8780 &Context.Idents.get("object_setClass"),
8781 SourceLocation(), LookupOrdinaryName);
8782 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
8783 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8784 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
8785 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
8786 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
8787 FixItHint::CreateInsertion(RHSLocEnd, ")");
8788 }
8789 else
8790 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
8791 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +00008792 else if (const ObjCIvarRefExpr *OIRE =
8793 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanian0c701812013-04-02 18:57:54 +00008794 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian99a72d22013-03-28 23:39:11 +00008795
Eli Friedmanab3a8522009-03-28 01:22:36 +00008796 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008797 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008798 ResultTy, VK, OK, OpLoc,
8799 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008800 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008801 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008802 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008803 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008804 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008805 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008806 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008807 CompResultTy, OpLoc,
8808 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008809}
8810
Sebastian Redlaee3c932009-10-27 12:10:02 +00008811/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8812/// operators are mixed in a way that suggests that the programmer forgot that
8813/// comparison operators have higher precedence. The most typical example of
8814/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008815static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008816 SourceLocation OpLoc, Expr *LHSExpr,
8817 Expr *RHSExpr) {
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008818 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8819 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008820
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008821 // Check that one of the sides is a comparison operator.
8822 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8823 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8824 if (!isLeftComp && !isRightComp)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008825 return;
8826
8827 // Bitwise operations are sometimes used as eager logical ops.
8828 // Don't diagnose this.
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008829 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8830 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8831 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008832 return;
8833
Richard Trieu78ea78b2011-09-07 01:49:20 +00008834 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8835 OpLoc)
8836 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008837 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu70979d42011-08-10 22:41:34 +00008838 SourceRange ParensRange = isLeftComp ?
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008839 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8840 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008841
8842 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008843 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu70979d42011-08-10 22:41:34 +00008844 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008845 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008846 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008847 SuggestParentheses(Self, OpLoc,
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008848 Self.PDiag(diag::note_precedence_bitwise_first)
8849 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu70979d42011-08-10 22:41:34 +00008850 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008851}
8852
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008853/// \brief It accepts a '&' expr that is inside a '|' one.
8854/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8855/// in parentheses.
8856static void
8857EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8858 BinaryOperator *Bop) {
8859 assert(Bop->getOpcode() == BO_And);
8860 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8861 << Bop->getSourceRange() << OpLoc;
8862 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008863 Self.PDiag(diag::note_precedence_silence)
8864 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008865 Bop->getSourceRange());
8866}
8867
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008868/// \brief It accepts a '&&' expr that is inside a '||' one.
8869/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8870/// in parentheses.
8871static void
8872EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008873 BinaryOperator *Bop) {
8874 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008875 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8876 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008877 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008878 Self.PDiag(diag::note_precedence_silence)
8879 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008880 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008881}
8882
8883/// \brief Returns true if the given expression can be evaluated as a constant
8884/// 'true'.
8885static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8886 bool Res;
8887 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8888}
8889
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008890/// \brief Returns true if the given expression can be evaluated as a constant
8891/// 'false'.
8892static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8893 bool Res;
8894 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8895}
8896
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008897/// \brief Look for '&&' in the left hand of a '||' expr.
8898static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008899 Expr *LHSExpr, Expr *RHSExpr) {
8900 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008901 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008902 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008903 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008904 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008905 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8906 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8907 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8908 } else if (Bop->getOpcode() == BO_LOr) {
8909 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8910 // If it's "a || b && 1 || c" we didn't warn earlier for
8911 // "a || b && 1", but warn now.
8912 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8913 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8914 }
8915 }
8916 }
8917}
8918
8919/// \brief Look for '&&' in the right hand of a '||' expr.
8920static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008921 Expr *LHSExpr, Expr *RHSExpr) {
8922 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008923 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008924 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008925 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008926 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008927 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8928 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8929 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008930 }
8931 }
8932}
8933
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008934/// \brief Look for '&' in the left or right hand of a '|' expr.
8935static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8936 Expr *OrArg) {
8937 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8938 if (Bop->getOpcode() == BO_And)
8939 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8940 }
8941}
8942
David Blaikieb3f55c52012-10-05 00:41:03 +00008943static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +00008944 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +00008945 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8946 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008947 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008948 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +00008949 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +00008950 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008951 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008952 Bop->getSourceRange());
8953 }
8954 }
8955}
8956
Richard Trieu2a6e5282013-04-17 02:12:45 +00008957static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
8958 Expr *LHSExpr, Expr *RHSExpr) {
8959 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
8960 if (!OCE)
8961 return;
8962
8963 FunctionDecl *FD = OCE->getDirectCallee();
8964 if (!FD || !FD->isOverloadedOperator())
8965 return;
8966
8967 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
8968 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
8969 return;
8970
8971 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
8972 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
8973 << (Kind == OO_LessLess);
Richard Trieu2a6e5282013-04-17 02:12:45 +00008974 SuggestParentheses(S, OCE->getOperatorLoc(),
8975 S.PDiag(diag::note_precedence_silence)
8976 << (Kind == OO_LessLess ? "<<" : ">>"),
8977 OCE->getSourceRange());
Richard Trieu1a7df992013-04-18 01:04:37 +00008978 SuggestParentheses(S, OpLoc,
8979 S.PDiag(diag::note_evaluate_comparison_first),
8980 SourceRange(OCE->getArg(1)->getLocStart(),
8981 RHSExpr->getLocEnd()));
Richard Trieu2a6e5282013-04-17 02:12:45 +00008982}
8983
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008984/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008985/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008986static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008987 SourceLocation OpLoc, Expr *LHSExpr,
8988 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008989 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008990 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008991 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008992
8993 // Diagnose "arg1 & arg2 | arg3"
8994 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008995 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8996 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008997 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008998
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008999 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9000 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00009001 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00009002 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9003 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009004 }
David Blaikieb3f55c52012-10-05 00:41:03 +00009005
9006 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9007 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +00009008 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9009 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9010 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +00009011 }
Richard Trieu2a6e5282013-04-17 02:12:45 +00009012
9013 // Warn on overloaded shift operators and comparisons, such as:
9014 // cout << 5 == 4;
9015 if (BinaryOperator::isComparisonOp(Opc))
9016 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009017}
9018
Reid Spencer5f016e22007-07-11 17:01:13 +00009019// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009020ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00009021 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00009022 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00009023 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00009024 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9025 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00009026
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009027 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00009028 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009029
Richard Trieubefece12011-09-07 02:02:10 +00009030 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009031}
9032
John McCall3c3b7f92011-10-25 17:37:35 +00009033/// Build an overloaded binary operator expression in the given scope.
9034static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9035 BinaryOperatorKind Opc,
9036 Expr *LHS, Expr *RHS) {
9037 // Find all of the overloaded operators visible from this
9038 // point. We perform both an operator-name lookup from the local
9039 // scope and an argument-dependent lookup based on the types of
9040 // the arguments.
9041 UnresolvedSet<16> Functions;
9042 OverloadedOperatorKind OverOp
9043 = BinaryOperator::getOverloadedOperator(Opc);
9044 if (Sc && OverOp != OO_None)
9045 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9046 RHS->getType(), Functions);
9047
9048 // Build the (potentially-overloaded, potentially-dependent)
9049 // binary operation.
9050 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9051}
9052
John McCall60d7b3a2010-08-24 06:29:42 +00009053ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009054 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00009055 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00009056 // We want to end up calling one of checkPseudoObjectAssignment
9057 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9058 // both expressions are overloadable or either is type-dependent),
9059 // or CreateBuiltinBinOp (in any other case). We also want to get
9060 // any placeholder types out of the way.
9061
John McCall3c3b7f92011-10-25 17:37:35 +00009062 // Handle pseudo-objects in the LHS.
9063 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9064 // Assignments with a pseudo-object l-value need special analysis.
9065 if (pty->getKind() == BuiltinType::PseudoObject &&
9066 BinaryOperator::isAssignmentOp(Opc))
9067 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9068
9069 // Don't resolve overloads if the other type is overloadable.
9070 if (pty->getKind() == BuiltinType::Overload) {
9071 // We can't actually test that if we still have a placeholder,
9072 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00009073 // code below are valid when the LHS is an overload set. Note
9074 // that an overload set can be dependently-typed, but it never
9075 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00009076 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9077 if (resolvedRHS.isInvalid()) return ExprError();
9078 RHSExpr = resolvedRHS.take();
9079
John McCallac516502011-10-28 01:04:34 +00009080 if (RHSExpr->isTypeDependent() ||
9081 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00009082 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9083 }
9084
9085 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9086 if (LHS.isInvalid()) return ExprError();
9087 LHSExpr = LHS.take();
9088 }
9089
9090 // Handle pseudo-objects in the RHS.
9091 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9092 // An overload in the RHS can potentially be resolved by the type
9093 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00009094 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9095 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9096 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9097
Eli Friedman87884912012-01-17 21:27:43 +00009098 if (LHSExpr->getType()->isOverloadableType())
9099 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9100
John McCall3c3b7f92011-10-25 17:37:35 +00009101 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00009102 }
John McCall3c3b7f92011-10-25 17:37:35 +00009103
9104 // Don't resolve overloads if the other type is overloadable.
9105 if (pty->getKind() == BuiltinType::Overload &&
9106 LHSExpr->getType()->isOverloadableType())
9107 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9108
9109 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9110 if (!resolvedRHS.isUsable()) return ExprError();
9111 RHSExpr = resolvedRHS.take();
9112 }
9113
David Blaikie4e4d0842012-03-11 07:00:24 +00009114 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00009115 // If either expression is type-dependent, always build an
9116 // overloaded op.
9117 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9118 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009119
John McCallac516502011-10-28 01:04:34 +00009120 // Otherwise, build an overloaded op if either expression has an
9121 // overloadable type.
9122 if (LHSExpr->getType()->isOverloadableType() ||
9123 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00009124 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00009125 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009126
Douglas Gregoreaebc752008-11-06 23:29:22 +00009127 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00009128 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00009129}
9130
John McCall60d7b3a2010-08-24 06:29:42 +00009131ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00009132 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00009133 Expr *InputExpr) {
9134 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00009135 ExprValueKind VK = VK_RValue;
9136 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00009137 QualType resultType;
9138 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00009139 case UO_PreInc:
9140 case UO_PreDec:
9141 case UO_PostInc:
9142 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00009143 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009144 Opc == UO_PreInc ||
9145 Opc == UO_PostInc,
9146 Opc == UO_PreInc ||
9147 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00009148 break;
John McCall2de56d12010-08-25 11:45:40 +00009149 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00009150 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009151 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009152 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00009153 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00009154 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009155 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009156 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009157 }
John McCall2de56d12010-08-25 11:45:40 +00009158 case UO_Plus:
9159 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00009160 Input = UsualUnaryConversions(Input.take());
9161 if (Input.isInvalid()) return ExprError();
9162 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009163 if (resultType->isDependentType())
9164 break;
Douglas Gregor00619622010-06-22 23:41:02 +00009165 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9166 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00009167 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00009168 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00009169 resultType->isEnumeralType())
9170 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00009171 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00009172 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00009173 resultType->isPointerType())
9174 break;
9175
Sebastian Redl0eb23302009-01-19 00:08:26 +00009176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009177 << resultType << Input.get()->getSourceRange());
9178
John McCall2de56d12010-08-25 11:45:40 +00009179 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00009180 Input = UsualUnaryConversions(Input.take());
Joey Gouly52e933b2013-02-21 11:49:56 +00009181 if (Input.isInvalid())
9182 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009183 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009184 if (resultType->isDependentType())
9185 break;
Chris Lattner02a65142008-07-25 23:52:49 +00009186 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9187 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9188 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00009189 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly52e933b2013-02-21 11:49:56 +00009190 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00009191 else if (resultType->hasIntegerRepresentation())
9192 break;
Joey Gouly52e933b2013-02-21 11:49:56 +00009193 else if (resultType->isExtVectorType()) {
9194 if (Context.getLangOpts().OpenCL) {
9195 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9196 // on vector float types.
9197 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9198 if (!T->isIntegerType())
9199 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9200 << resultType << Input.get()->getSourceRange());
9201 }
9202 break;
9203 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009204 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly52e933b2013-02-21 11:49:56 +00009205 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009206 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009207 break;
John Wiegley429bb272011-04-08 18:41:53 +00009208
John McCall2de56d12010-08-25 11:45:40 +00009209 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00009210 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00009211 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9212 if (Input.isInvalid()) return ExprError();
9213 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00009214
9215 // Though we still have to promote half FP to float...
Joey Gouly19dbb202013-01-23 11:56:20 +00009216 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00009217 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9218 resultType = Context.FloatTy;
9219 }
9220
Sebastian Redl28507842009-02-26 14:39:58 +00009221 if (resultType->isDependentType())
9222 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00009223 if (resultType->isScalarType()) {
9224 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00009225 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00009226 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9227 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00009228 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9229 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly52e933b2013-02-21 11:49:56 +00009230 } else if (Context.getLangOpts().OpenCL &&
9231 Context.getLangOpts().OpenCLVersion < 120) {
9232 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9233 // operate on scalar float types.
9234 if (!resultType->isIntegerType())
9235 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9236 << resultType << Input.get()->getSourceRange());
Abramo Bagnara737d5442011-04-07 09:26:19 +00009237 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00009238 } else if (resultType->isExtVectorType()) {
Joey Gouly52e933b2013-02-21 11:49:56 +00009239 if (Context.getLangOpts().OpenCL &&
9240 Context.getLangOpts().OpenCLVersion < 120) {
9241 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9242 // operate on vector float types.
9243 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9244 if (!T->isIntegerType())
9245 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9246 << resultType << Input.get()->getSourceRange());
9247 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00009248 // Vector logical not returns the signed variant of the operand type.
9249 resultType = GetSignedVectorType(resultType);
9250 break;
John McCall2cd11fe2010-10-12 02:09:17 +00009251 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009252 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009253 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009254 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009255
Reid Spencer5f016e22007-07-11 17:01:13 +00009256 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009257 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009258 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009259 break;
John McCall2de56d12010-08-25 11:45:40 +00009260 case UO_Real:
9261 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009262 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00009263 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9264 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00009265 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00009266 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9267 if (Input.get()->getValueKind() != VK_RValue &&
9268 Input.get()->getObjectKind() == OK_Ordinary)
9269 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00009270 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00009271 // In C, a volatile scalar is read by __imag. In C++, it is not.
9272 Input = DefaultLvalueConversion(Input.take());
9273 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00009274 break;
John McCall2de56d12010-08-25 11:45:40 +00009275 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009276 resultType = Input.get()->getType();
9277 VK = Input.get()->getValueKind();
9278 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009279 break;
9280 }
John Wiegley429bb272011-04-08 18:41:53 +00009281 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009282 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009283
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00009284 // Check for array bounds violations in the operand of the UnaryOperator,
9285 // except for the '*' and '&' operators that have to be handled specially
9286 // by CheckArrayAccess (as there are special cases like &array[arraysize]
9287 // that are explicitly defined as valid by the standard).
9288 if (Opc != UO_AddrOf && Opc != UO_Deref)
9289 CheckArrayAccess(Input.get());
9290
John Wiegley429bb272011-04-08 18:41:53 +00009291 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009292 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009293}
9294
Douglas Gregord3d08532011-12-14 21:23:13 +00009295/// \brief Determine whether the given expression is a qualified member
9296/// access expression, of a form that could be turned into a pointer to member
9297/// with the address-of operator.
9298static bool isQualifiedMemberAccess(Expr *E) {
9299 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9300 if (!DRE->getQualifier())
9301 return false;
9302
9303 ValueDecl *VD = DRE->getDecl();
9304 if (!VD->isCXXClassMember())
9305 return false;
9306
9307 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9308 return true;
9309 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9310 return Method->isInstance();
9311
9312 return false;
9313 }
9314
9315 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9316 if (!ULE->getQualifier())
9317 return false;
9318
9319 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9320 DEnd = ULE->decls_end();
9321 D != DEnd; ++D) {
9322 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9323 if (Method->isInstance())
9324 return true;
9325 } else {
9326 // Overload set does not contain methods.
9327 break;
9328 }
9329 }
9330
9331 return false;
9332 }
9333
9334 return false;
9335}
9336
John McCall60d7b3a2010-08-24 06:29:42 +00009337ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009338 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00009339 // First things first: handle placeholders so that the
9340 // overloaded-operator check considers the right type.
9341 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9342 // Increment and decrement of pseudo-object references.
9343 if (pty->getKind() == BuiltinType::PseudoObject &&
9344 UnaryOperator::isIncrementDecrementOp(Opc))
9345 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9346
9347 // extension is always a builtin operator.
9348 if (Opc == UO_Extension)
9349 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9350
9351 // & gets special logic for several kinds of placeholder.
9352 // The builtin code knows what to do.
9353 if (Opc == UO_AddrOf &&
9354 (pty->getKind() == BuiltinType::Overload ||
9355 pty->getKind() == BuiltinType::UnknownAny ||
9356 pty->getKind() == BuiltinType::BoundMember))
9357 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9358
9359 // Anything else needs to be handled now.
9360 ExprResult Result = CheckPlaceholderExpr(Input);
9361 if (Result.isInvalid()) return ExprError();
9362 Input = Result.take();
9363 }
9364
David Blaikie4e4d0842012-03-11 07:00:24 +00009365 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00009366 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9367 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009368 // Find all of the overloaded operators visible from this
9369 // point. We perform both an operator-name lookup from the local
9370 // scope and an argument-dependent lookup based on the types of
9371 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009372 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009373 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009374 if (S && OverOp != OO_None)
9375 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9376 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009377
John McCall9ae2f072010-08-23 23:25:46 +00009378 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009379 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009380
John McCall9ae2f072010-08-23 23:25:46 +00009381 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009382}
9383
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009384// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009385ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009386 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009387 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009388}
9389
Steve Naroff1b273c42007-09-16 14:56:35 +00009390/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009391ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009392 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009393 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009394 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009395 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009396 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009397}
9398
John McCallf85e1932011-06-15 23:02:42 +00009399/// Given the last statement in a statement-expression, check whether
9400/// the result is a producing expression (like a call to an
9401/// ns_returns_retained function) and, if so, rebuild it to hoist the
9402/// release out of the full-expression. Otherwise, return null.
9403/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00009404static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00009405 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00009406 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00009407 if (!cleanups) return 0;
9408
9409 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00009410 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00009411 return 0;
9412
9413 // Splice out the cast. This shouldn't modify any interesting
9414 // features of the statement.
9415 Expr *producer = cast->getSubExpr();
9416 assert(producer->getType() == cast->getType());
9417 assert(producer->getValueKind() == cast->getValueKind());
9418 cleanups->setSubExpr(producer);
9419 return cleanups;
9420}
9421
John McCall73f428c2012-04-04 01:27:53 +00009422void Sema::ActOnStartStmtExpr() {
9423 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9424}
9425
9426void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009427 // Note that function is also called by TreeTransform when leaving a
9428 // StmtExpr scope without rebuilding anything.
9429
John McCall73f428c2012-04-04 01:27:53 +00009430 DiscardCleanupsInEvaluationContext();
9431 PopExpressionEvaluationContext();
9432}
9433
John McCall60d7b3a2010-08-24 06:29:42 +00009434ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009435Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009436 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009437 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9438 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9439
John McCall73f428c2012-04-04 01:27:53 +00009440 if (hasAnyUnrecoverableErrorsInThisFunction())
9441 DiscardCleanupsInEvaluationContext();
9442 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9443 PopExpressionEvaluationContext();
9444
Douglas Gregordd8f5692010-03-10 04:54:39 +00009445 bool isFileScope
9446 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009447 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009448 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009449
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009450 // FIXME: there are a variety of strange constraints to enforce here, for
9451 // example, it is not possible to goto into a stmt expression apparently.
9452 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009453
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009454 // If there are sub stmts in the compound stmt, take the type of the last one
9455 // as the type of the stmtexpr.
9456 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009457 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009458 if (!Compound->body_empty()) {
9459 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009460 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009461 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009462 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9463 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009464 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009465 }
John McCallf85e1932011-06-15 23:02:42 +00009466
John Wiegley429bb272011-04-08 18:41:53 +00009467 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009468 // Do function/array conversion on the last expression, but not
9469 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009470 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9471 if (LastExpr.isInvalid())
9472 return ExprError();
9473 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009474
John Wiegley429bb272011-04-08 18:41:53 +00009475 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009476 // In ARC, if the final expression ends in a consume, splice
9477 // the consume out and bind it later. In the alternate case
9478 // (when dealing with a retainable type), the result
9479 // initialization will create a produce. In both cases the
9480 // result will be +1, and we'll need to balance that out with
9481 // a bind.
9482 if (Expr *rebuiltLastStmt
9483 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9484 LastExpr = rebuiltLastStmt;
9485 } else {
9486 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009487 InitializedEntity::InitializeResult(LPLoc,
9488 Ty,
9489 false),
9490 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009491 LastExpr);
9492 }
9493
John Wiegley429bb272011-04-08 18:41:53 +00009494 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009495 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009496 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009497 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009498 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009499 else
John Wiegley429bb272011-04-08 18:41:53 +00009500 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009501 StmtExprMayBindToTemp = true;
9502 }
9503 }
9504 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009505 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009506
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009507 // FIXME: Check that expression type is complete/non-abstract; statement
9508 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009509 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9510 if (StmtExprMayBindToTemp)
9511 return MaybeBindToTemporary(ResStmtExpr);
9512 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009513}
Steve Naroffd34e9152007-08-01 22:05:33 +00009514
John McCall60d7b3a2010-08-24 06:29:42 +00009515ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009516 TypeSourceInfo *TInfo,
9517 OffsetOfComponent *CompPtr,
9518 unsigned NumComponents,
9519 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009520 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009521 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009522 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009523
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009524 // We must have at least one component that refers to the type, and the first
9525 // one is known to be a field designator. Verify that the ArgTy represents
9526 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009527 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009528 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9529 << ArgTy << TypeRange);
9530
9531 // Type must be complete per C99 7.17p3 because a declaring a variable
9532 // with an incomplete type would be ill-formed.
9533 if (!Dependent
9534 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009535 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009536 return ExprError();
9537
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009538 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9539 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009540 // FIXME: This diagnostic isn't actually visible because the location is in
9541 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009542 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009543 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9544 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009545
9546 bool DidWarnAboutNonPOD = false;
9547 QualType CurrentType = ArgTy;
9548 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009549 SmallVector<OffsetOfNode, 4> Comps;
9550 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009551 for (unsigned i = 0; i != NumComponents; ++i) {
9552 const OffsetOfComponent &OC = CompPtr[i];
9553 if (OC.isBrackets) {
9554 // Offset of an array sub-field. TODO: Should we allow vector elements?
9555 if (!CurrentType->isDependentType()) {
9556 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9557 if(!AT)
9558 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9559 << CurrentType);
9560 CurrentType = AT->getElementType();
9561 } else
9562 CurrentType = Context.DependentTy;
9563
Richard Smithea011432011-10-17 23:29:39 +00009564 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9565 if (IdxRval.isInvalid())
9566 return ExprError();
9567 Expr *Idx = IdxRval.take();
9568
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009569 // The expression must be an integral expression.
9570 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009571 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9572 !Idx->getType()->isIntegerType())
9573 return ExprError(Diag(Idx->getLocStart(),
9574 diag::err_typecheck_subscript_not_integer)
9575 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009576
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009577 // Record this array index.
9578 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009579 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009580 continue;
9581 }
9582
9583 // Offset of a field.
9584 if (CurrentType->isDependentType()) {
9585 // We have the offset of a field, but we can't look into the dependent
9586 // type. Just record the identifier of the field.
9587 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9588 CurrentType = Context.DependentTy;
9589 continue;
9590 }
9591
9592 // We need to have a complete type to look into.
9593 if (RequireCompleteType(OC.LocStart, CurrentType,
9594 diag::err_offsetof_incomplete_type))
9595 return ExprError();
9596
9597 // Look for the designated field.
9598 const RecordType *RC = CurrentType->getAs<RecordType>();
9599 if (!RC)
9600 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9601 << CurrentType);
9602 RecordDecl *RD = RC->getDecl();
9603
9604 // C++ [lib.support.types]p5:
9605 // The macro offsetof accepts a restricted set of type arguments in this
9606 // International Standard. type shall be a POD structure or a POD union
9607 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009608 // C++11 [support.types]p4:
9609 // If type is not a standard-layout class (Clause 9), the results are
9610 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009611 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009612 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009613 unsigned DiagID =
Richard Smith80ad52f2013-01-02 11:42:31 +00009614 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009615 : diag::warn_offsetof_non_pod_type;
9616
9617 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009618 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009619 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009620 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9621 << CurrentType))
9622 DidWarnAboutNonPOD = true;
9623 }
9624
9625 // Look for the field.
9626 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9627 LookupQualifiedName(R, RD);
9628 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009629 IndirectFieldDecl *IndirectMemberDecl = 0;
9630 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009631 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009632 MemberDecl = IndirectMemberDecl->getAnonField();
9633 }
9634
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009635 if (!MemberDecl)
9636 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9637 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9638 OC.LocEnd));
9639
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009640 // C99 7.17p3:
9641 // (If the specified member is a bit-field, the behavior is undefined.)
9642 //
9643 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009644 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009645 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9646 << MemberDecl->getDeclName()
9647 << SourceRange(BuiltinLoc, RParenLoc);
9648 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9649 return ExprError();
9650 }
Eli Friedman19410a72010-08-05 10:11:36 +00009651
9652 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009653 if (IndirectMemberDecl)
9654 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009655
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009656 // If the member was found in a base class, introduce OffsetOfNodes for
9657 // the base class indirections.
9658 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9659 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009660 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009661 CXXBasePath &Path = Paths.front();
9662 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9663 B != BEnd; ++B)
9664 Comps.push_back(OffsetOfNode(B->Base));
9665 }
Eli Friedman19410a72010-08-05 10:11:36 +00009666
Francois Pichet87c2e122010-11-21 06:08:52 +00009667 if (IndirectMemberDecl) {
9668 for (IndirectFieldDecl::chain_iterator FI =
9669 IndirectMemberDecl->chain_begin(),
9670 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9671 assert(isa<FieldDecl>(*FI));
9672 Comps.push_back(OffsetOfNode(OC.LocStart,
9673 cast<FieldDecl>(*FI), OC.LocEnd));
9674 }
9675 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009676 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009677
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009678 CurrentType = MemberDecl->getType().getNonReferenceType();
9679 }
9680
9681 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009682 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009683}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009684
John McCall60d7b3a2010-08-24 06:29:42 +00009685ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009686 SourceLocation BuiltinLoc,
9687 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009688 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009689 OffsetOfComponent *CompPtr,
9690 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009691 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009692
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009693 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009694 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009695 if (ArgTy.isNull())
9696 return ExprError();
9697
Eli Friedman5a15dc12010-08-05 10:15:45 +00009698 if (!ArgTInfo)
9699 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9700
9701 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009702 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009703}
9704
9705
John McCall60d7b3a2010-08-24 06:29:42 +00009706ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009707 Expr *CondExpr,
9708 Expr *LHSExpr, Expr *RHSExpr,
9709 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009710 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9711
John McCallf89e55a2010-11-18 06:31:45 +00009712 ExprValueKind VK = VK_RValue;
9713 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009714 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009715 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009716 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009717 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009718 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009719 } else {
9720 // The conditional expression is required to be a constant expression.
9721 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009722 ExprResult CondICE
9723 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9724 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009725 if (CondICE.isInvalid())
9726 return ExprError();
9727 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009728
Sebastian Redl28507842009-02-26 14:39:58 +00009729 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009730 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9731
9732 resType = ActiveExpr->getType();
9733 ValueDependent = ActiveExpr->isValueDependent();
9734 VK = ActiveExpr->getValueKind();
9735 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009736 }
9737
Sebastian Redlf53597f2009-03-15 17:47:39 +00009738 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009739 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009740 resType->isDependentType(),
9741 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009742}
9743
Steve Naroff4eb206b2008-09-03 18:15:37 +00009744//===----------------------------------------------------------------------===//
9745// Clang Extensions.
9746//===----------------------------------------------------------------------===//
9747
9748/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009749void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009750 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009751 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009752 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009753 if (CurScope)
9754 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009755 else
9756 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009757
Eli Friedman84b007f2012-01-26 03:00:14 +00009758 getCurBlock()->HasImplicitReturnType = true;
9759
John McCall538773c2011-11-11 03:19:12 +00009760 // Enter a new evaluation context to insulate the block from any
9761 // cleanups from the enclosing full-expression.
9762 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009763}
9764
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009765void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9766 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009767 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009768 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009769 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009770
John McCallbf1a0282010-06-04 23:28:52 +00009771 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009772 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009773
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009774 // FIXME: We should allow unexpanded parameter packs here, but that would,
9775 // in turn, make the block expression contain unexpanded parameter packs.
9776 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9777 // Drop the parameters.
9778 FunctionProtoType::ExtProtoInfo EPI;
9779 EPI.HasTrailingReturn = false;
9780 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +00009781 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009782 Sig = Context.getTrivialTypeSourceInfo(T);
9783 }
9784
John McCall711c52b2011-01-05 12:14:39 +00009785 // GetTypeForDeclarator always produces a function type for a block
9786 // literal signature. Furthermore, it is always a FunctionProtoType
9787 // unless the function was written with a typedef.
9788 assert(T->isFunctionType() &&
9789 "GetTypeForDeclarator made a non-function block signature");
9790
9791 // Look for an explicit signature in that function type.
9792 FunctionProtoTypeLoc ExplicitSignature;
9793
9794 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00009795 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall711c52b2011-01-05 12:14:39 +00009796
9797 // Check whether that explicit signature was synthesized by
9798 // GetTypeForDeclarator. If so, don't save that as part of the
9799 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009800 if (ExplicitSignature.getLocalRangeBegin() ==
9801 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009802 // This would be much cheaper if we stored TypeLocs instead of
9803 // TypeSourceInfos.
9804 TypeLoc Result = ExplicitSignature.getResultLoc();
9805 unsigned Size = Result.getFullDataSize();
9806 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9807 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9808
9809 ExplicitSignature = FunctionProtoTypeLoc();
9810 }
John McCall82dc0092010-06-04 11:21:44 +00009811 }
Mike Stump1eb44332009-09-09 15:08:12 +00009812
John McCall711c52b2011-01-05 12:14:39 +00009813 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9814 CurBlock->FunctionType = T;
9815
9816 const FunctionType *Fn = T->getAs<FunctionType>();
9817 QualType RetTy = Fn->getResultType();
9818 bool isVariadic =
9819 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9820
John McCallc71a4912010-06-04 19:02:56 +00009821 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009822
John McCall82dc0092010-06-04 11:21:44 +00009823 // Don't allow returning a objc interface by value.
9824 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009825 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009826 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9827 return;
9828 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009829
John McCall82dc0092010-06-04 11:21:44 +00009830 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009831 // return type. TODO: what should we do with declarators like:
9832 // ^ * { ... }
9833 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009834 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009835 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009836 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009837 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009838 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009839
John McCall82dc0092010-06-04 11:21:44 +00009840 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009841 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009842 if (ExplicitSignature) {
9843 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9844 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009845 if (Param->getIdentifier() == 0 &&
9846 !Param->isImplicit() &&
9847 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009848 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009849 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009850 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009851 }
John McCall82dc0092010-06-04 11:21:44 +00009852
9853 // Fake up parameter variables if we have a typedef, like
9854 // ^ fntype { ... }
9855 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9856 for (FunctionProtoType::arg_type_iterator
9857 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9858 ParmVarDecl *Param =
9859 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009860 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009861 *I);
John McCallc71a4912010-06-04 19:02:56 +00009862 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009863 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009864 }
John McCall82dc0092010-06-04 11:21:44 +00009865
John McCallc71a4912010-06-04 19:02:56 +00009866 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009867 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009868 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009869 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9870 CurBlock->TheDecl->param_end(),
9871 /*CheckParameterNames=*/false);
9872 }
9873
John McCall82dc0092010-06-04 11:21:44 +00009874 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009875 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009876
John McCall82dc0092010-06-04 11:21:44 +00009877 // Put the parameter variables in scope. We can bail out immediately
9878 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009879 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009880 return;
9881
Steve Naroff090276f2008-10-10 01:28:17 +00009882 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009883 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9884 (*AI)->setOwningFunction(CurBlock->TheDecl);
9885
Steve Naroff090276f2008-10-10 01:28:17 +00009886 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009887 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009888 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009889
Steve Naroff090276f2008-10-10 01:28:17 +00009890 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009891 }
John McCall7a9813c2010-01-22 00:28:27 +00009892 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009893}
9894
9895/// ActOnBlockError - If there is an error parsing a block, this callback
9896/// is invoked to pop the information about the block from the action impl.
9897void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009898 // Leave the expression-evaluation context.
9899 DiscardCleanupsInEvaluationContext();
9900 PopExpressionEvaluationContext();
9901
Steve Naroff4eb206b2008-09-03 18:15:37 +00009902 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009903 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009904 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009905}
9906
9907/// ActOnBlockStmtExpr - This is called when the body of a block statement
9908/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009909ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009910 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009911 // If blocks are disabled, emit an error.
9912 if (!LangOpts.Blocks)
9913 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009914
John McCall538773c2011-11-11 03:19:12 +00009915 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009916 if (hasAnyUnrecoverableErrorsInThisFunction())
9917 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009918 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9919 PopExpressionEvaluationContext();
9920
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009921 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009922
9923 if (BSI->HasImplicitReturnType)
9924 deduceClosureReturnType(*BSI);
9925
Steve Naroff090276f2008-10-10 01:28:17 +00009926 PopDeclContext();
9927
Steve Naroff4eb206b2008-09-03 18:15:37 +00009928 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009929 if (!BSI->ReturnType.isNull())
9930 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009931
Mike Stump56925862009-07-28 22:04:01 +00009932 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009933 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009934
John McCall469a1eb2011-02-02 13:00:07 +00009935 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009936 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9937 SmallVector<BlockDecl::Capture, 4> Captures;
9938 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9939 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9940 if (Cap.isThisCapture())
9941 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009942 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009943 Cap.isNested(), Cap.getCopyExpr());
9944 Captures.push_back(NewCap);
9945 }
9946 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9947 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009948
John McCallc71a4912010-06-04 19:02:56 +00009949 // If the user wrote a function type in some form, try to use that.
9950 if (!BSI->FunctionType.isNull()) {
9951 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9952
9953 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9954 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9955
9956 // Turn protoless block types into nullary block types.
9957 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009958 FunctionProtoType::ExtProtoInfo EPI;
9959 EPI.ExtInfo = Ext;
Dmitri Gribenko55431692013-05-05 00:41:58 +00009960 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009961
9962 // Otherwise, if we don't need to change anything about the function type,
9963 // preserve its sugar structure.
9964 } else if (FTy->getResultType() == RetTy &&
9965 (!NoReturn || FTy->getNoReturnAttr())) {
9966 BlockTy = BSI->FunctionType;
9967
9968 // Otherwise, make the minimal modifications to the function type.
9969 } else {
9970 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009971 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9972 EPI.TypeQuals = 0; // FIXME: silently?
9973 EPI.ExtInfo = Ext;
Jordan Rosebea522f2013-03-08 21:51:21 +00009974 BlockTy =
9975 Context.getFunctionType(RetTy,
9976 ArrayRef<QualType>(FPT->arg_type_begin(),
9977 FPT->getNumArgs()),
9978 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009979 }
9980
9981 // If we don't have a function type, just build one from nothing.
9982 } else {
John McCalle23cf432010-12-14 08:05:40 +00009983 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009984 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko55431692013-05-05 00:41:58 +00009985 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009986 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009987
John McCallc71a4912010-06-04 19:02:56 +00009988 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9989 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009990 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009991
Chris Lattner17a78302009-04-19 05:28:12 +00009992 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009993 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009994 !hasAnyUnrecoverableErrorsInThisFunction() &&
9995 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009996 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009997
Chris Lattnere476bdc2011-02-17 23:58:47 +00009998 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009999
Jordan Rose7dd900e2012-07-02 21:19:23 +000010000 // Try to apply the named return value optimization. We have to check again
10001 // if we can do this, though, because blocks keep return statements around
10002 // to deduce an implicit return type.
10003 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10004 !BSI->TheDecl->isDependentContext())
10005 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +000010006
Benjamin Kramerd2486192011-07-12 14:11:05 +000010007 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10008 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +000010009 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +000010010
John McCall80ee6e82011-11-10 05:35:25 +000010011 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +000010012 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +000010013 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +000010014 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +000010015 ExprCleanupObjects.push_back(Result->getBlockDecl());
10016 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +000010017
10018 // It also gets a branch-protected scope if any of the captured
10019 // variables needs destruction.
10020 for (BlockDecl::capture_const_iterator
10021 ci = Result->getBlockDecl()->capture_begin(),
10022 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10023 const VarDecl *var = ci->getVariable();
10024 if (var->getType().isDestructedType() != QualType::DK_none) {
10025 getCurFunction()->setHasBranchProtectedScope();
10026 break;
10027 }
10028 }
John McCall80ee6e82011-11-10 05:35:25 +000010029 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +000010030
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000010031 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +000010032}
10033
John McCall60d7b3a2010-08-24 06:29:42 +000010034ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +000010035 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +000010036 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +000010037 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +000010038 GetTypeFromParser(Ty, &TInfo);
10039 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +000010040}
10041
John McCall60d7b3a2010-08-24 06:29:42 +000010042ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +000010043 Expr *E, TypeSourceInfo *TInfo,
10044 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +000010045 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +000010046
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010047 // Get the va_list type
10048 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +000010049 if (VaListType->isArrayType()) {
10050 // Deal with implicit array decay; for example, on x86-64,
10051 // va_list is an array, but it's supposed to decay to
10052 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010053 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +000010054 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +000010055 ExprResult Result = UsualUnaryConversions(E);
10056 if (Result.isInvalid())
10057 return ExprError();
10058 E = Result.take();
Logan Chienb687f3b2012-10-20 06:11:33 +000010059 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10060 // If va_list is a record type and we are compiling in C++ mode,
10061 // check the argument using reference binding.
10062 InitializedEntity Entity
10063 = InitializedEntity::InitializeParameter(Context,
10064 Context.getLValueReferenceType(VaListType), false);
10065 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10066 if (Init.isInvalid())
10067 return ExprError();
10068 E = Init.takeAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +000010069 } else {
10070 // Otherwise, the va_list argument must be an l-value because
10071 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +000010072 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +000010073 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +000010074 return ExprError();
10075 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010076
Douglas Gregordd027302009-05-19 23:10:31 +000010077 if (!E->isTypeDependent() &&
10078 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +000010079 return ExprError(Diag(E->getLocStart(),
10080 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +000010081 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +000010082 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010083
David Majnemer0adde122011-06-14 05:17:32 +000010084 if (!TInfo->getType()->isDependentType()) {
10085 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010086 diag::err_second_parameter_to_va_arg_incomplete,
10087 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +000010088 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +000010089
David Majnemer0adde122011-06-14 05:17:32 +000010090 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +000010091 TInfo->getType(),
10092 diag::err_second_parameter_to_va_arg_abstract,
10093 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +000010094 return ExprError();
10095
Douglas Gregor4eb75222011-07-30 06:45:27 +000010096 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +000010097 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +000010098 TInfo->getType()->isObjCLifetimeType()
10099 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10100 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +000010101 << TInfo->getType()
10102 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +000010103 }
Eli Friedman46d37c12011-07-11 21:45:59 +000010104
10105 // Check for va_arg where arguments of the given type will be promoted
10106 // (i.e. this va_arg is guaranteed to have undefined behavior).
10107 QualType PromoteType;
10108 if (TInfo->getType()->isPromotableIntegerType()) {
10109 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10110 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10111 PromoteType = QualType();
10112 }
10113 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10114 PromoteType = Context.DoubleTy;
10115 if (!PromoteType.isNull())
Ted Kremenekcbb99ef2013-01-08 01:50:40 +000010116 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10117 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10118 << TInfo->getType()
10119 << PromoteType
10120 << TInfo->getTypeLoc().getSourceRange());
David Majnemer0adde122011-06-14 05:17:32 +000010121 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010122
Abramo Bagnara2cad9002010-08-10 10:06:15 +000010123 QualType T = TInfo->getType().getNonLValueExprType(Context);
10124 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +000010125}
10126
John McCall60d7b3a2010-08-24 06:29:42 +000010127ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010128 // The type of __null will be int or long, depending on the size of
10129 // pointers on the target.
10130 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010131 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10132 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010133 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010134 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010135 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000010136 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010137 Ty = Context.LongLongTy;
10138 else {
David Blaikieb219cfc2011-09-23 05:06:16 +000010139 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010140 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010141
Sebastian Redlf53597f2009-03-15 17:47:39 +000010142 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010143}
10144
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010145static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +000010146 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010147 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010148 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010149
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010150 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10151 if (!PT)
10152 return;
10153
10154 // Check if the destination is of type 'id'.
10155 if (!PT->isObjCIdType()) {
10156 // Check if the destination is the 'NSString' interface.
10157 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10158 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10159 return;
10160 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010161
John McCall4b9c2d22011-11-06 09:01:30 +000010162 // Ignore any parens, implicit casts (should only be
10163 // array-to-pointer decays), and not-so-opaque values. The last is
10164 // important for making this trigger for property assignments.
10165 SrcExpr = SrcExpr->IgnoreParenImpCasts();
10166 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10167 if (OV->getSourceExpr())
10168 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10169
10170 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +000010171 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010172 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010173
Douglas Gregor849b2432010-03-31 17:46:05 +000010174 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010175}
10176
Chris Lattner5cf216b2008-01-04 18:04:52 +000010177bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10178 SourceLocation Loc,
10179 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +000010180 Expr *SrcExpr, AssignmentAction Action,
10181 bool *Complained) {
10182 if (Complained)
10183 *Complained = false;
10184
Chris Lattner5cf216b2008-01-04 18:04:52 +000010185 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +000010186 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010187 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +000010188 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +000010189 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +000010190 ConversionFixItGenerator ConvHints;
10191 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +000010192 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010193
Chris Lattner5cf216b2008-01-04 18:04:52 +000010194 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +000010195 case Compatible:
Daniel Dunbar7a0c0642012-10-15 22:23:53 +000010196 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10197 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +000010198
Chris Lattnerb7b61152008-01-04 18:22:42 +000010199 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +000010200 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +000010201 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10202 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010203 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010204 case IntToPointer:
10205 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +000010206 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10207 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010208 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010209 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +000010210 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +000010211 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +000010212 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10213 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +000010214 if (Hint.isNull() && !CheckInferredResultType) {
10215 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10216 }
Fariborz Jahanian443adec2013-04-30 00:30:48 +000010217 else if (CheckInferredResultType) {
10218 SrcType = SrcType.getUnqualifiedType();
10219 DstType = DstType.getUnqualifiedType();
10220 }
Anna Zaks67221552011-07-28 19:51:27 +000010221 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010222 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +000010223 case IncompatiblePointerSign:
10224 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10225 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010226 case FunctionVoidPointer:
10227 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10228 break;
John McCall86c05f32011-02-01 00:10:29 +000010229 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +000010230 // Perform array-to-pointer decay if necessary.
10231 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10232
John McCall86c05f32011-02-01 00:10:29 +000010233 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10234 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10235 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10236 DiagKind = diag::err_typecheck_incompatible_address_space;
10237 break;
John McCallf85e1932011-06-15 23:02:42 +000010238
10239
10240 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000010241 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +000010242 break;
John McCall86c05f32011-02-01 00:10:29 +000010243 }
10244
10245 llvm_unreachable("unknown error case for discarding qualifiers!");
10246 // fallthrough
10247 }
Chris Lattner5cf216b2008-01-04 18:04:52 +000010248 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +000010249 // If the qualifiers lost were because we were applying the
10250 // (deprecated) C++ conversion from a string literal to a char*
10251 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10252 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +000010253 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +000010254 // bit of refactoring (so that the second argument is an
10255 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +000010256 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +000010257 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010258 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +000010259 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10260 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010261 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10262 break;
Sean Huntc9132b62009-11-08 07:46:34 +000010263 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +000010264 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +000010265 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010266 case IntToBlockPointer:
10267 DiagKind = diag::err_int_to_block_pointer;
10268 break;
10269 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +000010270 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010271 break;
Steve Naroff39579072008-10-14 22:18:38 +000010272 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +000010273 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +000010274 // it can give a more specific diagnostic.
10275 DiagKind = diag::warn_incompatible_qualified_id;
10276 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +000010277 case IncompatibleVectors:
10278 DiagKind = diag::warn_incompatible_vectors;
10279 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +000010280 case IncompatibleObjCWeakRef:
10281 DiagKind = diag::err_arc_weak_unavailable_assign;
10282 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010283 case Incompatible:
10284 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +000010285 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10286 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010287 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +000010288 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010289 break;
10290 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010291
Douglas Gregord4eea832010-04-09 00:35:39 +000010292 QualType FirstType, SecondType;
10293 switch (Action) {
10294 case AA_Assigning:
10295 case AA_Initializing:
10296 // The destination type comes first.
10297 FirstType = DstType;
10298 SecondType = SrcType;
10299 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010300
Douglas Gregord4eea832010-04-09 00:35:39 +000010301 case AA_Returning:
10302 case AA_Passing:
10303 case AA_Converting:
10304 case AA_Sending:
10305 case AA_Casting:
10306 // The source type comes first.
10307 FirstType = SrcType;
10308 SecondType = DstType;
10309 break;
10310 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010311
Anna Zaks67221552011-07-28 19:51:27 +000010312 PartialDiagnostic FDiag = PDiag(DiagKind);
10313 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10314
10315 // If we can fix the conversion, suggest the FixIts.
10316 assert(ConvHints.isNull() || Hint.isNull());
10317 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +000010318 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10319 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +000010320 FDiag << *HI;
10321 } else {
10322 FDiag << Hint;
10323 }
10324 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10325
Richard Trieu6efd4c52011-11-23 22:32:32 +000010326 if (MayHaveFunctionDiff)
10327 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10328
Anna Zaks67221552011-07-28 19:51:27 +000010329 Diag(Loc, FDiag);
10330
Richard Trieu6efd4c52011-11-23 22:32:32 +000010331 if (SecondType == Context.OverloadTy)
10332 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10333 FirstType);
10334
Douglas Gregor926df6c2011-06-11 01:09:30 +000010335 if (CheckInferredResultType)
10336 EmitRelatedResultTypeNote(SrcExpr);
John McCall7cca8212013-03-19 07:04:25 +000010337
10338 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10339 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor926df6c2011-06-11 01:09:30 +000010340
Douglas Gregora41a8c52010-04-22 00:20:18 +000010341 if (Complained)
10342 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010343 return isInvalid;
10344}
Anders Carlssone21555e2008-11-30 19:50:32 +000010345
Richard Smith282e7e62012-02-04 09:53:13 +000010346ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10347 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010348 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10349 public:
10350 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10351 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10352 }
10353 } Diagnoser;
10354
10355 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10356}
10357
10358ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10359 llvm::APSInt *Result,
10360 unsigned DiagID,
10361 bool AllowFold) {
10362 class IDDiagnoser : public VerifyICEDiagnoser {
10363 unsigned DiagID;
10364
10365 public:
10366 IDDiagnoser(unsigned DiagID)
10367 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10368
10369 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10370 S.Diag(Loc, DiagID) << SR;
10371 }
10372 } Diagnoser(DiagID);
10373
10374 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10375}
10376
10377void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10378 SourceRange SR) {
10379 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +000010380}
10381
Benjamin Kramerd448ce02012-04-18 14:22:41 +000010382ExprResult
10383Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010384 VerifyICEDiagnoser &Diagnoser,
10385 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010386 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +000010387
Richard Smith80ad52f2013-01-02 11:42:31 +000010388 if (getLangOpts().CPlusPlus11) {
Richard Smith282e7e62012-02-04 09:53:13 +000010389 // C++11 [expr.const]p5:
10390 // If an expression of literal class type is used in a context where an
10391 // integral constant expression is required, then that class type shall
10392 // have a single non-explicit conversion function to an integral or
10393 // unscoped enumeration type
10394 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +000010395 if (!Diagnoser.Suppress) {
10396 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10397 public:
10398 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10399
10400 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10401 QualType T) {
10402 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10403 }
10404
10405 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10406 SourceLocation Loc,
10407 QualType T) {
10408 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10409 }
10410
10411 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10412 SourceLocation Loc,
10413 QualType T,
10414 QualType ConvTy) {
10415 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10416 }
10417
10418 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10419 CXXConversionDecl *Conv,
10420 QualType ConvTy) {
10421 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10422 << ConvTy->isEnumeralType() << ConvTy;
10423 }
10424
10425 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10426 QualType T) {
10427 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10428 }
10429
10430 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10431 CXXConversionDecl *Conv,
10432 QualType ConvTy) {
10433 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10434 << ConvTy->isEnumeralType() << ConvTy;
10435 }
10436
10437 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10438 SourceLocation Loc,
10439 QualType T,
10440 QualType ConvTy) {
10441 return DiagnosticBuilder::getEmpty();
10442 }
10443 } ConvertDiagnoser;
10444
10445 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10446 ConvertDiagnoser,
10447 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010448 } else {
10449 // The caller wants to silently enquire whether this is an ICE. Don't
10450 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010451 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10452 public:
10453 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10454
10455 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10456 QualType T) {
10457 return DiagnosticBuilder::getEmpty();
10458 }
10459
10460 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10461 SourceLocation Loc,
10462 QualType T) {
10463 return DiagnosticBuilder::getEmpty();
10464 }
10465
10466 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10467 SourceLocation Loc,
10468 QualType T,
10469 QualType ConvTy) {
10470 return DiagnosticBuilder::getEmpty();
10471 }
10472
10473 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10474 CXXConversionDecl *Conv,
10475 QualType ConvTy) {
10476 return DiagnosticBuilder::getEmpty();
10477 }
10478
10479 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10480 QualType T) {
10481 return DiagnosticBuilder::getEmpty();
10482 }
10483
10484 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10485 CXXConversionDecl *Conv,
10486 QualType ConvTy) {
10487 return DiagnosticBuilder::getEmpty();
10488 }
10489
10490 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10491 SourceLocation Loc,
10492 QualType T,
10493 QualType ConvTy) {
10494 return DiagnosticBuilder::getEmpty();
10495 }
10496 } ConvertDiagnoser;
10497
10498 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10499 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010500 }
10501 if (Converted.isInvalid())
10502 return Converted;
10503 E = Converted.take();
10504 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10505 return ExprError();
10506 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10507 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010508 if (!Diagnoser.Suppress)
10509 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010510 return ExprError();
10511 }
10512
Richard Smithdaaefc52011-12-14 23:32:26 +000010513 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10514 // in the non-ICE case.
Richard Smith80ad52f2013-01-02 11:42:31 +000010515 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010516 if (Result)
10517 *Result = E->EvaluateKnownConstInt(Context);
10518 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010519 }
10520
Anders Carlssone21555e2008-11-30 19:50:32 +000010521 Expr::EvalResult EvalResult;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010522 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010523 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010524
Richard Smithdaaefc52011-12-14 23:32:26 +000010525 // Try to evaluate the expression, and produce diagnostics explaining why it's
10526 // not a constant expression as a side-effect.
10527 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10528 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10529
10530 // In C++11, we can rely on diagnostics being produced for any expression
10531 // which is not a constant expression. If no diagnostics were produced, then
10532 // this is a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +000010533 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010534 if (Result)
10535 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010536 return Owned(E);
10537 }
10538
10539 // If our only note is the usual "invalid subexpression" note, just point
10540 // the caret at its location rather than producing an essentially
10541 // redundant note.
10542 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10543 diag::note_invalid_subexpr_in_const_expr) {
10544 DiagLoc = Notes[0].first;
10545 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010546 }
10547
10548 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010549 if (!Diagnoser.Suppress) {
10550 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010551 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10552 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010553 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010554
Richard Smith282e7e62012-02-04 09:53:13 +000010555 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010556 }
10557
Douglas Gregorab41fe92012-05-04 22:38:52 +000010558 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010559 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10560 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010561
Anders Carlssone21555e2008-11-30 19:50:32 +000010562 if (Result)
10563 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010564 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010565}
Douglas Gregore0762c92009-06-19 23:52:42 +000010566
Eli Friedmanef331b72012-01-20 01:26:23 +000010567namespace {
10568 // Handle the case where we conclude a expression which we speculatively
10569 // considered to be unevaluated is actually evaluated.
10570 class TransformToPE : public TreeTransform<TransformToPE> {
10571 typedef TreeTransform<TransformToPE> BaseTransform;
10572
10573 public:
10574 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10575
10576 // Make sure we redo semantic analysis
10577 bool AlwaysRebuild() { return true; }
10578
Eli Friedman56ff2832012-02-06 23:29:57 +000010579 // Make sure we handle LabelStmts correctly.
10580 // FIXME: This does the right thing, but maybe we need a more general
10581 // fix to TreeTransform?
10582 StmtResult TransformLabelStmt(LabelStmt *S) {
10583 S->getDecl()->setStmt(0);
10584 return BaseTransform::TransformLabelStmt(S);
10585 }
10586
Eli Friedmanef331b72012-01-20 01:26:23 +000010587 // We need to special-case DeclRefExprs referring to FieldDecls which
10588 // are not part of a member pointer formation; normal TreeTransforming
10589 // doesn't catch this case because of the way we represent them in the AST.
10590 // FIXME: This is a bit ugly; is it really the best way to handle this
10591 // case?
10592 //
10593 // Error on DeclRefExprs referring to FieldDecls.
10594 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10595 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010596 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010597 return SemaRef.Diag(E->getLocation(),
10598 diag::err_invalid_non_static_member_use)
10599 << E->getDecl() << E->getSourceRange();
10600
10601 return BaseTransform::TransformDeclRefExpr(E);
10602 }
10603
10604 // Exception: filter out member pointer formation
10605 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10606 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10607 return E;
10608
10609 return BaseTransform::TransformUnaryOperator(E);
10610 }
10611
Douglas Gregore2c59132012-02-09 08:14:43 +000010612 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10613 // Lambdas never need to be transformed.
10614 return E;
10615 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010616 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010617}
10618
Benjamin Krameraccaf192012-11-14 15:08:31 +000010619ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallaeeacf72013-05-03 00:10:13 +000010620 assert(isUnevaluatedContext() &&
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010621 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010622 ExprEvalContexts.back().Context =
10623 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallaeeacf72013-05-03 00:10:13 +000010624 if (isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010625 return E;
10626 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010627}
10628
Douglas Gregor2afce722009-11-26 00:44:06 +000010629void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010630Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010631 Decl *LambdaContextDecl,
10632 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010633 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010634 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010635 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010636 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010637 LambdaContextDecl,
10638 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010639 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010640 if (!MaybeODRUseExprs.empty())
10641 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010642}
10643
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010644void
10645Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10646 ReuseLambdaContextDecl_t,
10647 bool IsDecltype) {
10648 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10649 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10650}
10651
Richard Trieu67e29332011-08-02 04:35:43 +000010652void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010653 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010654
Douglas Gregore2c59132012-02-09 08:14:43 +000010655 if (!Rec.Lambdas.empty()) {
John McCallaeeacf72013-05-03 00:10:13 +000010656 if (Rec.isUnevaluated()) {
Douglas Gregore2c59132012-02-09 08:14:43 +000010657 // C++11 [expr.prim.lambda]p2:
10658 // A lambda-expression shall not appear in an unevaluated operand
10659 // (Clause 5).
10660 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10661 Diag(Rec.Lambdas[I]->getLocStart(),
10662 diag::err_lambda_unevaluated_operand);
10663 } else {
10664 // Mark the capture expressions odr-used. This was deferred
10665 // during lambda expression creation.
10666 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10667 LambdaExpr *Lambda = Rec.Lambdas[I];
10668 for (LambdaExpr::capture_init_iterator
10669 C = Lambda->capture_init_begin(),
10670 CEnd = Lambda->capture_init_end();
10671 C != CEnd; ++C) {
10672 MarkDeclarationsReferencedInExpr(*C);
10673 }
10674 }
10675 }
10676 }
10677
Douglas Gregor2afce722009-11-26 00:44:06 +000010678 // When are coming out of an unevaluated context, clear out any
10679 // temporaries that we may have created as part of the evaluation of
10680 // the expression in that context: they aren't relevant because they
10681 // will never be constructed.
John McCallaeeacf72013-05-03 00:10:13 +000010682 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010683 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10684 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010685 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010686 CleanupVarDeclMarking();
10687 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010688 // Otherwise, merge the contexts together.
10689 } else {
10690 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010691 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10692 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010693 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010694
10695 // Pop the current expression evaluation context off the stack.
10696 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010697}
Douglas Gregore0762c92009-06-19 23:52:42 +000010698
John McCallf85e1932011-06-15 23:02:42 +000010699void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010700 ExprCleanupObjects.erase(
10701 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10702 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010703 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010704 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010705}
10706
Eli Friedman71b8fb52012-01-21 01:01:51 +000010707ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10708 if (!E->getType()->isVariablyModifiedType())
10709 return E;
Benjamin Krameraccaf192012-11-14 15:08:31 +000010710 return TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +000010711}
10712
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010713static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010714 // Do not mark anything as "used" within a dependent context; wait for
10715 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010716 if (SemaRef.CurContext->isDependentContext())
10717 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010718
Eli Friedman5f2987c2012-02-02 03:46:19 +000010719 switch (SemaRef.ExprEvalContexts.back().Context) {
10720 case Sema::Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +000010721 case Sema::UnevaluatedAbstract:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010722 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010723 // (Depending on how you read the standard, we actually do need to do
10724 // something here for null pointer constants, but the standard's
10725 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010726 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010727
Eli Friedman5f2987c2012-02-02 03:46:19 +000010728 case Sema::ConstantEvaluated:
10729 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010730 // We are in a potentially evaluated expression (or a constant-expression
10731 // in C++03); we need to do implicit template instantiation, implicitly
10732 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010733 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010734
Eli Friedman5f2987c2012-02-02 03:46:19 +000010735 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010736 // Referenced declarations will only be used if the construct in the
10737 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010738 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010739 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010740 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010741}
10742
10743/// \brief Mark a function referenced, and check whether it is odr-used
10744/// (C++ [basic.def.odr]p2, C99 6.9p3)
10745void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10746 assert(Func && "No function?");
10747
10748 Func->setReferenced();
10749
Richard Smithce2661f2012-11-07 01:14:25 +000010750 // C++11 [basic.def.odr]p3:
10751 // A function whose name appears as a potentially-evaluated expression is
10752 // odr-used if it is the unique lookup result or the selected member of a
10753 // set of overloaded functions [...].
10754 //
10755 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10756 // can just check that here. Skip the rest of this function if we've already
10757 // marked the function as used.
10758 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10759 // C++11 [temp.inst]p3:
10760 // Unless a function template specialization has been explicitly
10761 // instantiated or explicitly specialized, the function template
10762 // specialization is implicitly instantiated when the specialization is
10763 // referenced in a context that requires a function definition to exist.
10764 //
10765 // We consider constexpr function templates to be referenced in a context
10766 // that requires a definition to exist whenever they are referenced.
10767 //
10768 // FIXME: This instantiates constexpr functions too frequently. If this is
10769 // really an unevaluated context (and we're not just in the definition of a
10770 // function template or overload resolution or other cases which we
10771 // incorrectly consider to be unevaluated contexts), and we're not in a
10772 // subexpression which we actually need to evaluate (for instance, a
10773 // template argument, array bound or an expression in a braced-init-list),
10774 // we are not permitted to instantiate this constexpr function definition.
10775 //
10776 // FIXME: This also implicitly defines special members too frequently. They
10777 // are only supposed to be implicitly defined if they are odr-used, but they
10778 // are not odr-used from constant expressions in unevaluated contexts.
10779 // However, they cannot be referenced if they are deleted, and they are
10780 // deleted whenever the implicit definition of the special member would
10781 // fail.
10782 if (!Func->isConstexpr() || Func->getBody())
10783 return;
10784 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10785 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10786 return;
10787 }
Mike Stump1eb44332009-09-09 15:08:12 +000010788
Douglas Gregore0762c92009-06-19 23:52:42 +000010789 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010790 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010791 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010792 if (Constructor->isDefaultConstructor()) {
10793 if (Constructor->isTrivial())
10794 return;
10795 if (!Constructor->isUsed(false))
10796 DefineImplicitDefaultConstructor(Loc, Constructor);
10797 } else if (Constructor->isCopyConstructor()) {
10798 if (!Constructor->isUsed(false))
10799 DefineImplicitCopyConstructor(Loc, Constructor);
10800 } else if (Constructor->isMoveConstructor()) {
10801 if (!Constructor->isUsed(false))
10802 DefineImplicitMoveConstructor(Loc, Constructor);
10803 }
Richard Smith07b0fdc2013-03-18 21:12:30 +000010804 } else if (Constructor->getInheritedConstructor()) {
10805 if (!Constructor->isUsed(false))
10806 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010807 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010808
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010809 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010810 } else if (CXXDestructorDecl *Destructor =
10811 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010812 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10813 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010814 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010815 if (Destructor->isVirtual())
10816 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010817 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010818 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10819 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010820 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010821 if (!MethodDecl->isUsed(false)) {
10822 if (MethodDecl->isCopyAssignmentOperator())
10823 DefineImplicitCopyAssignment(Loc, MethodDecl);
10824 else
10825 DefineImplicitMoveAssignment(Loc, MethodDecl);
10826 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010827 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10828 MethodDecl->getParent()->isLambda()) {
10829 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10830 if (Conversion->isLambdaToBlockPointerConversion())
10831 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10832 else
10833 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010834 } else if (MethodDecl->isVirtual())
10835 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010836 }
John McCall15e310a2011-02-19 02:53:41 +000010837
Eli Friedman5f2987c2012-02-02 03:46:19 +000010838 // Recursive functions should be marked when used from another function.
10839 // FIXME: Is this really right?
10840 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010841
Richard Smithb9d0b762012-07-27 04:22:15 +000010842 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010843 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010844 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010845 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10846 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010847
Eli Friedman5f2987c2012-02-02 03:46:19 +000010848 // Implicit instantiation of function templates and member functions of
10849 // class templates.
10850 if (Func->isImplicitlyInstantiable()) {
10851 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010852 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010853 if (FunctionTemplateSpecializationInfo *SpecInfo
10854 = Func->getTemplateSpecializationInfo()) {
10855 if (SpecInfo->getPointOfInstantiation().isInvalid())
10856 SpecInfo->setPointOfInstantiation(Loc);
10857 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010858 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010859 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010860 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10861 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010862 } else if (MemberSpecializationInfo *MSInfo
10863 = Func->getMemberSpecializationInfo()) {
10864 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010865 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010866 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010867 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010868 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010869 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10870 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010871 }
Mike Stump1eb44332009-09-09 15:08:12 +000010872
Richard Smith57b9c4e2012-02-14 22:25:15 +000010873 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010874 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10875 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010876 PendingLocalImplicitInstantiations.push_back(
10877 std::make_pair(Func, PointOfInstantiation));
10878 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010879 // Do not defer instantiations of constexpr functions, to avoid the
10880 // expression evaluator needing to call back into Sema if it sees a
10881 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010882 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010883 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010884 PendingInstantiations.push_back(std::make_pair(Func,
10885 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010886 // Notify the consumer that a function was implicitly instantiated.
10887 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10888 }
John McCall15e310a2011-02-19 02:53:41 +000010889 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010890 } else {
10891 // Walk redefinitions, as some of them may be instantiable.
10892 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10893 e(Func->redecls_end()); i != e; ++i) {
10894 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10895 MarkFunctionReferenced(Loc, *i);
10896 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010897 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010898
10899 // Keep track of used but undefined functions.
Nick Lewyckycd0655b2013-02-01 08:13:20 +000010900 if (!Func->isDefined()) {
Rafael Espindola2d1b0962013-03-14 03:07:35 +000010901 if (mightHaveNonExternalLinkage(Func))
Nick Lewyckycd0655b2013-02-01 08:13:20 +000010902 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10903 else if (Func->getMostRecentDecl()->isInlined() &&
10904 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10905 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10906 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010907 }
10908
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010909 // Normally the must current decl is marked used while processing the use and
10910 // any subsequent decls are marked used by decl merging. This fails with
10911 // template instantiation since marking can happen at the end of the file
10912 // and, because of the two phase lookup, this function is called with at
10913 // decl in the middle of a decl chain. We loop to maintain the invariant
10914 // that once a decl is used, all decls after it are also used.
Rafael Espindolaa6d20202013-01-08 19:58:34 +000010915 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010916 F->setUsed(true);
10917 if (F == Func)
10918 break;
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010919 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010920}
10921
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010922static void
10923diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10924 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010925 DeclContext *VarDC = var->getDeclContext();
10926
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010927 // If the parameter still belongs to the translation unit, then
10928 // we're actually just using one parameter in the declaration of
10929 // the next.
10930 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010931 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010932 return;
10933
Eli Friedman0a294222012-02-07 00:15:00 +000010934 // For C code, don't diagnose about capture if we're not actually in code
10935 // right now; it's impossible to write a non-constant expression outside of
10936 // function context, so we'll get other (more useful) diagnostics later.
10937 //
10938 // For C++, things get a bit more nasty... it would be nice to suppress this
10939 // diagnostic for certain cases like using a local variable in an array bound
10940 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010941 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010942 return;
10943
Eli Friedman0a294222012-02-07 00:15:00 +000010944 if (isa<CXXMethodDecl>(VarDC) &&
10945 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10946 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10947 << var->getIdentifier();
10948 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10949 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10950 << var->getIdentifier() << fn->getDeclName();
10951 } else if (isa<BlockDecl>(VarDC)) {
10952 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10953 << var->getIdentifier();
10954 } else {
10955 // FIXME: Is there any other context where a local variable can be
10956 // declared?
10957 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10958 << var->getIdentifier();
10959 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010960
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010961 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10962 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010963
10964 // FIXME: Add additional diagnostic info about class etc. which prevents
10965 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010966}
10967
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000010968/// \brief Capture the given variable in the captured region.
10969static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI,
10970 VarDecl *Var, QualType FieldType,
10971 QualType DeclRefType,
10972 SourceLocation Loc,
10973 bool RefersToEnclosingLocal) {
10974 // The current implemention assumes that all variables are captured
10975 // by references. Since there is no capture by copy, no expression evaluation
10976 // will be needed.
10977 //
10978 RecordDecl *RD = RSI->TheRecordDecl;
10979
10980 FieldDecl *Field
10981 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType,
10982 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10983 0, false, ICIS_NoInit);
10984 Field->setImplicit(true);
10985 Field->setAccess(AS_private);
10986 RD->addDecl(Field);
10987
10988 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10989 DeclRefType, VK_LValue, Loc);
10990 Var->setReferenced(true);
10991 Var->setUsed(true);
10992
10993 return Ref;
10994}
10995
Douglas Gregorf8af9822012-02-12 18:42:33 +000010996/// \brief Capture the given variable in the given lambda expression.
10997static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010998 VarDecl *Var, QualType FieldType,
10999 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000011000 SourceLocation Loc,
11001 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000011002 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000011003
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011004 // Build the non-static data member.
11005 FieldDecl *Field
11006 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11007 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000011008 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011009 Field->setImplicit(true);
11010 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000011011 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011012
11013 // C++11 [expr.prim.lambda]p21:
11014 // When the lambda-expression is evaluated, the entities that
11015 // are captured by copy are used to direct-initialize each
11016 // corresponding non-static data member of the resulting closure
11017 // object. (For array members, the array elements are
11018 // direct-initialized in increasing subscript order.) These
11019 // initializations are performed in the (unspecified) order in
11020 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011021
Douglas Gregore2c59132012-02-09 08:14:43 +000011022 // Introduce a new evaluation context for the initialization, so
11023 // that temporaries introduced as part of the capture are retained
11024 // to be re-"exported" from the lambda expression itself.
John McCallb760f112013-03-22 02:10:40 +000011025 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011026
Douglas Gregor73d90922012-02-10 09:26:04 +000011027 // C++ [expr.prim.labda]p12:
11028 // An entity captured by a lambda-expression is odr-used (3.2) in
11029 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000011030 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11031 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000011032 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000011033 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000011034
11035 // When the field has array type, create index variables for each
11036 // dimension of the array. We use these index variables to subscript
11037 // the source array, and other clients (e.g., CodeGen) will perform
11038 // the necessary iteration with these index variables.
11039 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000011040 QualType BaseType = FieldType;
11041 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000011042 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000011043 while (const ConstantArrayType *Array
11044 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000011045 // Create the iteration variable for this array index.
11046 IdentifierInfo *IterationVarName = 0;
11047 {
11048 SmallString<8> Str;
11049 llvm::raw_svector_ostream OS(Str);
11050 OS << "__i" << IndexVariables.size();
11051 IterationVarName = &S.Context.Idents.get(OS.str());
11052 }
11053 VarDecl *IterationVar
11054 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11055 IterationVarName, SizeType,
11056 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011057 SC_None);
Douglas Gregor18fe0842012-02-09 02:45:47 +000011058 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000011059 LSI->ArrayIndexVars.push_back(IterationVar);
11060
Douglas Gregor18fe0842012-02-09 02:45:47 +000011061 // Create a reference to the iteration variable.
11062 ExprResult IterationVarRef
11063 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11064 assert(!IterationVarRef.isInvalid() &&
11065 "Reference to invented variable cannot fail!");
11066 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11067 assert(!IterationVarRef.isInvalid() &&
11068 "Conversion of invented variable cannot fail!");
11069
11070 // Subscript the array with this iteration variable.
11071 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11072 Ref, Loc, IterationVarRef.take(), Loc);
11073 if (Subscript.isInvalid()) {
11074 S.CleanupVarDeclMarking();
11075 S.DiscardCleanupsInEvaluationContext();
Douglas Gregor18fe0842012-02-09 02:45:47 +000011076 return ExprError();
11077 }
11078
11079 Ref = Subscript.take();
11080 BaseType = Array->getElementType();
11081 }
11082
11083 // Construct the entity that we will be initializing. For an array, this
11084 // will be first element in the array, which may require several levels
11085 // of array-subscript entities.
11086 SmallVector<InitializedEntity, 4> Entities;
11087 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000011088 Entities.push_back(
11089 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000011090 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11091 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11092 0,
11093 Entities.back()));
11094
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011095 InitializationKind InitKind
11096 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011097 InitializationSequence Init(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011098 ExprResult Result(true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011099 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
Benjamin Kramer5354e772012-08-23 23:38:35 +000011100 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011101
11102 // If this initialization requires any cleanups (e.g., due to a
11103 // default argument to a copy constructor), note that for the
11104 // lambda.
11105 if (S.ExprNeedsCleanups)
11106 LSI->ExprNeedsCleanups = true;
11107
11108 // Exit the expression evaluation context used for the capture.
11109 S.CleanupVarDeclMarking();
11110 S.DiscardCleanupsInEvaluationContext();
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011111 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000011112}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000011113
Douglas Gregor999713e2012-02-18 09:37:24 +000011114bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11115 TryCaptureKind Kind, SourceLocation EllipsisLoc,
11116 bool BuildAndDiagnose,
11117 QualType &CaptureType,
11118 QualType &DeclRefType) {
11119 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000011120
Eli Friedmanb942cb22012-02-03 22:47:37 +000011121 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000011122 if (Var->getDeclContext() == DC) return true;
11123 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011124
Douglas Gregorf8af9822012-02-12 18:42:33 +000011125 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011126
Douglas Gregor999713e2012-02-18 09:37:24 +000011127 // Walk up the stack to determine whether we can capture the variable,
11128 // performing the "simple" checks that don't depend on type. We stop when
11129 // we've either hit the declared scope of the variable or find an existing
11130 // capture of that variable.
11131 CaptureType = Var->getType();
11132 DeclRefType = CaptureType.getNonReferenceType();
11133 bool Explicit = (Kind != TryCapture_Implicit);
11134 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011135 do {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000011136 // Only block literals, captured statements, and lambda expressions can
11137 // capture; other scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000011138 DeclContext *ParentDC;
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000011139 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
Eli Friedmanb942cb22012-02-03 22:47:37 +000011140 ParentDC = DC->getParent();
11141 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000011142 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000011143 cast<CXXRecordDecl>(DC->getParent())->isLambda())
11144 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000011145 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000011146 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000011147 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000011148 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000011149 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011150
Eli Friedmanb942cb22012-02-03 22:47:37 +000011151 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000011152 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011153
Eli Friedmanb942cb22012-02-03 22:47:37 +000011154 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000011155 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000011156 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011157 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000011158
11159 // Retrieve the capture type for this variable.
11160 CaptureType = CSI->getCapture(Var).getCaptureType();
11161
11162 // Compute the type of an expression that refers to this variable.
11163 DeclRefType = CaptureType.getNonReferenceType();
11164
11165 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11166 if (Cap.isCopyCapture() &&
11167 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11168 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011169 break;
11170 }
11171
Douglas Gregorf8af9822012-02-12 18:42:33 +000011172 bool IsBlock = isa<BlockScopeInfo>(CSI);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000011173 bool IsLambda = isa<LambdaScopeInfo>(CSI);
Eli Friedmanb942cb22012-02-03 22:47:37 +000011174
11175 // Lambdas are not allowed to capture unnamed variables
11176 // (e.g. anonymous unions).
11177 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11178 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000011179 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000011180 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000011181 Diag(Loc, diag::err_lambda_capture_anonymous_var);
11182 Diag(Var->getLocation(), diag::note_declared_at);
11183 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011184 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000011185 }
11186
11187 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000011188 if (Var->getType()->isVariablyModifiedType()) {
11189 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000011190 if (IsBlock)
11191 Diag(Loc, diag::err_ref_vm_type);
11192 else
11193 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11194 Diag(Var->getLocation(), diag::note_previous_decl)
11195 << Var->getDeclName();
11196 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011197 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011198 }
Fariborz Jahanianb20eb102013-01-08 23:48:48 +000011199 // Prohibit structs with flexible array members too.
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000011200 // We cannot capture what is in the tail end of the struct.
11201 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
Fariborz Jahaniane178e702013-01-09 00:09:15 +000011202 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000011203 if (BuildAndDiagnose) {
11204 if (IsBlock)
11205 Diag(Loc, diag::err_ref_flexarray_type);
Fariborz Jahaniane178e702013-01-09 00:09:15 +000011206 else
11207 Diag(Loc, diag::err_lambda_capture_flexarray_type)
11208 << Var->getDeclName();
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000011209 Diag(Var->getLocation(), diag::note_previous_decl)
11210 << Var->getDeclName();
11211 }
11212 return true;
11213 }
11214 }
Eli Friedmanb942cb22012-02-03 22:47:37 +000011215 // Lambdas are not allowed to capture __block variables; they don't
11216 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000011217 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000011218 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000011219 Diag(Loc, diag::err_lambda_capture_block)
11220 << Var->getDeclName();
11221 Diag(Var->getLocation(), diag::note_previous_decl)
11222 << Var->getDeclName();
11223 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011224 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000011225 }
11226
Douglas Gregorf8af9822012-02-12 18:42:33 +000011227 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11228 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000011229 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000011230 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11231 Diag(Var->getLocation(), diag::note_previous_decl)
11232 << Var->getDeclName();
11233 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11234 diag::note_lambda_decl);
11235 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011236 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000011237 }
11238
11239 FunctionScopesIndex--;
11240 DC = ParentDC;
11241 Explicit = false;
11242 } while (!Var->getDeclContext()->Equals(DC));
11243
Douglas Gregor999713e2012-02-18 09:37:24 +000011244 // Walk back down the scope stack, computing the type of the capture at
11245 // each step, checking type-specific requirements, and adding captures if
11246 // requested.
11247 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11248 ++I) {
11249 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000011250
Douglas Gregor999713e2012-02-18 09:37:24 +000011251 // Compute the type of the capture and of a reference to the capture within
11252 // this scope.
11253 if (isa<BlockScopeInfo>(CSI)) {
11254 Expr *CopyExpr = 0;
11255 bool ByRef = false;
11256
11257 // Blocks are not allowed to capture arrays.
11258 if (CaptureType->isArrayType()) {
11259 if (BuildAndDiagnose) {
11260 Diag(Loc, diag::err_ref_array_type);
11261 Diag(Var->getLocation(), diag::note_previous_decl)
11262 << Var->getDeclName();
11263 }
11264 return true;
11265 }
11266
John McCall100c6492012-03-30 05:23:48 +000011267 // Forbid the block-capture of autoreleasing variables.
11268 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11269 if (BuildAndDiagnose) {
11270 Diag(Loc, diag::err_arc_autoreleasing_capture)
11271 << /*block*/ 0;
11272 Diag(Var->getLocation(), diag::note_previous_decl)
11273 << Var->getDeclName();
11274 }
11275 return true;
11276 }
11277
Douglas Gregor999713e2012-02-18 09:37:24 +000011278 if (HasBlocksAttr || CaptureType->isReferenceType()) {
11279 // Block capture by reference does not change the capture or
11280 // declaration reference types.
11281 ByRef = true;
11282 } else {
11283 // Block capture by copy introduces 'const'.
11284 CaptureType = CaptureType.getNonReferenceType().withConst();
11285 DeclRefType = CaptureType;
11286
David Blaikie4e4d0842012-03-11 07:00:24 +000011287 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000011288 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11289 // The capture logic needs the destructor, so make sure we mark it.
11290 // Usually this is unnecessary because most local variables have
11291 // their destructors marked at declaration time, but parameters are
11292 // an exception because it's technically only the call site that
11293 // actually requires the destructor.
11294 if (isa<ParmVarDecl>(Var))
11295 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor464a01a2012-12-01 01:01:09 +000011296
John McCallb760f112013-03-22 02:10:40 +000011297 // Enter a new evaluation context to insulate the copy
11298 // full-expression.
11299 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11300
Douglas Gregor999713e2012-02-18 09:37:24 +000011301 // According to the blocks spec, the capture of a variable from
11302 // the stack requires a const copy constructor. This is not true
11303 // of the copy/move done to move a __block variable to the heap.
Douglas Gregor464a01a2012-12-01 01:01:09 +000011304 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
Douglas Gregor999713e2012-02-18 09:37:24 +000011305 DeclRefType.withConst(),
11306 VK_LValue, Loc);
Douglas Gregor464a01a2012-12-01 01:01:09 +000011307
Douglas Gregor999713e2012-02-18 09:37:24 +000011308 ExprResult Result
11309 = PerformCopyInitialization(
11310 InitializedEntity::InitializeBlock(Var->getLocation(),
11311 CaptureType, false),
11312 Loc, Owned(DeclRef));
11313
11314 // Build a full-expression copy expression if initialization
11315 // succeeded and used a non-trivial constructor. Recover from
11316 // errors by pretending that the copy isn't necessary.
11317 if (!Result.isInvalid() &&
11318 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11319 ->isTrivial()) {
11320 Result = MaybeCreateExprWithCleanups(Result);
11321 CopyExpr = Result.take();
11322 }
11323 }
11324 }
11325 }
11326
11327 // Actually capture the variable.
11328 if (BuildAndDiagnose)
11329 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11330 SourceLocation(), CaptureType, CopyExpr);
11331 Nested = true;
11332 continue;
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000011333 }
11334
11335 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11336 // By default, capture variables by reference.
11337 bool ByRef = true;
11338 // Using an LValue reference type is consistent with Lambdas (see below).
11339 CaptureType = Context.getLValueReferenceType(DeclRefType);
11340
11341 Expr *CopyExpr = 0;
11342 if (BuildAndDiagnose) {
11343 ExprResult Result = captureInCapturedRegion(*this, RSI, Var,
11344 CaptureType, DeclRefType,
11345 Loc, Nested);
11346 if (!Result.isInvalid())
11347 CopyExpr = Result.take();
11348 }
11349
11350 // Actually capture the variable.
11351 if (BuildAndDiagnose)
11352 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc,
11353 SourceLocation(), CaptureType, CopyExpr);
11354 Nested = true;
11355 continue;
11356 }
11357
Douglas Gregor999713e2012-02-18 09:37:24 +000011358 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11359
11360 // Determine whether we are capturing by reference or by value.
11361 bool ByRef = false;
11362 if (I == N - 1 && Kind != TryCapture_Implicit) {
11363 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000011364 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000011365 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000011366 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011367
11368 // Compute the type of the field that will capture this variable.
11369 if (ByRef) {
11370 // C++11 [expr.prim.lambda]p15:
11371 // An entity is captured by reference if it is implicitly or
11372 // explicitly captured but not captured by copy. It is
11373 // unspecified whether additional unnamed non-static data
11374 // members are declared in the closure type for entities
11375 // captured by reference.
11376 //
11377 // FIXME: It is not clear whether we want to build an lvalue reference
11378 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11379 // to do the former, while EDG does the latter. Core issue 1249 will
11380 // clarify, but for now we follow GCC because it's a more permissive and
11381 // easily defensible position.
11382 CaptureType = Context.getLValueReferenceType(DeclRefType);
11383 } else {
11384 // C++11 [expr.prim.lambda]p14:
11385 // For each entity captured by copy, an unnamed non-static
11386 // data member is declared in the closure type. The
11387 // declaration order of these members is unspecified. The type
11388 // of such a data member is the type of the corresponding
11389 // captured entity if the entity is not a reference to an
11390 // object, or the referenced type otherwise. [Note: If the
11391 // captured entity is a reference to a function, the
11392 // corresponding data member is also a reference to a
11393 // function. - end note ]
11394 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11395 if (!RefType->getPointeeType()->isFunctionType())
11396 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011397 }
John McCall100c6492012-03-30 05:23:48 +000011398
11399 // Forbid the lambda copy-capture of autoreleasing variables.
11400 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11401 if (BuildAndDiagnose) {
11402 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11403 Diag(Var->getLocation(), diag::note_previous_decl)
11404 << Var->getDeclName();
11405 }
11406 return true;
11407 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011408 }
11409
Douglas Gregor999713e2012-02-18 09:37:24 +000011410 // Capture this variable in the lambda.
11411 Expr *CopyExpr = 0;
11412 if (BuildAndDiagnose) {
11413 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000011414 DeclRefType, Loc,
Douglas Gregor464a01a2012-12-01 01:01:09 +000011415 Nested);
Douglas Gregor999713e2012-02-18 09:37:24 +000011416 if (!Result.isInvalid())
11417 CopyExpr = Result.take();
11418 }
11419
11420 // Compute the type of a reference to this captured variable.
11421 if (ByRef)
11422 DeclRefType = CaptureType.getNonReferenceType();
11423 else {
11424 // C++ [expr.prim.lambda]p5:
11425 // The closure type for a lambda-expression has a public inline
11426 // function call operator [...]. This function call operator is
11427 // declared const (9.3.1) if and only if the lambda-expression’s
11428 // parameter-declaration-clause is not followed by mutable.
11429 DeclRefType = CaptureType.getNonReferenceType();
11430 if (!LSI->Mutable && !CaptureType->isReferenceType())
11431 DeclRefType.addConst();
11432 }
11433
11434 // Add the capture.
11435 if (BuildAndDiagnose)
11436 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11437 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011438 Nested = true;
11439 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011440
11441 return false;
11442}
11443
11444bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11445 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11446 QualType CaptureType;
11447 QualType DeclRefType;
11448 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11449 /*BuildAndDiagnose=*/true, CaptureType,
11450 DeclRefType);
11451}
11452
11453QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11454 QualType CaptureType;
11455 QualType DeclRefType;
11456
11457 // Determine whether we can capture this variable.
11458 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11459 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11460 return QualType();
11461
11462 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011463}
11464
Eli Friedmand2cce132012-02-02 23:15:15 +000011465static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11466 SourceLocation Loc) {
11467 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000011468 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011469 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000011470 Var->getLinkage() != ExternalLinkage &&
11471 !(Var->isStaticDataMember() && Var->hasInit())) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +000011472 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
Eli Friedmand2cce132012-02-02 23:15:15 +000011473 if (old.isInvalid()) old = Loc;
11474 }
11475
Douglas Gregor999713e2012-02-18 09:37:24 +000011476 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011477
Eli Friedmand2cce132012-02-02 23:15:15 +000011478 Var->setUsed(true);
11479}
11480
11481void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11482 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11483 // an object that satisfies the requirements for appearing in a
11484 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11485 // is immediately applied." This function handles the lvalue-to-rvalue
11486 // conversion part.
11487 MaybeODRUseExprs.erase(E->IgnoreParens());
11488}
11489
Eli Friedmanac626012012-02-29 03:16:56 +000011490ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11491 if (!Res.isUsable())
11492 return Res;
11493
11494 // If a constant-expression is a reference to a variable where we delay
11495 // deciding whether it is an odr-use, just assume we will apply the
11496 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11497 // (a non-type template argument), we have special handling anyway.
11498 UpdateMarkingForLValueToRValue(Res.get());
11499 return Res;
11500}
11501
Eli Friedmand2cce132012-02-02 23:15:15 +000011502void Sema::CleanupVarDeclMarking() {
11503 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11504 e = MaybeODRUseExprs.end();
11505 i != e; ++i) {
11506 VarDecl *Var;
11507 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000011508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011509 Var = cast<VarDecl>(DRE->getDecl());
11510 Loc = DRE->getLocation();
11511 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11512 Var = cast<VarDecl>(ME->getMemberDecl());
11513 Loc = ME->getMemberLoc();
11514 } else {
11515 llvm_unreachable("Unexpcted expression");
11516 }
11517
11518 MarkVarDeclODRUsed(*this, Var, Loc);
11519 }
11520
11521 MaybeODRUseExprs.clear();
11522}
11523
11524// Mark a VarDecl referenced, and perform the necessary handling to compute
11525// odr-uses.
11526static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11527 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011528 Var->setReferenced();
11529
Eli Friedmand2cce132012-02-02 23:15:15 +000011530 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011531 return;
11532
11533 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000011534 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011535 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11536 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000011537 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11538 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011539 (!AlreadyInstantiated ||
11540 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000011541 if (!AlreadyInstantiated) {
11542 // This is a modification of an existing AST node. Notify listeners.
11543 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11544 L->StaticDataMemberInstantiated(Var);
11545 MSInfo->setPointOfInstantiation(Loc);
11546 }
11547 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011548 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011549 // Do not defer instantiations of variables which could be used in a
11550 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011551 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011552 else
Richard Smith37ce0102012-02-15 02:42:50 +000011553 SemaRef.PendingInstantiations.push_back(
11554 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011555 }
11556 }
11557
Richard Smith5016a702012-10-20 01:38:33 +000011558 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11559 // the requirements for appearing in a constant expression (5.19) and, if
11560 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000011561 // is immediately applied." We check the first part here, and
11562 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11563 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000011564 // C++03 depends on whether we get the C++03 version correct. The second
11565 // part does not apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011566 const VarDecl *DefVD;
Richard Smith5016a702012-10-20 01:38:33 +000011567 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011568 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5016a702012-10-20 01:38:33 +000011569 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11570 if (!Var->getType()->isReferenceType())
11571 SemaRef.MaybeODRUseExprs.insert(E);
11572 } else
Eli Friedmand2cce132012-02-02 23:15:15 +000011573 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11574}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011575
Eli Friedmand2cce132012-02-02 23:15:15 +000011576/// \brief Mark a variable referenced, and check whether it is odr-used
11577/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11578/// used directly for normal expressions referring to VarDecl.
11579void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11580 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011581}
11582
11583static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011584 Decl *D, Expr *E, bool OdrUse) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011585 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11586 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11587 return;
11588 }
11589
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011590 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011591
11592 // If this is a call to a method via a cast, also mark the method in the
11593 // derived class used in case codegen can devirtualize the call.
11594 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11595 if (!ME)
11596 return;
11597 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11598 if (!MD)
11599 return;
11600 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011601 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011602 if (!MostDerivedClassDecl)
11603 return;
11604 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyd3b4f0e2013-02-14 00:55:17 +000011605 if (!DM || DM->isPure())
Rafael Espindola0713d992012-06-27 17:44:39 +000011606 return;
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011607 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011608}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011609
Eli Friedman5f2987c2012-02-02 03:46:19 +000011610/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11611void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011612 // TODO: update this with DR# once a defect report is filed.
11613 // C++11 defect. The address of a pure member should not be an ODR use, even
11614 // if it's a qualified reference.
11615 bool OdrUse = true;
11616 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky7cea1482013-02-05 06:20:31 +000011617 if (Method->isVirtual())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011618 OdrUse = false;
11619 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011620}
11621
11622/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11623void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky869709c2013-01-31 03:15:20 +000011624 // C++11 [basic.def.odr]p2:
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011625 // A non-overloaded function whose name appears as a potentially-evaluated
11626 // expression or a member of a set of candidate functions, if selected by
11627 // overload resolution when referred to from a potentially-evaluated
11628 // expression, is odr-used, unless it is a pure virtual function and its
11629 // name is not explicitly qualified.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011630 bool OdrUse = true;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011631 if (!E->hasQualifier()) {
11632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11633 if (Method->isPure())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011634 OdrUse = false;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011635 }
Nick Lewycky3c86a5c2013-02-12 08:08:54 +000011636 SourceLocation Loc = E->getMemberLoc().isValid() ?
11637 E->getMemberLoc() : E->getLocStart();
11638 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011639}
11640
Douglas Gregor73d90922012-02-10 09:26:04 +000011641/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011642/// marks the declaration referenced, and performs odr-use checking for functions
11643/// and variables. This method should not be used when building an normal
11644/// expression which refers to a variable.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011645void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11646 if (OdrUse) {
11647 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11648 MarkVariableReferenced(Loc, VD);
11649 return;
11650 }
11651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11652 MarkFunctionReferenced(Loc, FD);
11653 return;
11654 }
11655 }
11656 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011657}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011658
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011659namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011660 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011661 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011662 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011663 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11664 Sema &S;
11665 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011666
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011667 public:
11668 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011669
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011670 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011671
11672 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11673 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011674 };
11675}
11676
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011677bool MarkReferencedDecls::TraverseTemplateArgument(
11678 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011679 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011680 if (Decl *D = Arg.getAsDecl())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011681 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011682 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011683
11684 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011685}
11686
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011687bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011688 if (ClassTemplateSpecializationDecl *Spec
11689 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11690 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011691 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011692 }
11693
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011694 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011695}
11696
11697void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11698 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011699 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011700}
11701
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011702namespace {
11703 /// \brief Helper class that marks all of the declarations referenced by
11704 /// potentially-evaluated subexpressions as "referenced".
11705 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11706 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011707 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011708
11709 public:
11710 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11711
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011712 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11713 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011714
11715 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011716 // If we were asked not to visit local variables, don't.
11717 if (SkipLocalVariables) {
11718 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11719 if (VD->hasLocalStorage())
11720 return;
11721 }
11722
Eli Friedman5f2987c2012-02-02 03:46:19 +000011723 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011724 }
11725
11726 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011727 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011728 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011729 }
11730
John McCall80ee6e82011-11-10 05:35:25 +000011731 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011732 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011733 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11734 Visit(E->getSubExpr());
11735 }
11736
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011737 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011738 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011739 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011740 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011741 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011742 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011743 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011744
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011745 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11746 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011747 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011748 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11749 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11750 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011751 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011752 S.LookupDestructor(Record));
11753 }
11754
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011755 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011756 }
11757
11758 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011759 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011760 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011761 }
11762
Douglas Gregor102ff972010-10-19 17:17:35 +000011763 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11764 Visit(E->getExpr());
11765 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011766
11767 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11768 Inherited::VisitImplicitCastExpr(E);
11769
11770 if (E->getCastKind() == CK_LValueToRValue)
11771 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11772 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011773 };
11774}
11775
11776/// \brief Mark any declarations that appear within this expression or any
11777/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011778///
11779/// \param SkipLocalVariables If true, don't mark local variables as
11780/// 'referenced'.
11781void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11782 bool SkipLocalVariables) {
11783 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011784}
11785
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011786/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11787/// of the program being compiled.
11788///
11789/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011790/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011791/// possibility that the code will actually be executable. Code in sizeof()
11792/// expressions, code used only during overload resolution, etc., are not
11793/// potentially evaluated. This routine will suppress such diagnostics or,
11794/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011795/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011796/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011797///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011798/// This routine should be used for all diagnostics that describe the run-time
11799/// behavior of a program, such as passing a non-POD value through an ellipsis.
11800/// Failure to do so will likely result in spurious diagnostics or failures
11801/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011802bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011803 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011804 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011805 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +000011806 case UnevaluatedAbstract:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011807 // The argument will never be evaluated, so don't complain.
11808 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011809
Richard Smithf6702a32011-12-20 02:08:33 +000011810 case ConstantEvaluated:
11811 // Relevant diagnostics should be produced by constant evaluation.
11812 break;
11813
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011814 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011815 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011816 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011817 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011818 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011819 }
11820 else
11821 Diag(Loc, PD);
11822
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011823 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011824 }
11825
11826 return false;
11827}
11828
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011829bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11830 CallExpr *CE, FunctionDecl *FD) {
11831 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11832 return false;
11833
Richard Smith76f3f692012-02-22 02:04:18 +000011834 // If we're inside a decltype's expression, don't check for a valid return
11835 // type or construct temporaries until we know whether this is the last call.
11836 if (ExprEvalContexts.back().IsDecltype) {
11837 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11838 return false;
11839 }
11840
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011841 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011842 FunctionDecl *FD;
11843 CallExpr *CE;
11844
11845 public:
11846 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11847 : FD(FD), CE(CE) { }
11848
11849 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11850 if (!FD) {
11851 S.Diag(Loc, diag::err_call_incomplete_return)
11852 << T << CE->getSourceRange();
11853 return;
11854 }
11855
11856 S.Diag(Loc, diag::err_call_function_incomplete_return)
11857 << CE->getSourceRange() << FD->getDeclName() << T;
11858 S.Diag(FD->getLocation(),
11859 diag::note_function_with_incomplete_return_type_declared_here)
11860 << FD->getDeclName();
11861 }
11862 } Diagnoser(FD, CE);
11863
11864 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011865 return true;
11866
11867 return false;
11868}
11869
Douglas Gregor92c3a042011-01-19 16:50:08 +000011870// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011871// will prevent this condition from triggering, which is what we want.
11872void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11873 SourceLocation Loc;
11874
John McCalla52ef082009-11-11 02:41:58 +000011875 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011876 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011877
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011878 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011879 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011880 return;
11881
Douglas Gregor92c3a042011-01-19 16:50:08 +000011882 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11883
John McCallc8d8ac52009-11-12 00:06:05 +000011884 // Greylist some idioms by putting them into a warning subcategory.
11885 if (ObjCMessageExpr *ME
11886 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11887 Selector Sel = ME->getSelector();
11888
John McCallc8d8ac52009-11-12 00:06:05 +000011889 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011890 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011891 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11892
11893 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011894 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011895 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11896 }
John McCalla52ef082009-11-11 02:41:58 +000011897
John McCall5a881bb2009-10-12 21:59:07 +000011898 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011899 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011900 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011901 return;
11902
Douglas Gregor92c3a042011-01-19 16:50:08 +000011903 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011904 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011905 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11906 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11907 else {
John McCall5a881bb2009-10-12 21:59:07 +000011908 // Not an assignment.
11909 return;
11910 }
11911
Douglas Gregor55b38842010-04-14 16:09:52 +000011912 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011913
Daniel Dunbar96a00142012-03-09 18:35:03 +000011914 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011915 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11916 Diag(Loc, diag::note_condition_assign_silence)
11917 << FixItHint::CreateInsertion(Open, "(")
11918 << FixItHint::CreateInsertion(Close, ")");
11919
Douglas Gregor92c3a042011-01-19 16:50:08 +000011920 if (IsOrAssign)
11921 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11922 << FixItHint::CreateReplacement(Loc, "!=");
11923 else
11924 Diag(Loc, diag::note_condition_assign_to_comparison)
11925 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011926}
11927
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011928/// \brief Redundant parentheses over an equality comparison can indicate
11929/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011930void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011931 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011932 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011933 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11934 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011935 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011936 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011937 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011938
Richard Trieuccd891a2011-09-09 01:45:06 +000011939 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011940
11941 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011942 if (opE->getOpcode() == BO_EQ &&
11943 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11944 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011945 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011946
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011947 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011948 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011949 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011950 << FixItHint::CreateRemoval(ParenERange.getBegin())
11951 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011952 Diag(Loc, diag::note_equality_comparison_to_assign)
11953 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011954 }
11955}
11956
John Wiegley429bb272011-04-08 18:41:53 +000011957ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011958 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011959 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11960 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011961
John McCall864c0412011-04-26 20:42:42 +000011962 ExprResult result = CheckPlaceholderExpr(E);
11963 if (result.isInvalid()) return ExprError();
11964 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011965
John McCall864c0412011-04-26 20:42:42 +000011966 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011967 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011968 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11969
John Wiegley429bb272011-04-08 18:41:53 +000011970 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11971 if (ERes.isInvalid())
11972 return ExprError();
11973 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011974
11975 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011976 if (!T->isScalarType()) { // C99 6.8.4.1p1
11977 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11978 << T << E->getSourceRange();
11979 return ExprError();
11980 }
John McCall5a881bb2009-10-12 21:59:07 +000011981 }
11982
John Wiegley429bb272011-04-08 18:41:53 +000011983 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011984}
Douglas Gregor586596f2010-05-06 17:25:47 +000011985
John McCall60d7b3a2010-08-24 06:29:42 +000011986ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011987 Expr *SubExpr) {
11988 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011989 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011990
Richard Trieuccd891a2011-09-09 01:45:06 +000011991 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011992}
John McCall2a984ca2010-10-12 00:20:44 +000011993
John McCall1de4d4e2011-04-07 08:22:57 +000011994namespace {
John McCall755d8492011-04-12 00:42:48 +000011995 /// A visitor for rebuilding a call to an __unknown_any expression
11996 /// to have an appropriate type.
11997 struct RebuildUnknownAnyFunction
11998 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11999
12000 Sema &S;
12001
12002 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12003
12004 ExprResult VisitStmt(Stmt *S) {
12005 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000012006 }
12007
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012008 ExprResult VisitExpr(Expr *E) {
12009 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12010 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000012011 return ExprError();
12012 }
12013
12014 /// Rebuild an expression which simply semantically wraps another
12015 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012016 template <class T> ExprResult rebuildSugarExpr(T *E) {
12017 ExprResult SubResult = Visit(E->getSubExpr());
12018 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000012019
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012020 Expr *SubExpr = SubResult.take();
12021 E->setSubExpr(SubExpr);
12022 E->setType(SubExpr->getType());
12023 E->setValueKind(SubExpr->getValueKind());
12024 assert(E->getObjectKind() == OK_Ordinary);
12025 return E;
John McCall755d8492011-04-12 00:42:48 +000012026 }
12027
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012028 ExprResult VisitParenExpr(ParenExpr *E) {
12029 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000012030 }
12031
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012032 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12033 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000012034 }
12035
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012036 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12037 ExprResult SubResult = Visit(E->getSubExpr());
12038 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000012039
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012040 Expr *SubExpr = SubResult.take();
12041 E->setSubExpr(SubExpr);
12042 E->setType(S.Context.getPointerType(SubExpr->getType()));
12043 assert(E->getValueKind() == VK_RValue);
12044 assert(E->getObjectKind() == OK_Ordinary);
12045 return E;
John McCall755d8492011-04-12 00:42:48 +000012046 }
12047
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012048 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12049 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000012050
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012051 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000012052
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012053 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000012054 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012055 !(isa<CXXMethodDecl>(VD) &&
12056 cast<CXXMethodDecl>(VD)->isInstance()))
12057 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000012058
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012059 return E;
John McCall755d8492011-04-12 00:42:48 +000012060 }
12061
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012062 ExprResult VisitMemberExpr(MemberExpr *E) {
12063 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000012064 }
12065
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012066 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12067 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000012068 }
12069 };
12070}
12071
12072/// Given a function expression of unknown-any type, try to rebuild it
12073/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012074static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12075 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12076 if (Result.isInvalid()) return ExprError();
12077 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000012078}
12079
12080namespace {
John McCall379b5152011-04-11 07:02:50 +000012081 /// A visitor for rebuilding an expression of type __unknown_anytype
12082 /// into one which resolves the type directly on the referring
12083 /// expression. Strict preservation of the original source
12084 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000012085 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000012086 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000012087
12088 Sema &S;
12089
12090 /// The current destination type.
12091 QualType DestType;
12092
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012093 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12094 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000012095
John McCalla5fc4722011-04-09 22:50:59 +000012096 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000012097 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000012098 }
12099
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012100 ExprResult VisitExpr(Expr *E) {
12101 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12102 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000012103 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000012104 }
12105
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012106 ExprResult VisitCallExpr(CallExpr *E);
12107 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000012108
John McCalla5fc4722011-04-09 22:50:59 +000012109 /// Rebuild an expression which simply semantically wraps another
12110 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012111 template <class T> ExprResult rebuildSugarExpr(T *E) {
12112 ExprResult SubResult = Visit(E->getSubExpr());
12113 if (SubResult.isInvalid()) return ExprError();
12114 Expr *SubExpr = SubResult.take();
12115 E->setSubExpr(SubExpr);
12116 E->setType(SubExpr->getType());
12117 E->setValueKind(SubExpr->getValueKind());
12118 assert(E->getObjectKind() == OK_Ordinary);
12119 return E;
John McCalla5fc4722011-04-09 22:50:59 +000012120 }
John McCall1de4d4e2011-04-07 08:22:57 +000012121
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012122 ExprResult VisitParenExpr(ParenExpr *E) {
12123 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000012124 }
12125
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012126 ExprResult VisitUnaryExtension(UnaryOperator *E) {
12127 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000012128 }
12129
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012130 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12131 const PointerType *Ptr = DestType->getAs<PointerType>();
12132 if (!Ptr) {
12133 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12134 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000012135 return ExprError();
12136 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012137 assert(E->getValueKind() == VK_RValue);
12138 assert(E->getObjectKind() == OK_Ordinary);
12139 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000012140
12141 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012142 DestType = Ptr->getPointeeType();
12143 ExprResult SubResult = Visit(E->getSubExpr());
12144 if (SubResult.isInvalid()) return ExprError();
12145 E->setSubExpr(SubResult.take());
12146 return E;
John McCall755d8492011-04-12 00:42:48 +000012147 }
12148
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012149 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000012150
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012151 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000012152
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012153 ExprResult VisitMemberExpr(MemberExpr *E) {
12154 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000012155 }
John McCalla5fc4722011-04-09 22:50:59 +000012156
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012157 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12158 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000012159 }
12160 };
12161}
12162
John McCall379b5152011-04-11 07:02:50 +000012163/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012164ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12165 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000012166
12167 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000012168 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000012169 FK_FunctionPointer,
12170 FK_BlockPointer
12171 };
12172
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012173 FnKind Kind;
12174 QualType CalleeType = CalleeExpr->getType();
12175 if (CalleeType == S.Context.BoundMemberTy) {
12176 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12177 Kind = FK_MemberFunction;
12178 CalleeType = Expr::findBoundMemberType(CalleeExpr);
12179 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12180 CalleeType = Ptr->getPointeeType();
12181 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000012182 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012183 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12184 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000012185 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012186 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000012187
12188 // Verify that this is a legal result type of a function.
12189 if (DestType->isArrayType() || DestType->isFunctionType()) {
12190 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012191 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000012192 diagID = diag::err_block_returning_array_function;
12193
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012194 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000012195 << DestType->isFunctionType() << DestType;
12196 return ExprError();
12197 }
12198
12199 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012200 E->setType(DestType.getNonLValueExprType(S.Context));
12201 E->setValueKind(Expr::getValueKindForType(DestType));
12202 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000012203
12204 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012205 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
Jordan Rosebea522f2013-03-08 21:51:21 +000012206 DestType =
12207 S.Context.getFunctionType(DestType,
12208 ArrayRef<QualType>(Proto->arg_type_begin(),
12209 Proto->getNumArgs()),
12210 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000012211 else
12212 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012213 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000012214
12215 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012216 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000012217 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000012218 // Nothing to do.
12219 break;
12220
12221 case FK_FunctionPointer:
12222 DestType = S.Context.getPointerType(DestType);
12223 break;
12224
12225 case FK_BlockPointer:
12226 DestType = S.Context.getBlockPointerType(DestType);
12227 break;
12228 }
12229
12230 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012231 ExprResult CalleeResult = Visit(CalleeExpr);
12232 if (!CalleeResult.isUsable()) return ExprError();
12233 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000012234
12235 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012236 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000012237}
12238
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012239ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000012240 // Verify that this is a legal result type of a call.
12241 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012242 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000012243 << DestType->isFunctionType() << DestType;
12244 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000012245 }
12246
John McCall48218c62011-07-13 17:56:40 +000012247 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012248 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12249 assert(Method->getResultType() == S.Context.UnknownAnyTy);
12250 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000012251 }
John McCall755d8492011-04-12 00:42:48 +000012252
John McCall379b5152011-04-11 07:02:50 +000012253 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012254 E->setType(DestType.getNonReferenceType());
12255 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000012256
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012257 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000012258}
12259
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012260ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000012261 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000012262 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000012263 assert(E->getValueKind() == VK_RValue);
12264 assert(E->getObjectKind() == OK_Ordinary);
12265
12266 E->setType(DestType);
12267
12268 // Rebuild the sub-expression as the pointee (function) type.
12269 DestType = DestType->castAs<PointerType>()->getPointeeType();
12270
12271 ExprResult Result = Visit(E->getSubExpr());
12272 if (!Result.isUsable()) return ExprError();
12273
12274 E->setSubExpr(Result.take());
12275 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000012276 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000012277 assert(E->getValueKind() == VK_RValue);
12278 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000012279
Sean Callanance9c8312012-03-06 21:34:12 +000012280 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000012281
Sean Callanance9c8312012-03-06 21:34:12 +000012282 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000012283
Sean Callanance9c8312012-03-06 21:34:12 +000012284 // The sub-expression has to be a lvalue reference, so rebuild it as such.
12285 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000012286
Sean Callanance9c8312012-03-06 21:34:12 +000012287 ExprResult Result = Visit(E->getSubExpr());
12288 if (!Result.isUsable()) return ExprError();
12289
12290 E->setSubExpr(Result.take());
12291 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000012292 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000012293 llvm_unreachable("Unhandled cast type!");
12294 }
John McCall379b5152011-04-11 07:02:50 +000012295}
12296
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012297ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12298 ExprValueKind ValueKind = VK_LValue;
12299 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000012300
12301 // We know how to make this work for certain kinds of decls:
12302
12303 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012304 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12305 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12306 DestType = Ptr->getPointeeType();
12307 ExprResult Result = resolveDecl(E, VD);
12308 if (Result.isInvalid()) return ExprError();
12309 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000012310 CK_FunctionToPointerDecay, VK_RValue);
12311 }
12312
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012313 if (!Type->isFunctionType()) {
12314 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12315 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000012316 return ExprError();
12317 }
John McCall379b5152011-04-11 07:02:50 +000012318
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12320 if (MD->isInstance()) {
12321 ValueKind = VK_RValue;
12322 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000012323 }
12324
John McCall379b5152011-04-11 07:02:50 +000012325 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000012326 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012327 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000012328
12329 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012330 } else if (isa<VarDecl>(VD)) {
12331 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12332 Type = RefTy->getPointeeType();
12333 } else if (Type->isFunctionType()) {
12334 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12335 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000012336 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000012337 }
12338
12339 // - nothing else
12340 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012341 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12342 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000012343 return ExprError();
12344 }
12345
Richard Trieu5e4c80b2011-09-09 03:59:41 +000012346 VD->setType(DestType);
12347 E->setType(Type);
12348 E->setValueKind(ValueKind);
12349 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000012350}
12351
John McCall1de4d4e2011-04-07 08:22:57 +000012352/// Check a cast of an unknown-any type. We intentionally only
12353/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000012354ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12355 Expr *CastExpr, CastKind &CastKind,
12356 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000012357 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000012358 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000012359 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000012360
Richard Trieuccd891a2011-09-09 01:45:06 +000012361 CastExpr = result.take();
12362 VK = CastExpr->getValueKind();
12363 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000012364
Richard Trieuccd891a2011-09-09 01:45:06 +000012365 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000012366}
12367
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000012368ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12369 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12370}
12371
John McCall48f90422013-03-04 07:34:02 +000012372ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12373 Expr *arg, QualType &paramType) {
12374 // If the syntactic form of the argument is not an explicit cast of
12375 // any sort, just do default argument promotion.
12376 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12377 if (!castArg) {
12378 ExprResult result = DefaultArgumentPromotion(arg);
12379 if (result.isInvalid()) return ExprError();
12380 paramType = result.get()->getType();
12381 return result;
John McCallb8a8de32012-11-14 00:49:39 +000012382 }
12383
John McCall48f90422013-03-04 07:34:02 +000012384 // Otherwise, use the type that was written in the explicit cast.
12385 assert(!arg->hasPlaceholderType());
12386 paramType = castArg->getTypeAsWritten();
12387
12388 // Copy-initialize a parameter of that type.
12389 InitializedEntity entity =
12390 InitializedEntity::InitializeParameter(Context, paramType,
12391 /*consumed*/ false);
12392 return PerformCopyInitialization(entity, callLoc, Owned(arg));
John McCallb8a8de32012-11-14 00:49:39 +000012393}
12394
Richard Trieuccd891a2011-09-09 01:45:06 +000012395static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12396 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000012397 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000012398 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000012399 E = E->IgnoreParenImpCasts();
12400 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12401 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000012402 diagID = diag::err_uncasted_call_of_unknown_any;
12403 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000012404 break;
John McCall379b5152011-04-11 07:02:50 +000012405 }
John McCall1de4d4e2011-04-07 08:22:57 +000012406 }
12407
John McCall379b5152011-04-11 07:02:50 +000012408 SourceLocation loc;
12409 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000012410 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012411 loc = ref->getLocation();
12412 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000012413 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012414 loc = mem->getMemberLoc();
12415 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000012416 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012417 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000012418 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000012419 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000012420 if (!d) {
12421 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12422 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12423 << orig->getSourceRange();
12424 return ExprError();
12425 }
John McCall379b5152011-04-11 07:02:50 +000012426 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000012427 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12428 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000012429 return ExprError();
12430 }
12431
12432 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000012433
12434 // Never recoverable.
12435 return ExprError();
12436}
12437
John McCall2a984ca2010-10-12 00:20:44 +000012438/// Check for operands with placeholder types and complain if found.
12439/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000012440ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000012441 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12442 if (!placeholderType) return Owned(E);
12443
12444 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000012445
John McCall1de4d4e2011-04-07 08:22:57 +000012446 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000012447 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000012448 // Try to resolve a single function template specialization.
12449 // This is obligatory.
12450 ExprResult result = Owned(E);
12451 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12452 return result;
12453
12454 // If that failed, try to recover with a call.
12455 } else {
12456 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12457 /*complain*/ true);
12458 return result;
12459 }
12460 }
John McCall1de4d4e2011-04-07 08:22:57 +000012461
John McCall864c0412011-04-26 20:42:42 +000012462 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000012463 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000012464 ExprResult result = Owned(E);
12465 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12466 /*complain*/ true);
12467 return result;
John McCall5acb0c92011-10-17 18:40:02 +000012468 }
12469
12470 // ARC unbridged casts.
12471 case BuiltinType::ARCUnbridgedCast: {
12472 Expr *realCast = stripARCUnbridgedCast(E);
12473 diagnoseARCUnbridgedCast(realCast);
12474 return Owned(realCast);
12475 }
John McCall864c0412011-04-26 20:42:42 +000012476
John McCall1de4d4e2011-04-07 08:22:57 +000012477 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000012478 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000012479 return diagnoseUnknownAnyExpr(*this, E);
12480
John McCall3c3b7f92011-10-25 17:37:35 +000012481 // Pseudo-objects.
12482 case BuiltinType::PseudoObject:
12483 return checkPseudoObjectRValue(E);
12484
Eli Friedmana6c66ce2012-08-31 00:14:07 +000012485 case BuiltinType::BuiltinFn:
12486 Diag(E->getLocStart(), diag::err_builtin_fn_use);
12487 return ExprError();
12488
John McCalle0a22d02011-10-18 21:02:43 +000012489 // Everything else should be impossible.
12490#define BUILTIN_TYPE(Id, SingletonId) \
12491 case BuiltinType::Id:
12492#define PLACEHOLDER_TYPE(Id, SingletonId)
12493#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000012494 break;
12495 }
12496
12497 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000012498}
Richard Trieubb9b80c2011-04-21 21:44:26 +000012499
Richard Trieuccd891a2011-09-09 01:45:06 +000012500bool Sema::CheckCaseExpression(Expr *E) {
12501 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000012502 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000012503 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12504 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000012505 return false;
12506}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012507
12508/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12509ExprResult
12510Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12511 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12512 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000012513 QualType BoolT = Context.ObjCBuiltinBoolTy;
12514 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000012515 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012516 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000012517 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000012518 NamedDecl *ND = Result.getFoundDecl();
12519 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12520 Context.setBOOLDecl(TD);
12521 }
12522 }
12523 if (Context.getBOOLDecl())
12524 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012525 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012526 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012527}