blob: a6051d6ccc06609d576e63bae1b7dd4e780728fb [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Ted Kremenekd6cf9122012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000096 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith6c4c36c2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith5bdaac52012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose0eb3f452012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000146/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000147///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000148/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154 const NamedDecl *D,
155 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000156 // This is disabled under C++; there are too many ways for this to fire in
157 // contexts where the warning is a false positive, or where it is technically
158 // correct but benign.
159 if (S.getLangOpts().CPlusPlus)
160 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000161
162 // Check if this is an inlined function or method.
163 FunctionDecl *Current = S.getCurFunctionDecl();
164 if (!Current)
165 return;
166 if (!Current->isInlined())
167 return;
168 if (Current->getLinkage() != ExternalLinkage)
169 return;
170
171 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000172 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174
Jordan Rose05233272012-06-21 05:54:50 +0000175 // Downgrade from ExtWarn to Extension if
176 // (1) the supposedly external inline function is in the main file,
177 // and probably won't be included anywhere else.
178 // (2) the thing we're referencing is a pure function.
179 // (3) the thing we're referencing is another inline function.
180 // This last can give us false negatives, but it's better than warning on
181 // wrappers for simple C library functions.
182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184 if (!DowngradeWarning && UsedFn)
185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188 : diag::warn_internal_in_extern_inline)
189 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000190
191 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000192 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198
199 S.Diag(D->getCanonicalDecl()->getLocation(),
200 diag::note_internal_decl_declared_here)
201 << D;
202}
203
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000215///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000217 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226 Diag(Suppressed[I].first, Suppressed[I].second);
227
228 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000229 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000230 // entry from the table, because we want to avoid ever emitting these
231 // diagnostics again.
232 Suppressed.clear();
233 }
234 }
235
Richard Smith34b41d92011-02-20 03:19:35 +0000236 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000237 if (ParsingInitForAutoVars.count(D)) {
238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239 << D->getDeclName();
240 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000241 }
242
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000243 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000245 if (FD->isDeleted()) {
246 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000247 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000248 return true;
249 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000250 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000252
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000253 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000254 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose106af9e2012-06-15 18:19:48 +0000256
Jordan Rose0eb3f452012-06-18 22:09:19 +0000257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000258
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000259 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000260}
261
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266 // FIXME: C++0x implicitly-deleted special member functions could be
267 // detected here so that we could improve diagnostics to say, e.g.,
268 // "base class 'A' had a deleted copy constructor".
269 if (FD->isDeleted())
270 return std::string();
271
272 std::string Message;
273 if (FD->getAvailability(&Message))
274 return ": " + Message;
275
276 return std::string();
277}
278
John McCall3323fad2011-09-09 07:56:05 +0000279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000284 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000286 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000287 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000288
John McCall3323fad2011-09-09 07:56:05 +0000289 // The number of formal parameters of the declaration.
290 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall3323fad2011-09-09 07:56:05 +0000292 // The kind of declaration. This is also an index into a %select in
293 // the diagnostic.
294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000297 numFormalParams = MD->param_size();
298 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000300 numFormalParams = FD->param_size();
301 calleeType = CT_Function;
302 } else if (isa<VarDecl>(D)) {
303 QualType type = cast<ValueDecl>(D)->getType();
304 const FunctionType *fn = 0;
305 if (const PointerType *ptr = type->getAs<PointerType>()) {
306 fn = ptr->getPointeeType()->getAs<FunctionType>();
307 if (!fn) return;
308 calleeType = CT_Function;
309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310 fn = ptr->getPointeeType()->castAs<FunctionType>();
311 calleeType = CT_Block;
312 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000313 return;
John McCall3323fad2011-09-09 07:56:05 +0000314 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000315
John McCall3323fad2011-09-09 07:56:05 +0000316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317 numFormalParams = proto->getNumArgs();
318 } else {
319 numFormalParams = 0;
320 }
321 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000322 return;
323 }
John McCall3323fad2011-09-09 07:56:05 +0000324
325 // "nullPos" is the number of formal parameters at the end which
326 // effectively count as part of the variadic arguments. This is
327 // useful if you would prefer to not have *any* formal parameters,
328 // but the language forces you to have at least one.
329 unsigned nullPos = attr->getNullPos();
330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333 // The number of arguments which should follow the sentinel.
334 unsigned numArgsAfterSentinel = attr->getSentinel();
335
336 // If there aren't enough arguments for all the formal parameters,
337 // the sentinel, and the args after the sentinel, complain.
338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000341 return;
342 }
John McCall3323fad2011-09-09 07:56:05 +0000343
344 // Otherwise, find the sentinel expression.
345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000346 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000347 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000348 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000349
John McCall3323fad2011-09-09 07:56:05 +0000350 // Pick a reasonable string to insert. Optimistically use 'nil' or
351 // 'NULL' if those are actually defined in the context. Only use
352 // 'nil' for ObjC methods, where it's much more likely that the
353 // variadic arguments form a list of object pointers.
354 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000357 if (calleeType == CT_Method &&
358 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000359 NullValue = "nil";
360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000362 else
John McCall3323fad2011-09-09 07:56:05 +0000363 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000364
365 if (MissingNilLoc.isInvalid())
366 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367 else
368 Diag(MissingNilLoc, diag::warn_missing_sentinel)
369 << calleeType
370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000372}
373
Richard Trieuccd891a2011-09-09 01:45:06 +0000374SourceRange Sema::getExprRange(Expr *E) const {
375 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000376}
377
Chris Lattnere7a2e912008-07-25 21:10:04 +0000378//===----------------------------------------------------------------------===//
379// Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
Chris Lattnere7a2e912008-07-25 21:10:04 +0000382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000384 // Handle any placeholder expressions which made it here.
385 if (E->getType()->isPlaceholderType()) {
386 ExprResult result = CheckPlaceholderExpr(E);
387 if (result.isInvalid()) return ExprError();
388 E = result.take();
389 }
390
Chris Lattnere7a2e912008-07-25 21:10:04 +0000391 QualType Ty = E->getType();
392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000395 E = ImpCastExprToType(E, Context.getPointerType(Ty),
396 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000397 else if (Ty->isArrayType()) {
398 // In C90 mode, arrays only promote to pointers if the array expression is
399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400 // type 'array of type' is converted to an expression that has type 'pointer
401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
402 // that has type 'array of type' ...". The relevant change is "an lvalue"
403 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000404 //
405 // C++ 4.2p1:
406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407 // T" can be converted to an rvalue of type "pointer to T".
408 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000412 }
John Wiegley429bb272011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000414}
415
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417 // Check to see if we are dereferencing a null pointer. If so,
418 // and if not volatile-qualified, this is undefined behavior that the
419 // optimizer will delete, so warn about it. People sometimes try to use this
420 // to get a deterministic trap and are surprised by clang's behavior. This
421 // only handles the pattern "*null", which is a very syntactic check.
422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423 if (UO->getOpcode() == UO_Deref &&
424 UO->getSubExpr()->IgnoreParenCasts()->
425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426 !UO->getType().isVolatileQualified()) {
427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428 S.PDiag(diag::warn_indirection_through_null)
429 << UO->getSubExpr()->getSourceRange());
430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431 S.PDiag(diag::note_indirection_through_null));
432 }
433}
434
John Wiegley429bb272011-04-08 18:41:53 +0000435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
John McCall0ae287a2010-12-01 04:43:34 +0000443 // C++ [conv.lval]p1:
444 // A glvalue of a non-function, non-array type T can be
445 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000446 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000447
John McCall409fa9a2010-12-06 20:48:59 +0000448 QualType T = E->getType();
449 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000450
John McCall409fa9a2010-12-06 20:48:59 +0000451 // We don't want to throw lvalue-to-rvalue casts on top of
452 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000453 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000454 (E->getType() == Context.OverloadTy ||
455 T->isDependentType() ||
456 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000458
459 // The C standard is actually really unclear on this point, and
460 // DR106 tells us what the result should be but not why. It's
461 // generally best to say that void types just doesn't undergo
462 // lvalue-to-rvalue at all. Note that expressions of unqualified
463 // 'void' type are never l-values, but qualified void can be.
464 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000465 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000466
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000467 CheckForNullPointerDereference(*this, E);
468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // C++ [conv.lval]p1:
470 // [...] If T is a non-class type, the type of the prvalue is the
471 // cv-unqualified version of T. Otherwise, the type of the
472 // rvalue is T.
473 //
474 // C99 6.3.2.1p2:
475 // If the lvalue has qualified type, the value has the unqualified
476 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000477 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000478 if (T.hasQualifiers())
479 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000480
Eli Friedmand2cce132012-02-02 23:15:15 +0000481 UpdateMarkingForLValueToRValue(E);
482
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484 E, 0, VK_RValue));
485
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000486 // C11 6.3.2.1p2:
487 // ... if the lvalue has atomic type, the value has the non-atomic version
488 // of the type of the lvalue ...
489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490 T = Atomic->getValueType().getUnqualifiedType();
491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492 Res.get(), 0, VK_RValue));
493 }
494
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000495 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000496}
497
John Wiegley429bb272011-04-08 18:41:53 +0000498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499 ExprResult Res = DefaultFunctionArrayConversion(E);
500 if (Res.isInvalid())
501 return ExprError();
502 Res = DefaultLvalueConversion(Res.take());
503 if (Res.isInvalid())
504 return ExprError();
505 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000506}
507
508
Chris Lattnere7a2e912008-07-25 21:10:04 +0000509/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000510/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000511/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000514ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000515 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517 if (Res.isInvalid())
518 return Owned(E);
519 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520
John McCall0ae287a2010-12-01 04:43:34 +0000521 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000523
524 // Half FP is a bit different: it's a storage-only type, meaning that any
525 // "use" of it should be promoted to float.
526 if (Ty->isHalfType())
527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
John McCall0ae287a2010-12-01 04:43:34 +0000529 // Try to perform integral promotions if the object has a theoretically
530 // promotable type.
531 if (Ty->isIntegralOrUnscopedEnumerationType()) {
532 // C99 6.3.1.1p2:
533 //
534 // The following may be used in an expression wherever an int or
535 // unsigned int may be used:
536 // - an object or expression with an integer type whose integer
537 // conversion rank is less than or equal to the rank of int
538 // and unsigned int.
539 // - A bit-field of type _Bool, int, signed int, or unsigned int.
540 //
541 // If an int can represent all values of the original type, the
542 // value is converted to an int; otherwise, it is converted to an
543 // unsigned int. These are called the integer promotions. All
544 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType PTy = Context.isPromotableBitField(E);
547 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000550 }
551 if (Ty->isPromotableIntegerType()) {
552 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000555 }
Eli Friedman04e83572009-08-20 04:21:42 +0000556 }
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000558}
559
Chris Lattner05faf172008-07-25 22:25:12 +0000560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000561/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000562/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000566
John Wiegley429bb272011-04-08 18:41:53 +0000567 ExprResult Res = UsualUnaryConversions(E);
568 if (Res.isInvalid())
569 return Owned(E);
570 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000571
Chris Lattner05faf172008-07-25 22:25:12 +0000572 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000573 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
John McCall96a914a2011-08-27 22:06:17 +0000576 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000577 // promotion, even on class types, but note:
578 // C++11 [conv.lval]p2:
579 // When an lvalue-to-rvalue conversion occurs in an unevaluated
580 // operand or a subexpression thereof the value contained in the
581 // referenced object is not accessed. Otherwise, if the glvalue
582 // has a class type, the conversion copy-initializes a temporary
583 // of type T from the glvalue and the result of the conversion
584 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000585 // FIXME: add some way to gate this entire thing for correctness in
586 // potentially potentially evaluated contexts.
David Blaikie4e4d0842012-03-11 07:00:24 +0000587 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman55693fb2012-01-17 02:13:45 +0000588 ExprEvalContexts.back().Context != Unevaluated) {
589 ExprResult Temp = PerformCopyInitialization(
590 InitializedEntity::InitializeTemporary(E->getType()),
591 E->getExprLoc(),
592 Owned(E));
593 if (Temp.isInvalid())
594 return ExprError();
595 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000596 }
597
John Wiegley429bb272011-04-08 18:41:53 +0000598 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000599}
600
Richard Smith831421f2012-06-25 20:30:08 +0000601/// Determine the degree of POD-ness for an expression.
602/// Incomplete types are considered POD, since this check can be performed
603/// when we're in an unevaluated context.
604Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
605 if (Ty->isIncompleteType() || Ty.isCXX98PODType(Context))
606 return VAK_Valid;
607 // C++0x [expr.call]p7:
608 // Passing a potentially-evaluated argument of class type (Clause 9)
609 // having a non-trivial copy constructor, a non-trivial move constructor,
610 // or a non-trivial destructor, with no corresponding parameter,
611 // is conditionally-supported with implementation-defined semantics.
612
613 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
614 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
615 if (Record->hasTrivialCopyConstructor() &&
616 Record->hasTrivialMoveConstructor() &&
617 Record->hasTrivialDestructor())
618 return VAK_ValidInCXX11;
619
620 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
621 return VAK_Valid;
622 return VAK_Invalid;
623}
624
625bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
626 // Don't allow one to pass an Objective-C interface to a vararg.
627 const QualType & Ty = E->getType();
628
629 // Complain about passing non-POD types through varargs.
630 switch (isValidVarArgType(Ty)) {
631 case VAK_Valid:
632 break;
633 case VAK_ValidInCXX11:
634 DiagRuntimeBehavior(E->getLocStart(), 0,
635 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
636 << E->getType() << CT);
637 break;
638 case VAK_Invalid:
639 return DiagRuntimeBehavior(E->getLocStart(), 0,
640 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
641 << getLangOpts().CPlusPlus0x << Ty << CT);
642 }
643 // c++ rules are enforced elsewhere.
644 return false;
645}
646
Chris Lattner312531a2009-04-12 08:11:20 +0000647/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
648/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000649/// interfaces passed by value.
650ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000651 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000652 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000653 // Strip the unbridged-cast placeholder expression off, if applicable.
654 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
655 (CT == VariadicMethod ||
656 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
657 E = stripARCUnbridgedCast(E);
658
659 // Otherwise, do normal placeholder checking.
660 } else {
661 ExprResult ExprRes = CheckPlaceholderExpr(E);
662 if (ExprRes.isInvalid())
663 return ExprError();
664 E = ExprRes.take();
665 }
666 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000667
John McCall5acb0c92011-10-17 18:40:02 +0000668 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000669 if (ExprRes.isInvalid())
670 return ExprError();
671 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Richard Smithe1971a12012-06-27 20:29:39 +0000673 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000674 DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
Richard Smithe1971a12012-06-27 20:29:39 +0000676 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000677 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000678
Richard Smith831421f2012-06-25 20:30:08 +0000679 // Diagnostics regarding non-POD argument types are
680 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000681 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000682 // Turn this into a trap.
683 CXXScopeSpec SS;
684 SourceLocation TemplateKWLoc;
685 UnqualifiedId Name;
686 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
687 E->getLocStart());
688 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
689 Name, true, false);
690 if (TrapFn.isInvalid())
691 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000692
Richard Smith831421f2012-06-25 20:30:08 +0000693 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
694 E->getLocStart(), MultiExprArg(),
695 E->getLocEnd());
696 if (Call.isInvalid())
697 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000698
Richard Smith831421f2012-06-25 20:30:08 +0000699 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
700 Call.get(), E);
701 if (Comma.isInvalid())
702 return ExprError();
703 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000704 }
Richard Smith831421f2012-06-25 20:30:08 +0000705
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000707 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000708 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000709 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000710
John Wiegley429bb272011-04-08 18:41:53 +0000711 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000712}
713
Richard Trieu8289f492011-09-02 20:58:51 +0000714/// \brief Converts an integer to complex float type. Helper function of
715/// UsualArithmeticConversions()
716///
717/// \return false if the integer expression is an integer type and is
718/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000719static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
720 ExprResult &ComplexExpr,
721 QualType IntTy,
722 QualType ComplexTy,
723 bool SkipCast) {
724 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
725 if (SkipCast) return false;
726 if (IntTy->isIntegerType()) {
727 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
728 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
729 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000730 CK_FloatingRealToComplex);
731 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000732 assert(IntTy->isComplexIntegerType());
733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000734 CK_IntegralComplexToFloatingComplex);
735 }
736 return false;
737}
738
739/// \brief Takes two complex float types and converts them to the same type.
740/// Helper function of UsualArithmeticConversions()
741static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000742handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
743 ExprResult &RHS, QualType LHSType,
744 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000745 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000746 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000747
748 if (order < 0) {
749 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000750 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000751 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
752 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000753 }
754 if (order > 0)
755 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000756 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
757 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000758}
759
760/// \brief Converts otherExpr to complex float and promotes complexExpr if
761/// necessary. Helper function of UsualArithmeticConversions()
762static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000763 ExprResult &ComplexExpr,
764 ExprResult &OtherExpr,
765 QualType ComplexTy,
766 QualType OtherTy,
767 bool ConvertComplexExpr,
768 bool ConvertOtherExpr) {
769 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000770
771 // If just the complexExpr is complex, the otherExpr needs to be converted,
772 // and the complexExpr might need to be promoted.
773 if (order > 0) { // complexExpr is wider
774 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000775 if (ConvertOtherExpr) {
776 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
777 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
778 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000779 CK_FloatingRealToComplex);
780 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000781 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783
784 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000785 QualType result = (order == 0 ? ComplexTy :
786 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000787
788 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 if (ConvertOtherExpr)
790 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000791 CK_FloatingRealToComplex);
792
793 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000794 if (ConvertComplexExpr && order < 0)
795 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000796 CK_FloatingComplexCast);
797
798 return result;
799}
800
801/// \brief Handle arithmetic conversion with complex types. Helper function of
802/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000803static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
804 ExprResult &RHS, QualType LHSType,
805 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000806 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000807 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000808 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000809 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000810 return LHSType;
811 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000812 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000813 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000814
815 // This handles complex/complex, complex/float, or float/complex.
816 // When both operands are complex, the shorter operand is converted to the
817 // type of the longer, and that is the type of the result. This corresponds
818 // to what is done when combining two real floating-point operands.
819 // The fun begins when size promotion occur across type domains.
820 // From H&S 6.3.4: When one operand is complex and the other is a real
821 // floating-point type, the less precise type is converted, within it's
822 // real or complex domain, to the precision of the other type. For example,
823 // when combining a "long double" with a "double _Complex", the
824 // "double _Complex" is promoted to "long double _Complex".
825
Richard Trieucafd30b2011-09-06 18:25:09 +0000826 bool LHSComplexFloat = LHSType->isComplexType();
827 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000828
829 // If both are complex, just cast to the more precise type.
830 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000831 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
832 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000833 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000834
835 // If only one operand is complex, promote it if necessary and convert the
836 // other operand to complex.
837 if (LHSComplexFloat)
838 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000839 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000840 /*convertOtherExpr*/ true);
841
842 assert(RHSComplexFloat);
843 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000844 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000845 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000846}
847
848/// \brief Hande arithmetic conversion from integer to float. Helper function
849/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000850static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
851 ExprResult &IntExpr,
852 QualType FloatTy, QualType IntTy,
853 bool ConvertFloat, bool ConvertInt) {
854 if (IntTy->isIntegerType()) {
855 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000856 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000857 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000858 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000859 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000860 }
861
862 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000863 assert(IntTy->isComplexIntegerType());
864 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000865
866 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 if (ConvertInt)
868 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000869 CK_IntegralComplexToFloatingComplex);
870
871 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000872 if (ConvertFloat)
873 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000874 CK_FloatingRealToComplex);
875
876 return result;
877}
878
879/// \brief Handle arithmethic conversion with floating point types. Helper
880/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000881static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
882 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000883 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000884 bool LHSFloat = LHSType->isRealFloatingType();
885 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000886
887 // If we have two real floating types, convert the smaller operand
888 // to the bigger result.
889 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000890 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000891 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000892 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
893 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000894 }
895
896 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000897 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000898 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
899 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000900 }
901
902 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000903 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000904 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000905 /*convertInt=*/ true);
906 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000907 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000908 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000909 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000910}
911
912/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000913/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000914// FIXME: if the operands are (int, _Complex long), we currently
915// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000916static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
917 ExprResult &RHS, QualType LHSType,
918 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000919 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000920 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
921 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000922
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000923 if (LHSComplexInt && RHSComplexInt) {
924 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
925 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000926 assert(order && "inequal types with equal element ordering");
927 if (order > 0) {
928 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000929 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
930 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000931 }
932
Richard Trieuccd891a2011-09-09 01:45:06 +0000933 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000934 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
935 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000936 }
937
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000938 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000939 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000940 // FIXME: This needs to take integer ranks into account
941 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
942 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000943 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
944 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000945 }
946
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000947 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000948 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000949 // FIXME: This needs to take integer ranks into account
950 if (!IsCompAssign) {
951 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
952 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000953 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000954 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000955 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000956}
957
958/// \brief Handle integer arithmetic conversions. Helper function of
959/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000960static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
961 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000962 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000963 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000964 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
965 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
966 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
967 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000968 // Same signedness; use the higher-ranked type
969 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000970 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
971 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000972 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000973 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
974 return RHSType;
975 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000976 // The unsigned type has greater than or equal rank to the
977 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000978 if (RHSSigned) {
979 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
980 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000981 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
983 return RHSType;
984 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000985 // The two types are different widths; if we are here, that
986 // means the signed type is larger than the unsigned type, so
987 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000988 if (LHSSigned) {
989 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
990 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000991 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
993 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000994 } else {
995 // The signed type is higher-ranked than the unsigned type,
996 // but isn't actually any bigger (like unsigned int and long
997 // on most 32-bit systems). Use the unsigned type corresponding
998 // to the signed type.
999 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001000 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1001 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001002 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001003 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001004 return result;
1005 }
1006}
1007
Chris Lattnere7a2e912008-07-25 21:10:04 +00001008/// UsualArithmeticConversions - Performs various conversions that are common to
1009/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001010/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001011/// responsible for emitting appropriate error diagnostics.
1012/// FIXME: verify the conversion rules for "complex int" are consistent with
1013/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001014QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001015 bool IsCompAssign) {
1016 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001017 LHS = UsualUnaryConversions(LHS.take());
1018 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001019 return QualType();
1020 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001021
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001022 RHS = UsualUnaryConversions(RHS.take());
1023 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001024 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001025
Mike Stump1eb44332009-09-09 15:08:12 +00001026 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001027 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001028 QualType LHSType =
1029 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1030 QualType RHSType =
1031 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001032
Eli Friedman860a3192012-06-16 02:19:17 +00001033 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1034 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1035 LHSType = AtomicLHS->getValueType();
1036
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001037 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001038 if (LHSType == RHSType)
1039 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001040
1041 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1042 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001043 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001044 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001045
John McCallcf33b242010-11-13 08:17:45 +00001046 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001047 QualType LHSUnpromotedType = LHSType;
1048 if (LHSType->isPromotableIntegerType())
1049 LHSType = Context.getPromotedIntegerType(LHSType);
1050 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001051 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001052 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001053 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001054 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001055
John McCallcf33b242010-11-13 08:17:45 +00001056 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001057 if (LHSType == RHSType)
1058 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001059
1060 // At this point, we have two different arithmetic types.
1061
1062 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001063 if (LHSType->isComplexType() || RHSType->isComplexType())
1064 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001065 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001066
1067 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001068 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1069 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001070 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001071
1072 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001073 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001074 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001075 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001076
1077 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001078 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001079 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001080}
1081
Chris Lattnere7a2e912008-07-25 21:10:04 +00001082//===----------------------------------------------------------------------===//
1083// Semantic Analysis for various Expression Types
1084//===----------------------------------------------------------------------===//
1085
1086
Peter Collingbournef111d932011-04-15 00:35:48 +00001087ExprResult
1088Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1089 SourceLocation DefaultLoc,
1090 SourceLocation RParenLoc,
1091 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001092 MultiTypeArg ArgTypes,
1093 MultiExprArg ArgExprs) {
1094 unsigned NumAssocs = ArgTypes.size();
1095 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001096
Richard Trieuccd891a2011-09-09 01:45:06 +00001097 ParsedType *ParsedTypes = ArgTypes.release();
1098 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +00001099
1100 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1101 for (unsigned i = 0; i < NumAssocs; ++i) {
1102 if (ParsedTypes[i])
1103 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1104 else
1105 Types[i] = 0;
1106 }
1107
1108 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1109 ControllingExpr, Types, Exprs,
1110 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001111 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001112 return ER;
1113}
1114
1115ExprResult
1116Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1117 SourceLocation DefaultLoc,
1118 SourceLocation RParenLoc,
1119 Expr *ControllingExpr,
1120 TypeSourceInfo **Types,
1121 Expr **Exprs,
1122 unsigned NumAssocs) {
1123 bool TypeErrorFound = false,
1124 IsResultDependent = ControllingExpr->isTypeDependent(),
1125 ContainsUnexpandedParameterPack
1126 = ControllingExpr->containsUnexpandedParameterPack();
1127
1128 for (unsigned i = 0; i < NumAssocs; ++i) {
1129 if (Exprs[i]->containsUnexpandedParameterPack())
1130 ContainsUnexpandedParameterPack = true;
1131
1132 if (Types[i]) {
1133 if (Types[i]->getType()->containsUnexpandedParameterPack())
1134 ContainsUnexpandedParameterPack = true;
1135
1136 if (Types[i]->getType()->isDependentType()) {
1137 IsResultDependent = true;
1138 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001139 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001140 // complete object type other than a variably modified type."
1141 unsigned D = 0;
1142 if (Types[i]->getType()->isIncompleteType())
1143 D = diag::err_assoc_type_incomplete;
1144 else if (!Types[i]->getType()->isObjectType())
1145 D = diag::err_assoc_type_nonobject;
1146 else if (Types[i]->getType()->isVariablyModifiedType())
1147 D = diag::err_assoc_type_variably_modified;
1148
1149 if (D != 0) {
1150 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1151 << Types[i]->getTypeLoc().getSourceRange()
1152 << Types[i]->getType();
1153 TypeErrorFound = true;
1154 }
1155
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001156 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001157 // selection shall specify compatible types."
1158 for (unsigned j = i+1; j < NumAssocs; ++j)
1159 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1160 Context.typesAreCompatible(Types[i]->getType(),
1161 Types[j]->getType())) {
1162 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1163 diag::err_assoc_compatible_types)
1164 << Types[j]->getTypeLoc().getSourceRange()
1165 << Types[j]->getType()
1166 << Types[i]->getType();
1167 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1168 diag::note_compat_assoc)
1169 << Types[i]->getTypeLoc().getSourceRange()
1170 << Types[i]->getType();
1171 TypeErrorFound = true;
1172 }
1173 }
1174 }
1175 }
1176 if (TypeErrorFound)
1177 return ExprError();
1178
1179 // If we determined that the generic selection is result-dependent, don't
1180 // try to compute the result expression.
1181 if (IsResultDependent)
1182 return Owned(new (Context) GenericSelectionExpr(
1183 Context, KeyLoc, ControllingExpr,
1184 Types, Exprs, NumAssocs, DefaultLoc,
1185 RParenLoc, ContainsUnexpandedParameterPack));
1186
Chris Lattner5f9e2722011-07-23 10:55:15 +00001187 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001188 unsigned DefaultIndex = -1U;
1189 for (unsigned i = 0; i < NumAssocs; ++i) {
1190 if (!Types[i])
1191 DefaultIndex = i;
1192 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1193 Types[i]->getType()))
1194 CompatIndices.push_back(i);
1195 }
1196
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001197 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001198 // type compatible with at most one of the types named in its generic
1199 // association list."
1200 if (CompatIndices.size() > 1) {
1201 // We strip parens here because the controlling expression is typically
1202 // parenthesized in macro definitions.
1203 ControllingExpr = ControllingExpr->IgnoreParens();
1204 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1205 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1206 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001207 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001208 E = CompatIndices.end(); I != E; ++I) {
1209 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1210 diag::note_compat_assoc)
1211 << Types[*I]->getTypeLoc().getSourceRange()
1212 << Types[*I]->getType();
1213 }
1214 return ExprError();
1215 }
1216
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001217 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001218 // its controlling expression shall have type compatible with exactly one of
1219 // the types named in its generic association list."
1220 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1221 // We strip parens here because the controlling expression is typically
1222 // parenthesized in macro definitions.
1223 ControllingExpr = ControllingExpr->IgnoreParens();
1224 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1225 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1226 return ExprError();
1227 }
1228
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001229 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001230 // type name that is compatible with the type of the controlling expression,
1231 // then the result expression of the generic selection is the expression
1232 // in that generic association. Otherwise, the result expression of the
1233 // generic selection is the expression in the default generic association."
1234 unsigned ResultIndex =
1235 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1236
1237 return Owned(new (Context) GenericSelectionExpr(
1238 Context, KeyLoc, ControllingExpr,
1239 Types, Exprs, NumAssocs, DefaultLoc,
1240 RParenLoc, ContainsUnexpandedParameterPack,
1241 ResultIndex));
1242}
1243
Richard Smithdd66be72012-03-08 01:34:56 +00001244/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1245/// location of the token and the offset of the ud-suffix within it.
1246static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1247 unsigned Offset) {
1248 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001249 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001250}
1251
Richard Smith36f5cfe2012-03-09 08:00:36 +00001252/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1253/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1254static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1255 IdentifierInfo *UDSuffix,
1256 SourceLocation UDSuffixLoc,
1257 ArrayRef<Expr*> Args,
1258 SourceLocation LitEndLoc) {
1259 assert(Args.size() <= 2 && "too many arguments for literal operator");
1260
1261 QualType ArgTy[2];
1262 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1263 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1264 if (ArgTy[ArgIdx]->isArrayType())
1265 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1266 }
1267
1268 DeclarationName OpName =
1269 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1270 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1271 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1272
1273 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1274 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1275 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1276 return ExprError();
1277
1278 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1279}
1280
Steve Narofff69936d2007-09-16 03:34:24 +00001281/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001282/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1283/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1284/// multiple tokens. However, the common case is that StringToks points to one
1285/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001286///
John McCall60d7b3a2010-08-24 06:29:42 +00001287ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001288Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1289 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 assert(NumStringToks && "Must have at least one string!");
1291
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001292 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001294 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
Chris Lattner5f9e2722011-07-23 10:55:15 +00001296 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 for (unsigned i = 0; i != NumStringToks; ++i)
1298 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001299
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001300 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001301 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001302 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001303 else if (Literal.isUTF16())
1304 StrTy = Context.Char16Ty;
1305 else if (Literal.isUTF32())
1306 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001307 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001308 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001309
Douglas Gregor5cee1192011-07-27 05:40:30 +00001310 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1311 if (Literal.isWide())
1312 Kind = StringLiteral::Wide;
1313 else if (Literal.isUTF8())
1314 Kind = StringLiteral::UTF8;
1315 else if (Literal.isUTF16())
1316 Kind = StringLiteral::UTF16;
1317 else if (Literal.isUTF32())
1318 Kind = StringLiteral::UTF32;
1319
Douglas Gregor77a52232008-09-12 00:47:35 +00001320 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001321 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001322 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001323
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001324 // Get an array type for the string, according to C99 6.4.5. This includes
1325 // the nul terminator character as well as the string length for pascal
1326 // strings.
1327 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001328 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001329 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001332 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1333 Kind, Literal.Pascal, StrTy,
1334 &StringTokLocs[0],
1335 StringTokLocs.size());
1336 if (Literal.getUDSuffix().empty())
1337 return Owned(Lit);
1338
1339 // We're building a user-defined literal.
1340 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001341 SourceLocation UDSuffixLoc =
1342 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1343 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001344
Richard Smith36f5cfe2012-03-09 08:00:36 +00001345 // Make sure we're allowed user-defined literals here.
1346 if (!UDLScope)
1347 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1348
Richard Smith9fcce652012-03-07 08:35:16 +00001349 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1350 // operator "" X (str, len)
1351 QualType SizeType = Context.getSizeType();
1352 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1353 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1354 StringTokLocs[0]);
1355 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001356 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1357 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001358}
1359
John McCall60d7b3a2010-08-24 06:29:42 +00001360ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001361Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001362 SourceLocation Loc,
1363 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001364 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001365 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001366}
1367
John McCall76a40212011-02-09 01:13:10 +00001368/// BuildDeclRefExpr - Build an expression that references a
1369/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001370ExprResult
John McCall76a40212011-02-09 01:13:10 +00001371Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001372 const DeclarationNameInfo &NameInfo,
1373 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001374 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001375 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1376 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1377 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1378 CalleeTarget = IdentifyCUDATarget(Callee);
1379 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1380 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1381 << CalleeTarget << D->getIdentifier() << CallerTarget;
1382 Diag(D->getLocation(), diag::note_previous_decl)
1383 << D->getIdentifier();
1384 return ExprError();
1385 }
1386 }
1387
John McCallf4b88a42012-03-10 09:33:50 +00001388 bool refersToEnclosingScope =
1389 (CurContext != D->getDeclContext() &&
1390 D->getDeclContext()->isFunctionOrMethod());
1391
Eli Friedman5f2987c2012-02-02 03:46:19 +00001392 DeclRefExpr *E = DeclRefExpr::Create(Context,
1393 SS ? SS->getWithLocInContext(Context)
1394 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001395 SourceLocation(),
1396 D, refersToEnclosingScope,
1397 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Eli Friedman5f2987c2012-02-02 03:46:19 +00001399 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001400
1401 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001402 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1403 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001404 E->setObjectKind(OK_BitField);
1405
1406 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001407}
1408
Abramo Bagnara25777432010-08-11 22:01:17 +00001409/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001410/// possibly a list of template arguments.
1411///
1412/// If this produces template arguments, it is permitted to call
1413/// DecomposeTemplateName.
1414///
1415/// This actually loses a lot of source location information for
1416/// non-standard name kinds; we should consider preserving that in
1417/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001418void
1419Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1420 TemplateArgumentListInfo &Buffer,
1421 DeclarationNameInfo &NameInfo,
1422 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001423 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1424 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1425 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1426
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001427 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001428 Id.TemplateId->getTemplateArgs(),
1429 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001430 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001431 TemplateArgsPtr.release();
1432
John McCall2b5289b2010-08-23 07:28:44 +00001433 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001434 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001435 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001436 TemplateArgs = &Buffer;
1437 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001438 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001439 TemplateArgs = 0;
1440 }
1441}
1442
John McCall578b69b2009-12-16 08:11:27 +00001443/// Diagnose an empty lookup.
1444///
1445/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001446bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001447 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001448 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001449 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001450 DeclarationName Name = R.getLookupName();
1451
John McCall578b69b2009-12-16 08:11:27 +00001452 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001453 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001454 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1455 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001456 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001457 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001458 diagnostic_suggest = diag::err_undeclared_use_suggest;
1459 }
John McCall578b69b2009-12-16 08:11:27 +00001460
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001461 // If the original lookup was an unqualified lookup, fake an
1462 // unqualified lookup. This is useful when (for example) the
1463 // original lookup would not have found something because it was a
1464 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001465 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1466 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001467 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001468 if (isa<CXXRecordDecl>(DC)) {
1469 LookupQualifiedName(R, DC);
1470
1471 if (!R.empty()) {
1472 // Don't give errors about ambiguities in this lookup.
1473 R.suppressDiagnostics();
1474
Francois Pichete6226ae2011-11-17 03:44:24 +00001475 // During a default argument instantiation the CurContext points
1476 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1477 // function parameter list, hence add an explicit check.
1478 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1479 ActiveTemplateInstantiations.back().Kind ==
1480 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001481 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1482 bool isInstance = CurMethod &&
1483 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001484 DC == CurMethod->getParent() && !isDefaultArgument;
1485
John McCall578b69b2009-12-16 08:11:27 +00001486
1487 // Give a code modification hint to insert 'this->'.
1488 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1489 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001490 if (getLangOpts().MicrosoftMode)
1491 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001492 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001493 Diag(R.getNameLoc(), diagnostic) << Name
1494 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001495 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1496 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001497
1498
1499 CXXMethodDecl *DepMethod;
1500 if (CurMethod->getTemplatedKind() ==
1501 FunctionDecl::TK_FunctionTemplateSpecialization)
1502 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1503 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1504 else
1505 DepMethod = cast<CXXMethodDecl>(
1506 CurMethod->getInstantiatedFromMemberFunction());
1507 assert(DepMethod && "No template pattern found");
1508
1509 QualType DepThisType = DepMethod->getThisType(Context);
1510 CheckCXXThisCapture(R.getNameLoc());
1511 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1512 R.getNameLoc(), DepThisType, false);
1513 TemplateArgumentListInfo TList;
1514 if (ULE->hasExplicitTemplateArgs())
1515 ULE->copyTemplateArgumentsInto(TList);
1516
1517 CXXScopeSpec SS;
1518 SS.Adopt(ULE->getQualifierLoc());
1519 CXXDependentScopeMemberExpr *DepExpr =
1520 CXXDependentScopeMemberExpr::Create(
1521 Context, DepThis, DepThisType, true, SourceLocation(),
1522 SS.getWithLocInContext(Context),
1523 ULE->getTemplateKeywordLoc(), 0,
1524 R.getLookupNameInfo(),
1525 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1526 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001527 } else {
John McCall578b69b2009-12-16 08:11:27 +00001528 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001529 }
John McCall578b69b2009-12-16 08:11:27 +00001530
1531 // Do we really want to note all of these?
1532 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1533 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1534
Francois Pichete6226ae2011-11-17 03:44:24 +00001535 // Return true if we are inside a default argument instantiation
1536 // and the found name refers to an instance member function, otherwise
1537 // the function calling DiagnoseEmptyLookup will try to create an
1538 // implicit member call and this is wrong for default argument.
1539 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1540 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1541 return true;
1542 }
1543
John McCall578b69b2009-12-16 08:11:27 +00001544 // Tell the callee to try to recover.
1545 return false;
1546 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001547
1548 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001549 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001550
1551 // In Microsoft mode, if we are performing lookup from within a friend
1552 // function definition declared at class scope then we must set
1553 // DC to the lexical parent to be able to search into the parent
1554 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001555 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001556 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1557 DC->getLexicalParent()->isRecord())
1558 DC = DC->getLexicalParent();
1559 else
1560 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001561 }
1562
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001563 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001564 TypoCorrection Corrected;
1565 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001566 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001567 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1568 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001569 R.setLookupName(Corrected.getCorrection());
1570
Hans Wennborg701d1e72011-07-12 08:45:31 +00001571 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001572 if (Corrected.isOverloaded()) {
1573 OverloadCandidateSet OCS(R.getNameLoc());
1574 OverloadCandidateSet::iterator Best;
1575 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1576 CDEnd = Corrected.end();
1577 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001578 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001579 dyn_cast<FunctionTemplateDecl>(*CD))
1580 AddTemplateOverloadCandidate(
1581 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001582 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001583 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1584 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1585 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001586 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001587 }
1588 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1589 case OR_Success:
1590 ND = Best->Function;
1591 break;
1592 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001593 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001594 }
1595 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001596 R.addDecl(ND);
1597 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001598 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001599 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1600 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001601 else
1602 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001603 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001604 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001605 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1606 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001607 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001608 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001609
1610 // Tell the callee to try to recover.
1611 return false;
1612 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001613
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001614 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001615 // FIXME: If we ended up with a typo for a type name or
1616 // Objective-C class name, we're in trouble because the parser
1617 // is in the wrong place to recover. Suggest the typo
1618 // correction, but don't make it a fix-it since we're not going
1619 // to recover well anyway.
1620 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001621 Diag(R.getNameLoc(), diagnostic_suggest)
1622 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001623 else
1624 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001625 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001626 << SS.getRange();
1627
1628 // Don't try to recover; it won't work.
1629 return true;
1630 }
1631 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001632 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001633 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001634 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001635 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001636 else
Douglas Gregord203a162010-01-01 00:15:04 +00001637 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001638 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001639 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001640 return true;
1641 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001642 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001643 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001644
1645 // Emit a special diagnostic for failed member lookups.
1646 // FIXME: computing the declaration context might fail here (?)
1647 if (!SS.isEmpty()) {
1648 Diag(R.getNameLoc(), diag::err_no_member)
1649 << Name << computeDeclContext(SS, false)
1650 << SS.getRange();
1651 return true;
1652 }
1653
John McCall578b69b2009-12-16 08:11:27 +00001654 // Give up, we can't recover.
1655 Diag(R.getNameLoc(), diagnostic) << Name;
1656 return true;
1657}
1658
John McCall60d7b3a2010-08-24 06:29:42 +00001659ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001660 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001661 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001662 UnqualifiedId &Id,
1663 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001664 bool IsAddressOfOperand,
1665 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001666 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001667 "cannot be direct & operand and have a trailing lparen");
1668
1669 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001670 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001671
John McCall129e2df2009-11-30 22:42:35 +00001672 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001673
1674 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001675 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001676 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001677 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001678
Abramo Bagnara25777432010-08-11 22:01:17 +00001679 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001680 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001681 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001682
John McCallf7a1a742009-11-24 19:00:30 +00001683 // C++ [temp.dep.expr]p3:
1684 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001685 // -- an identifier that was declared with a dependent type,
1686 // (note: handled after lookup)
1687 // -- a template-id that is dependent,
1688 // (note: handled in BuildTemplateIdExpr)
1689 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001690 // -- a nested-name-specifier that contains a class-name that
1691 // names a dependent type.
1692 // Determine whether this is a member of an unknown specialization;
1693 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001694 bool DependentID = false;
1695 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1696 Name.getCXXNameType()->isDependentType()) {
1697 DependentID = true;
1698 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001699 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001700 if (RequireCompleteDeclContext(SS, DC))
1701 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001702 } else {
1703 DependentID = true;
1704 }
1705 }
1706
Chris Lattner337e5502011-02-18 01:27:55 +00001707 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001708 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1709 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001710
John McCallf7a1a742009-11-24 19:00:30 +00001711 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001712 LookupResult R(*this, NameInfo,
1713 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1714 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001715 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001716 // Lookup the template name again to correctly establish the context in
1717 // which it was found. This is really unfortunate as we already did the
1718 // lookup to determine that it was a template name in the first place. If
1719 // this becomes a performance hit, we can work harder to preserve those
1720 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001721 bool MemberOfUnknownSpecialization;
1722 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1723 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001724
1725 if (MemberOfUnknownSpecialization ||
1726 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001727 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1728 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001729 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001730 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001731 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001733 // If the result might be in a dependent base class, this is a dependent
1734 // id-expression.
1735 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001736 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1737 IsAddressOfOperand, TemplateArgs);
1738
John McCallf7a1a742009-11-24 19:00:30 +00001739 // If this reference is in an Objective-C method, then we need to do
1740 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001741 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001742 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001743 if (E.isInvalid())
1744 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattner337e5502011-02-18 01:27:55 +00001746 if (Expr *Ex = E.takeAs<Expr>())
1747 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001748 }
Chris Lattner8a934232008-03-31 00:36:02 +00001749 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001750
John McCallf7a1a742009-11-24 19:00:30 +00001751 if (R.isAmbiguous())
1752 return ExprError();
1753
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001754 // Determine whether this name might be a candidate for
1755 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001756 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001757
John McCallf7a1a742009-11-24 19:00:30 +00001758 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001760 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001762 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1763 if (D) R.addDecl(D);
1764 }
1765
1766 // If this name wasn't predeclared and if this is not a function
1767 // call, diagnose the problem.
1768 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001769
1770 // In Microsoft mode, if we are inside a template class member function
1771 // and we can't resolve an identifier then assume the identifier is type
1772 // dependent. The goal is to postpone name lookup to instantiation time
1773 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001774 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001775 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001776 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1777 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001778
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001779 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001780 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001781 return ExprError();
1782
1783 assert(!R.empty() &&
1784 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001785
1786 // If we found an Objective-C instance variable, let
1787 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001788 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001789 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1790 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001791 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001792 // In a hopelessly buggy code, Objective-C instance variable
1793 // lookup fails and no expression will be built to reference it.
1794 if (!E.isInvalid() && !E.get())
1795 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001796 return move(E);
1797 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 }
1799 }
Mike Stump1eb44332009-09-09 15:08:12 +00001800
John McCallf7a1a742009-11-24 19:00:30 +00001801 // This is guaranteed from this point on.
1802 assert(!R.empty() || ADL);
1803
John McCallaa81e162009-12-01 22:10:20 +00001804 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001805 // C++ [class.mfct.non-static]p3:
1806 // When an id-expression that is not part of a class member access
1807 // syntax and not used to form a pointer to member is used in the
1808 // body of a non-static member function of class X, if name lookup
1809 // resolves the name in the id-expression to a non-static non-type
1810 // member of some class C, the id-expression is transformed into a
1811 // class member access expression using (*this) as the
1812 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001813 //
1814 // But we don't actually need to do this for '&' operands if R
1815 // resolved to a function or overloaded function set, because the
1816 // expression is ill-formed if it actually works out to be a
1817 // non-static member function:
1818 //
1819 // C++ [expr.ref]p4:
1820 // Otherwise, if E1.E2 refers to a non-static member function. . .
1821 // [t]he expression can be used only as the left-hand operand of a
1822 // member function call.
1823 //
1824 // There are other safeguards against such uses, but it's important
1825 // to get this right here so that we don't end up making a
1826 // spuriously dependent expression if we're inside a dependent
1827 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001828 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001829 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001830 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001831 MightBeImplicitMember = true;
1832 else if (!SS.isEmpty())
1833 MightBeImplicitMember = false;
1834 else if (R.isOverloadedResult())
1835 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001836 else if (R.isUnresolvableResult())
1837 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001838 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001839 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1840 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001841
1842 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001843 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1844 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001845 }
1846
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001847 if (TemplateArgs || TemplateKWLoc.isValid())
1848 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001849
John McCallf7a1a742009-11-24 19:00:30 +00001850 return BuildDeclarationNameExpr(SS, R, ADL);
1851}
1852
John McCall129e2df2009-11-30 22:42:35 +00001853/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1854/// declaration name, generally during template instantiation.
1855/// There's a large number of things which don't need to be done along
1856/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001857ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001858Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001859 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001860 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001861 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001862 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1863 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001864
John McCall77bb1aa2010-05-01 00:40:08 +00001865 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001866 return ExprError();
1867
Abramo Bagnara25777432010-08-11 22:01:17 +00001868 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001869 LookupQualifiedName(R, DC);
1870
1871 if (R.isAmbiguous())
1872 return ExprError();
1873
1874 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001875 Diag(NameInfo.getLoc(), diag::err_no_member)
1876 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001877 return ExprError();
1878 }
1879
1880 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1881}
1882
1883/// LookupInObjCMethod - The parser has read a name in, and Sema has
1884/// detected that we're currently inside an ObjC method. Perform some
1885/// additional lookup.
1886///
1887/// Ideally, most of this would be done by lookup, but there's
1888/// actually quite a lot of extra work involved.
1889///
1890/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001891ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001892Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001893 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001894 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001895 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001896
John McCallf7a1a742009-11-24 19:00:30 +00001897 // There are two cases to handle here. 1) scoped lookup could have failed,
1898 // in which case we should look for an ivar. 2) scoped lookup could have
1899 // found a decl, but that decl is outside the current instance method (i.e.
1900 // a global variable). In these two cases, we do a lookup for an ivar with
1901 // this name, if the lookup sucedes, we replace it our current decl.
1902
1903 // If we're in a class method, we don't normally want to look for
1904 // ivars. But if we don't find anything else, and there's an
1905 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001906 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001907
1908 bool LookForIvars;
1909 if (Lookup.empty())
1910 LookForIvars = true;
1911 else if (IsClassMethod)
1912 LookForIvars = false;
1913 else
1914 LookForIvars = (Lookup.isSingleResult() &&
1915 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001916 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001917 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001918 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001919 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001920 ObjCIvarDecl *IV = 0;
1921 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001922 // Diagnose using an ivar in a class method.
1923 if (IsClassMethod)
1924 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1925 << IV->getDeclName());
1926
1927 // If we're referencing an invalid decl, just return this as a silent
1928 // error node. The error diagnostic was already emitted on the decl.
1929 if (IV->isInvalidDecl())
1930 return ExprError();
1931
1932 // Check if referencing a field with __attribute__((deprecated)).
1933 if (DiagnoseUseOfDecl(IV, Loc))
1934 return ExprError();
1935
1936 // Diagnose the use of an ivar outside of the declaring class.
1937 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001938 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001939 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001940 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1941
1942 // FIXME: This should use a new expr for a direct reference, don't
1943 // turn this into Self->ivar, just return a BareIVarExpr or something.
1944 IdentifierInfo &II = Context.Idents.get("self");
1945 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001946 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001947 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001948 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001949 SourceLocation TemplateKWLoc;
1950 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001951 SelfName, false, false);
1952 if (SelfExpr.isInvalid())
1953 return ExprError();
1954
John Wiegley429bb272011-04-08 18:41:53 +00001955 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1956 if (SelfExpr.isInvalid())
1957 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001958
Eli Friedman5f2987c2012-02-02 03:46:19 +00001959 MarkAnyDeclReferenced(Loc, IV);
John McCallf7a1a742009-11-24 19:00:30 +00001960 return Owned(new (Context)
1961 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001962 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001963 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001964 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001965 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001966 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1967 ObjCInterfaceDecl *ClassDeclared;
1968 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1969 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001970 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001971 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1972 }
John McCallf7a1a742009-11-24 19:00:30 +00001973 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001974 } else if (Lookup.isSingleResult() &&
1975 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1976 // If accessing a stand-alone ivar in a class method, this is an error.
1977 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1978 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1979 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001980 }
1981
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001982 if (Lookup.empty() && II && AllowBuiltinCreation) {
1983 // FIXME. Consolidate this with similar code in LookupName.
1984 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001985 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001986 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1987 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1988 S, Lookup.isForRedeclaration(),
1989 Lookup.getNameLoc());
1990 if (D) Lookup.addDecl(D);
1991 }
1992 }
1993 }
John McCallf7a1a742009-11-24 19:00:30 +00001994 // Sentinel value saying that we didn't do anything special.
1995 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001996}
John McCallba135432009-11-21 08:51:07 +00001997
John McCall6bb80172010-03-30 21:47:33 +00001998/// \brief Cast a base object to a member's actual type.
1999///
2000/// Logically this happens in three phases:
2001///
2002/// * First we cast from the base type to the naming class.
2003/// The naming class is the class into which we were looking
2004/// when we found the member; it's the qualifier type if a
2005/// qualifier was provided, and otherwise it's the base type.
2006///
2007/// * Next we cast from the naming class to the declaring class.
2008/// If the member we found was brought into a class's scope by
2009/// a using declaration, this is that class; otherwise it's
2010/// the class declaring the member.
2011///
2012/// * Finally we cast from the declaring class to the "true"
2013/// declaring class of the member. This conversion does not
2014/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002015ExprResult
2016Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002017 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002018 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002019 NamedDecl *Member) {
2020 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2021 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002022 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002023
Douglas Gregor5fccd362010-03-03 23:55:11 +00002024 QualType DestRecordType;
2025 QualType DestType;
2026 QualType FromRecordType;
2027 QualType FromType = From->getType();
2028 bool PointerConversions = false;
2029 if (isa<FieldDecl>(Member)) {
2030 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002031
Douglas Gregor5fccd362010-03-03 23:55:11 +00002032 if (FromType->getAs<PointerType>()) {
2033 DestType = Context.getPointerType(DestRecordType);
2034 FromRecordType = FromType->getPointeeType();
2035 PointerConversions = true;
2036 } else {
2037 DestType = DestRecordType;
2038 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002039 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002040 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2041 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002042 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002043
Douglas Gregor5fccd362010-03-03 23:55:11 +00002044 DestType = Method->getThisType(Context);
2045 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002046
Douglas Gregor5fccd362010-03-03 23:55:11 +00002047 if (FromType->getAs<PointerType>()) {
2048 FromRecordType = FromType->getPointeeType();
2049 PointerConversions = true;
2050 } else {
2051 FromRecordType = FromType;
2052 DestType = DestRecordType;
2053 }
2054 } else {
2055 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002056 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002057 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002058
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002060 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002061
Douglas Gregor5fccd362010-03-03 23:55:11 +00002062 // If the unqualified types are the same, no conversion is necessary.
2063 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002064 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002065
John McCall6bb80172010-03-30 21:47:33 +00002066 SourceRange FromRange = From->getSourceRange();
2067 SourceLocation FromLoc = FromRange.getBegin();
2068
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002069 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002070
Douglas Gregor5fccd362010-03-03 23:55:11 +00002071 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002072 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002073 // class name.
2074 //
2075 // If the member was a qualified name and the qualified referred to a
2076 // specific base subobject type, we'll cast to that intermediate type
2077 // first and then to the object in which the member is declared. That allows
2078 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2079 //
2080 // class Base { public: int x; };
2081 // class Derived1 : public Base { };
2082 // class Derived2 : public Base { };
2083 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2084 //
2085 // void VeryDerived::f() {
2086 // x = 17; // error: ambiguous base subobjects
2087 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2088 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002089 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002090 QualType QType = QualType(Qualifier->getAsType(), 0);
2091 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2092 assert(QType->isRecordType() && "lookup done with non-record type");
2093
2094 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2095
2096 // In C++98, the qualifier type doesn't actually have to be a base
2097 // type of the object type, in which case we just ignore it.
2098 // Otherwise build the appropriate casts.
2099 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002100 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002101 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002102 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002103 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002104
Douglas Gregor5fccd362010-03-03 23:55:11 +00002105 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002106 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002107 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2108 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002109
2110 FromType = QType;
2111 FromRecordType = QRecordType;
2112
2113 // If the qualifier type was the same as the destination type,
2114 // we're done.
2115 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002116 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002117 }
2118 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002119
John McCall6bb80172010-03-30 21:47:33 +00002120 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002121
John McCall6bb80172010-03-30 21:47:33 +00002122 // If we actually found the member through a using declaration, cast
2123 // down to the using declaration's type.
2124 //
2125 // Pointer equality is fine here because only one declaration of a
2126 // class ever has member declarations.
2127 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2128 assert(isa<UsingShadowDecl>(FoundDecl));
2129 QualType URecordType = Context.getTypeDeclType(
2130 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2131
2132 // We only need to do this if the naming-class to declaring-class
2133 // conversion is non-trivial.
2134 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2135 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002136 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002137 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002138 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002139 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002140
John McCall6bb80172010-03-30 21:47:33 +00002141 QualType UType = URecordType;
2142 if (PointerConversions)
2143 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002144 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2145 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002146 FromType = UType;
2147 FromRecordType = URecordType;
2148 }
2149
2150 // We don't do access control for the conversion from the
2151 // declaring class to the true declaring class.
2152 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002153 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002154
John McCallf871d0c2010-08-07 06:22:56 +00002155 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002156 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2157 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002158 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002159 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002160
John Wiegley429bb272011-04-08 18:41:53 +00002161 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2162 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002163}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002164
John McCallf7a1a742009-11-24 19:00:30 +00002165bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002166 const LookupResult &R,
2167 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002168 // Only when used directly as the postfix-expression of a call.
2169 if (!HasTrailingLParen)
2170 return false;
2171
2172 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002173 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002174 return false;
2175
2176 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002177 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002178 return false;
2179
2180 // Turn off ADL when we find certain kinds of declarations during
2181 // normal lookup:
2182 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2183 NamedDecl *D = *I;
2184
2185 // C++0x [basic.lookup.argdep]p3:
2186 // -- a declaration of a class member
2187 // Since using decls preserve this property, we check this on the
2188 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002189 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002190 return false;
2191
2192 // C++0x [basic.lookup.argdep]p3:
2193 // -- a block-scope function declaration that is not a
2194 // using-declaration
2195 // NOTE: we also trigger this for function templates (in fact, we
2196 // don't check the decl type at all, since all other decl types
2197 // turn off ADL anyway).
2198 if (isa<UsingShadowDecl>(D))
2199 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2200 else if (D->getDeclContext()->isFunctionOrMethod())
2201 return false;
2202
2203 // C++0x [basic.lookup.argdep]p3:
2204 // -- a declaration that is neither a function or a function
2205 // template
2206 // And also for builtin functions.
2207 if (isa<FunctionDecl>(D)) {
2208 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2209
2210 // But also builtin functions.
2211 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2212 return false;
2213 } else if (!isa<FunctionTemplateDecl>(D))
2214 return false;
2215 }
2216
2217 return true;
2218}
2219
2220
John McCallba135432009-11-21 08:51:07 +00002221/// Diagnoses obvious problems with the use of the given declaration
2222/// as an expression. This is only actually called for lookups that
2223/// were not overloaded, and it doesn't promise that the declaration
2224/// will in fact be used.
2225static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002226 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002227 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2228 return true;
2229 }
2230
2231 if (isa<ObjCInterfaceDecl>(D)) {
2232 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2233 return true;
2234 }
2235
2236 if (isa<NamespaceDecl>(D)) {
2237 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2238 return true;
2239 }
2240
2241 return false;
2242}
2243
John McCall60d7b3a2010-08-24 06:29:42 +00002244ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002245Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002246 LookupResult &R,
2247 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002248 // If this is a single, fully-resolved result and we don't need ADL,
2249 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002250 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002251 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2252 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002253
2254 // We only need to check the declaration if there's exactly one
2255 // result, because in the overloaded case the results can only be
2256 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002257 if (R.isSingleResult() &&
2258 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002259 return ExprError();
2260
John McCallc373d482010-01-27 01:50:18 +00002261 // Otherwise, just build an unresolved lookup expression. Suppress
2262 // any lookup-related diagnostics; we'll hash these out later, when
2263 // we've picked a target.
2264 R.suppressDiagnostics();
2265
John McCallba135432009-11-21 08:51:07 +00002266 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002267 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002268 SS.getWithLocInContext(Context),
2269 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002270 NeedsADL, R.isOverloadedResult(),
2271 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002272
2273 return Owned(ULE);
2274}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002275
John McCallba135432009-11-21 08:51:07 +00002276/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002277ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002278Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002279 const DeclarationNameInfo &NameInfo,
2280 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002281 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002282 assert(!isa<FunctionTemplateDecl>(D) &&
2283 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002284
Abramo Bagnara25777432010-08-11 22:01:17 +00002285 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002286 if (CheckDeclInExpr(*this, Loc, D))
2287 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002288
Douglas Gregor9af2f522009-12-01 16:58:18 +00002289 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2290 // Specifically diagnose references to class templates that are missing
2291 // a template argument list.
2292 Diag(Loc, diag::err_template_decl_ref)
2293 << Template << SS.getRange();
2294 Diag(Template->getLocation(), diag::note_template_decl_here);
2295 return ExprError();
2296 }
2297
2298 // Make sure that we're referring to a value.
2299 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2300 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002301 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002302 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002303 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002304 return ExprError();
2305 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002306
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002307 // Check whether this declaration can be used. Note that we suppress
2308 // this check when we're going to perform argument-dependent lookup
2309 // on this function name, because this might not be the function
2310 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002311 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002312 return ExprError();
2313
Steve Naroffdd972f22008-09-05 22:11:13 +00002314 // Only create DeclRefExpr's for valid Decl's.
2315 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002316 return ExprError();
2317
John McCall5808ce42011-02-03 08:15:49 +00002318 // Handle members of anonymous structs and unions. If we got here,
2319 // and the reference is to a class member indirect field, then this
2320 // must be the subject of a pointer-to-member expression.
2321 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2322 if (!indirectField->isCXXClassMember())
2323 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2324 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002325
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002326 {
John McCall76a40212011-02-09 01:13:10 +00002327 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002328 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002329
2330 switch (D->getKind()) {
2331 // Ignore all the non-ValueDecl kinds.
2332#define ABSTRACT_DECL(kind)
2333#define VALUE(type, base)
2334#define DECL(type, base) \
2335 case Decl::type:
2336#include "clang/AST/DeclNodes.inc"
2337 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002338
2339 // These shouldn't make it here.
2340 case Decl::ObjCAtDefsField:
2341 case Decl::ObjCIvar:
2342 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002343
2344 // Enum constants are always r-values and never references.
2345 // Unresolved using declarations are dependent.
2346 case Decl::EnumConstant:
2347 case Decl::UnresolvedUsingValue:
2348 valueKind = VK_RValue;
2349 break;
2350
2351 // Fields and indirect fields that got here must be for
2352 // pointer-to-member expressions; we just call them l-values for
2353 // internal consistency, because this subexpression doesn't really
2354 // exist in the high-level semantics.
2355 case Decl::Field:
2356 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002357 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002358 "building reference to field in C?");
2359
2360 // These can't have reference type in well-formed programs, but
2361 // for internal consistency we do this anyway.
2362 type = type.getNonReferenceType();
2363 valueKind = VK_LValue;
2364 break;
2365
2366 // Non-type template parameters are either l-values or r-values
2367 // depending on the type.
2368 case Decl::NonTypeTemplateParm: {
2369 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2370 type = reftype->getPointeeType();
2371 valueKind = VK_LValue; // even if the parameter is an r-value reference
2372 break;
2373 }
2374
2375 // For non-references, we need to strip qualifiers just in case
2376 // the template parameter was declared as 'const int' or whatever.
2377 valueKind = VK_RValue;
2378 type = type.getUnqualifiedType();
2379 break;
2380 }
2381
2382 case Decl::Var:
2383 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002384 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002385 !type.hasQualifiers() &&
2386 type->isVoidType()) {
2387 valueKind = VK_RValue;
2388 break;
2389 }
2390 // fallthrough
2391
2392 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002393 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002394 // These are always l-values.
2395 valueKind = VK_LValue;
2396 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002397
Douglas Gregor68932842012-02-18 05:51:20 +00002398 // FIXME: Does the addition of const really only apply in
2399 // potentially-evaluated contexts? Since the variable isn't actually
2400 // captured in an unevaluated context, it seems that the answer is no.
2401 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2402 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2403 if (!CapturedType.isNull())
2404 type = CapturedType;
2405 }
2406
John McCall76a40212011-02-09 01:13:10 +00002407 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002408 }
2409
John McCall76a40212011-02-09 01:13:10 +00002410 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002411 const FunctionType *fty = type->castAs<FunctionType>();
2412
2413 // If we're referring to a function with an __unknown_anytype
2414 // result type, make the entire expression __unknown_anytype.
2415 if (fty->getResultType() == Context.UnknownAnyTy) {
2416 type = Context.UnknownAnyTy;
2417 valueKind = VK_RValue;
2418 break;
2419 }
2420
John McCall76a40212011-02-09 01:13:10 +00002421 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002422 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002423 valueKind = VK_LValue;
2424 break;
2425 }
2426
2427 // C99 DR 316 says that, if a function type comes from a
2428 // function definition (without a prototype), that type is only
2429 // used for checking compatibility. Therefore, when referencing
2430 // the function, we pretend that we don't have the full function
2431 // type.
John McCall755d8492011-04-12 00:42:48 +00002432 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2433 isa<FunctionProtoType>(fty))
2434 type = Context.getFunctionNoProtoType(fty->getResultType(),
2435 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002436
2437 // Functions are r-values in C.
2438 valueKind = VK_RValue;
2439 break;
2440 }
2441
2442 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002443 // If we're referring to a method with an __unknown_anytype
2444 // result type, make the entire expression __unknown_anytype.
2445 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002446 if (const FunctionProtoType *proto
2447 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002448 if (proto->getResultType() == Context.UnknownAnyTy) {
2449 type = Context.UnknownAnyTy;
2450 valueKind = VK_RValue;
2451 break;
2452 }
2453
John McCall76a40212011-02-09 01:13:10 +00002454 // C++ methods are l-values if static, r-values if non-static.
2455 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2456 valueKind = VK_LValue;
2457 break;
2458 }
2459 // fallthrough
2460
2461 case Decl::CXXConversion:
2462 case Decl::CXXDestructor:
2463 case Decl::CXXConstructor:
2464 valueKind = VK_RValue;
2465 break;
2466 }
2467
2468 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2469 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002470}
2471
John McCall755d8492011-04-12 00:42:48 +00002472ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002473 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002474
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002476 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002477 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2478 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002479 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002480 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002482
Chris Lattnerfa28b302008-01-12 08:14:25 +00002483 // Pre-defined identifiers are of type char[x], where x is the length of the
2484 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Anders Carlsson3a082d82009-09-08 18:24:21 +00002486 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002487 if (!currentDecl && getCurBlock())
2488 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002489 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002490 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002491 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002492 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002493
Anders Carlsson773f3972009-09-11 01:22:35 +00002494 QualType ResTy;
2495 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2496 ResTy = Context.DependentTy;
2497 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002498 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002499
Anders Carlsson773f3972009-09-11 01:22:35 +00002500 llvm::APInt LengthI(32, Length + 1);
Nico Weber28ad0632012-06-23 02:07:59 +00002501 if (Kind == tok::kw_L__FUNCTION__)
2502 ResTy = Context.WCharTy.withConst();
2503 else
2504 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002505 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2506 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002507 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002508}
2509
Richard Smith36f5cfe2012-03-09 08:00:36 +00002510ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002511 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002512 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002513 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002514 if (Invalid)
2515 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002516
Benjamin Kramerddeea562010-02-27 13:44:12 +00002517 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002518 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002520 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002521
Chris Lattnere8337df2009-12-30 21:19:39 +00002522 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002523 if (Literal.isWide())
2524 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002525 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002526 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002527 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002528 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002529 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002530 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002531 else
2532 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002533
Douglas Gregor5cee1192011-07-27 05:40:30 +00002534 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2535 if (Literal.isWide())
2536 Kind = CharacterLiteral::Wide;
2537 else if (Literal.isUTF16())
2538 Kind = CharacterLiteral::UTF16;
2539 else if (Literal.isUTF32())
2540 Kind = CharacterLiteral::UTF32;
2541
Richard Smithdd66be72012-03-08 01:34:56 +00002542 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2543 Tok.getLocation());
2544
2545 if (Literal.getUDSuffix().empty())
2546 return Owned(Lit);
2547
2548 // We're building a user-defined literal.
2549 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2550 SourceLocation UDSuffixLoc =
2551 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2552
Richard Smith36f5cfe2012-03-09 08:00:36 +00002553 // Make sure we're allowed user-defined literals here.
2554 if (!UDLScope)
2555 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2556
Richard Smithdd66be72012-03-08 01:34:56 +00002557 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2558 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002559 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2560 llvm::makeArrayRef(&Lit, 1),
2561 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002562}
2563
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002564ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2565 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2566 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2567 Context.IntTy, Loc));
2568}
2569
Richard Smithb453ad32012-03-08 08:45:32 +00002570static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2571 QualType Ty, SourceLocation Loc) {
2572 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2573
2574 using llvm::APFloat;
2575 APFloat Val(Format);
2576
2577 APFloat::opStatus result = Literal.GetFloatValue(Val);
2578
2579 // Overflow is always an error, but underflow is only an error if
2580 // we underflowed to zero (APFloat reports denormals as underflow).
2581 if ((result & APFloat::opOverflow) ||
2582 ((result & APFloat::opUnderflow) && Val.isZero())) {
2583 unsigned diagnostic;
2584 SmallString<20> buffer;
2585 if (result & APFloat::opOverflow) {
2586 diagnostic = diag::warn_float_overflow;
2587 APFloat::getLargest(Format).toString(buffer);
2588 } else {
2589 diagnostic = diag::warn_float_underflow;
2590 APFloat::getSmallest(Format).toString(buffer);
2591 }
2592
2593 S.Diag(Loc, diagnostic)
2594 << Ty
2595 << StringRef(buffer.data(), buffer.size());
2596 }
2597
2598 bool isExact = (result == APFloat::opOK);
2599 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2600}
2601
Richard Smith36f5cfe2012-03-09 08:00:36 +00002602ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002603 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002604 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002606 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002607 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 }
Ted Kremenek28396602009-01-13 23:19:12 +00002609
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002610 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002611 // Add padding so that NumericLiteralParser can overread by one character.
2612 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002614
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002616 bool Invalid = false;
2617 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2618 if (Invalid)
2619 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002620
Mike Stump1eb44332009-09-09 15:08:12 +00002621 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 Tok.getLocation(), PP);
2623 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002624 return ExprError();
2625
Richard Smithb453ad32012-03-08 08:45:32 +00002626 if (Literal.hasUDSuffix()) {
2627 // We're building a user-defined literal.
2628 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2629 SourceLocation UDSuffixLoc =
2630 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2631
Richard Smith36f5cfe2012-03-09 08:00:36 +00002632 // Make sure we're allowed user-defined literals here.
2633 if (!UDLScope)
2634 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002635
Richard Smith36f5cfe2012-03-09 08:00:36 +00002636 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002637 if (Literal.isFloatingLiteral()) {
2638 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2639 // long double, the literal is treated as a call of the form
2640 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002641 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002642 } else {
2643 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2644 // unsigned long long, the literal is treated as a call of the form
2645 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002646 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002647 }
2648
Richard Smith36f5cfe2012-03-09 08:00:36 +00002649 DeclarationName OpName =
2650 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2651 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2652 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2653
2654 // Perform literal operator lookup to determine if we're building a raw
2655 // literal or a cooked one.
2656 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2657 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2658 /*AllowRawAndTemplate*/true)) {
2659 case LOLR_Error:
2660 return ExprError();
2661
2662 case LOLR_Cooked: {
2663 Expr *Lit;
2664 if (Literal.isFloatingLiteral()) {
2665 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2666 } else {
2667 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2668 if (Literal.GetIntegerValue(ResultVal))
2669 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2670 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2671 Tok.getLocation());
2672 }
2673 return BuildLiteralOperatorCall(R, OpNameInfo,
2674 llvm::makeArrayRef(&Lit, 1),
2675 Tok.getLocation());
2676 }
2677
2678 case LOLR_Raw: {
2679 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2680 // literal is treated as a call of the form
2681 // operator "" X ("n")
2682 SourceLocation TokLoc = Tok.getLocation();
2683 unsigned Length = Literal.getUDSuffixOffset();
2684 QualType StrTy = Context.getConstantArrayType(
2685 Context.CharTy, llvm::APInt(32, Length + 1),
2686 ArrayType::Normal, 0);
2687 Expr *Lit = StringLiteral::Create(
2688 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2689 /*Pascal*/false, StrTy, &TokLoc, 1);
2690 return BuildLiteralOperatorCall(R, OpNameInfo,
2691 llvm::makeArrayRef(&Lit, 1), TokLoc);
2692 }
2693
2694 case LOLR_Template:
2695 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2696 // template), L is treated as a call fo the form
2697 // operator "" X <'c1', 'c2', ... 'ck'>()
2698 // where n is the source character sequence c1 c2 ... ck.
2699 TemplateArgumentListInfo ExplicitArgs;
2700 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2701 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2702 llvm::APSInt Value(CharBits, CharIsUnsigned);
2703 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2704 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002705 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002706 TemplateArgumentLocInfo ArgInfo;
2707 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2708 }
2709 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2710 Tok.getLocation(), &ExplicitArgs);
2711 }
2712
2713 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002714 }
2715
Chris Lattner5d661452007-08-26 03:42:43 +00002716 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002717
Chris Lattner5d661452007-08-26 03:42:43 +00002718 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002719 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002720 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002721 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002722 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002723 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002724 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002725 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002726
Richard Smithb453ad32012-03-08 08:45:32 +00002727 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002728
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002729 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002730 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002731 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002732 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002733 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002734 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002735 }
2736 }
Chris Lattner5d661452007-08-26 03:42:43 +00002737 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002738 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002739 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002740 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002741
Neil Boothb9449512007-08-29 22:00:19 +00002742 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002743 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002744 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002745 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002746 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002747
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002749 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2750 // The microsoft literal suffix extensions support 128-bit literals, which
2751 // may be wider than [u]intmax_t.
2752 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2753 MaxWidth = 128;
2754 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002755
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 if (Literal.GetIntegerValue(ResultVal)) {
2757 // If this value didn't fit into uintmax_t, warn and force to ull.
2758 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002759 Ty = Context.UnsignedLongLongTy;
2760 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002761 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 } else {
2763 // If this value fits into a ULL, try to figure out what else it fits into
2764 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002765
Reid Spencer5f016e22007-07-11 17:01:13 +00002766 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2767 // be an unsigned int.
2768 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2769
2770 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002771 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002772 if (!Literal.isLong && !Literal.isLongLong) {
2773 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002774 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002775
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 // Does it fit in a unsigned int?
2777 if (ResultVal.isIntN(IntSize)) {
2778 // Does it fit in a signed int?
2779 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002780 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002782 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002783 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002786
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002788 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002789 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002790
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 // Does it fit in a unsigned long?
2792 if (ResultVal.isIntN(LongSize)) {
2793 // Does it fit in a signed long?
2794 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002795 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002797 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002798 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002800 }
2801
Stephen Canonb9e05f12012-05-03 22:49:43 +00002802 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002804 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002805
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 // Does it fit in a unsigned long long?
2807 if (ResultVal.isIntN(LongLongSize)) {
2808 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002809 // To be compatible with MSVC, hex integer literals ending with the
2810 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002811 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002812 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002813 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002815 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002816 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 }
2818 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002819
2820 // If it doesn't fit in unsigned long long, and we're using Microsoft
2821 // extensions, then its a 128-bit integer literal.
2822 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2823 if (Literal.isUnsigned)
2824 Ty = Context.UnsignedInt128Ty;
2825 else
2826 Ty = Context.Int128Ty;
2827 Width = 128;
2828 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002829
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 // If we still couldn't decide a type, we probably have something that
2831 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002832 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002834 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002835 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002837
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002838 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002839 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002841 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002843
Chris Lattner5d661452007-08-26 03:42:43 +00002844 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2845 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002846 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002847 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002848
2849 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002850}
2851
Richard Trieuccd891a2011-09-09 01:45:06 +00002852ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002853 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002854 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002855}
2856
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002857static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2858 SourceLocation Loc,
2859 SourceRange ArgRange) {
2860 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2861 // scalar or vector data type argument..."
2862 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2863 // type (C99 6.2.5p18) or void.
2864 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2865 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2866 << T << ArgRange;
2867 return true;
2868 }
2869
2870 assert((T->isVoidType() || !T->isIncompleteType()) &&
2871 "Scalar types should always be complete");
2872 return false;
2873}
2874
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002875static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2876 SourceLocation Loc,
2877 SourceRange ArgRange,
2878 UnaryExprOrTypeTrait TraitKind) {
2879 // C99 6.5.3.4p1:
2880 if (T->isFunctionType()) {
2881 // alignof(function) is allowed as an extension.
2882 if (TraitKind == UETT_SizeOf)
2883 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2884 return false;
2885 }
2886
2887 // Allow sizeof(void)/alignof(void) as an extension.
2888 if (T->isVoidType()) {
2889 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2890 return false;
2891 }
2892
2893 return true;
2894}
2895
2896static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2897 SourceLocation Loc,
2898 SourceRange ArgRange,
2899 UnaryExprOrTypeTrait TraitKind) {
2900 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall260611a2012-06-20 06:18:46 +00002901 if (S.LangOpts.ObjCRuntime.isNonFragile() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002902 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2903 << T << (TraitKind == UETT_SizeOf)
2904 << ArgRange;
2905 return true;
2906 }
2907
2908 return false;
2909}
2910
Chandler Carruth9d342d02011-05-26 08:53:10 +00002911/// \brief Check the constrains on expression operands to unary type expression
2912/// and type traits.
2913///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002914/// Completes any types necessary and validates the constraints on the operand
2915/// expression. The logic mostly mirrors the type-based overload, but may modify
2916/// the expression as it completes the type for that expression through template
2917/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002918bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002919 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002920 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002921
2922 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2923 // the result is the size of the referenced type."
2924 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2925 // result shall be the alignment of the referenced type."
2926 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2927 ExprTy = Ref->getPointeeType();
2928
2929 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002930 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2931 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002932
2933 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002934 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2935 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002936 return false;
2937
Richard Trieuccd891a2011-09-09 01:45:06 +00002938 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002939 diag::err_sizeof_alignof_incomplete_type,
2940 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002941 return true;
2942
2943 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002944 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002945 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2946 ExprTy = Ref->getPointeeType();
2947
Richard Trieuccd891a2011-09-09 01:45:06 +00002948 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2949 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002950 return true;
2951
Nico Webercf739922011-06-15 02:47:03 +00002952 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002953 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002954 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2955 QualType OType = PVD->getOriginalType();
2956 QualType Type = PVD->getType();
2957 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002958 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002959 << Type << OType;
2960 Diag(PVD->getLocation(), diag::note_declared_at);
2961 }
2962 }
2963 }
2964 }
2965
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002966 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002967}
2968
2969/// \brief Check the constraints on operands to unary expression and type
2970/// traits.
2971///
2972/// This will complete any types necessary, and validate the various constraints
2973/// on those operands.
2974///
Reid Spencer5f016e22007-07-11 17:01:13 +00002975/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002976/// C99 6.3.2.1p[2-4] all state:
2977/// Except when it is the operand of the sizeof operator ...
2978///
2979/// C++ [expr.sizeof]p4
2980/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2981/// standard conversions are not applied to the operand of sizeof.
2982///
2983/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002984bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002985 SourceLocation OpLoc,
2986 SourceRange ExprRange,
2987 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002988 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002989 return false;
2990
Sebastian Redl5d484e82009-11-23 17:18:46 +00002991 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2992 // the result is the size of the referenced type."
2993 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2994 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00002995 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2996 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00002997
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002998 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002999 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003000
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003001 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003002 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003003 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003004 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Richard Trieuccd891a2011-09-09 01:45:06 +00003006 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003007 diag::err_sizeof_alignof_incomplete_type,
3008 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003009 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Richard Trieuccd891a2011-09-09 01:45:06 +00003011 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003012 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003013 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Chris Lattner1efaa952009-04-24 00:30:45 +00003015 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003016}
3017
Chandler Carruth9d342d02011-05-26 08:53:10 +00003018static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003019 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003020
Mike Stump1eb44332009-09-09 15:08:12 +00003021 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003022 if (isa<DeclRefExpr>(E))
3023 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003024
3025 // Cannot know anything else if the expression is dependent.
3026 if (E->isTypeDependent())
3027 return false;
3028
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003029 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003030 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3031 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003032 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003033 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003034
3035 // Alignment of a field access is always okay, so long as it isn't a
3036 // bit-field.
3037 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003038 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003039 return false;
3040
Chandler Carruth9d342d02011-05-26 08:53:10 +00003041 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003042}
3043
Chandler Carruth9d342d02011-05-26 08:53:10 +00003044bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003045 E = E->IgnoreParens();
3046
3047 // Cannot know anything else if the expression is dependent.
3048 if (E->isTypeDependent())
3049 return false;
3050
Chandler Carruth9d342d02011-05-26 08:53:10 +00003051 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003052}
3053
Douglas Gregorba498172009-03-13 21:01:28 +00003054/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003055ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003056Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3057 SourceLocation OpLoc,
3058 UnaryExprOrTypeTrait ExprKind,
3059 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003060 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003061 return ExprError();
3062
John McCalla93c9342009-12-07 02:54:59 +00003063 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003064
Douglas Gregorba498172009-03-13 21:01:28 +00003065 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003066 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003067 return ExprError();
3068
3069 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003070 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3071 Context.getSizeType(),
3072 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003073}
3074
3075/// \brief Build a sizeof or alignof expression given an expression
3076/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003077ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003078Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3079 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003080 ExprResult PE = CheckPlaceholderExpr(E);
3081 if (PE.isInvalid())
3082 return ExprError();
3083
3084 E = PE.get();
3085
Douglas Gregorba498172009-03-13 21:01:28 +00003086 // Verify that the operand is valid.
3087 bool isInvalid = false;
3088 if (E->isTypeDependent()) {
3089 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003090 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003091 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003092 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003093 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003094 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003096 isInvalid = true;
3097 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003098 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003099 }
3100
3101 if (isInvalid)
3102 return ExprError();
3103
Eli Friedman71b8fb52012-01-21 01:01:51 +00003104 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3105 PE = TranformToPotentiallyEvaluated(E);
3106 if (PE.isInvalid()) return ExprError();
3107 E = PE.take();
3108 }
3109
Douglas Gregorba498172009-03-13 21:01:28 +00003110 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003111 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003112 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003113 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003114}
3115
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003116/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3117/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003118/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003119ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003120Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003121 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003122 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003123 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003124 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003125
Richard Trieuccd891a2011-09-09 01:45:06 +00003126 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003127 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003128 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003130 }
Sebastian Redl05189992008-11-11 17:56:53 +00003131
Douglas Gregorba498172009-03-13 21:01:28 +00003132 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003133 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003134 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003135}
3136
John Wiegley429bb272011-04-08 18:41:53 +00003137static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003138 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003139 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003140 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
John McCallf6a16482010-12-04 03:47:34 +00003142 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003143 if (V.get()->getObjectKind() != OK_Ordinary) {
3144 V = S.DefaultLvalueConversion(V.take());
3145 if (V.isInvalid())
3146 return QualType();
3147 }
John McCallf6a16482010-12-04 03:47:34 +00003148
Chris Lattnercc26ed72007-08-26 05:39:26 +00003149 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003150 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003151 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Chris Lattnercc26ed72007-08-26 05:39:26 +00003153 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003154 if (V.get()->getType()->isArithmeticType())
3155 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003156
John McCall2cd11fe2010-10-12 02:09:17 +00003157 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003158 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003159 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003160 if (PR.get() != V.get()) {
3161 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00003162 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003163 }
3164
Chris Lattnercc26ed72007-08-26 05:39:26 +00003165 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003166 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003167 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003168 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003169}
3170
3171
Reid Spencer5f016e22007-07-11 17:01:13 +00003172
John McCall60d7b3a2010-08-24 06:29:42 +00003173ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003174Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003175 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003176 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003177 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003178 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003179 case tok::plusplus: Opc = UO_PostInc; break;
3180 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003181 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003182
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003183 // Since this might is a postfix expression, get rid of ParenListExprs.
3184 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3185 if (Result.isInvalid()) return ExprError();
3186 Input = Result.take();
3187
John McCall9ae2f072010-08-23 23:25:46 +00003188 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003189}
3190
John McCall60d7b3a2010-08-24 06:29:42 +00003191ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003192Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3193 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003194 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003195 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003196 if (Result.isInvalid()) return ExprError();
3197 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003198
John McCall9ae2f072010-08-23 23:25:46 +00003199 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003200
David Blaikie4e4d0842012-03-11 07:00:24 +00003201 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003202 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003203 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003204 Context.DependentTy,
3205 VK_LValue, OK_Ordinary,
3206 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003207 }
3208
David Blaikie4e4d0842012-03-11 07:00:24 +00003209 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003210 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003211 LHSExp->getType()->isEnumeralType() ||
3212 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003213 RHSExp->getType()->isEnumeralType()) &&
3214 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003215 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003216 }
3217
John McCall9ae2f072010-08-23 23:25:46 +00003218 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003219}
3220
3221
John McCall60d7b3a2010-08-24 06:29:42 +00003222ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003223Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003224 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003225 Expr *LHSExp = Base;
3226 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003227
Chris Lattner12d9ff62007-07-16 00:14:47 +00003228 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003229 if (!LHSExp->getType()->getAs<VectorType>()) {
3230 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3231 if (Result.isInvalid())
3232 return ExprError();
3233 LHSExp = Result.take();
3234 }
3235 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3236 if (Result.isInvalid())
3237 return ExprError();
3238 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003239
Chris Lattner12d9ff62007-07-16 00:14:47 +00003240 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003241 ExprValueKind VK = VK_LValue;
3242 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003243
Reid Spencer5f016e22007-07-11 17:01:13 +00003244 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003245 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003246 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003247 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003248 Expr *BaseExpr, *IndexExpr;
3249 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003250 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3251 BaseExpr = LHSExp;
3252 IndexExpr = RHSExp;
3253 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003254 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003255 BaseExpr = LHSExp;
3256 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003257 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003258 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003259 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003260 BaseExpr = LHSExp;
3261 IndexExpr = RHSExp;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003262 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3263 if (!Result.isInvalid())
3264 return Owned(Result.take());
Steve Naroff14108da2009-07-10 23:34:53 +00003265 ResultType = PTy->getPointeeType();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003266 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3267 // Handle the uncommon case of "123[Ptr]".
3268 BaseExpr = RHSExp;
3269 IndexExpr = LHSExp;
3270 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003271 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003272 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003273 // Handle the uncommon case of "123[Ptr]".
3274 BaseExpr = RHSExp;
3275 IndexExpr = LHSExp;
3276 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003277 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003278 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003279 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003280 VK = LHSExp->getValueKind();
3281 if (VK != VK_RValue)
3282 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003283
Chris Lattner12d9ff62007-07-16 00:14:47 +00003284 // FIXME: need to deal with const...
3285 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003286 } else if (LHSTy->isArrayType()) {
3287 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003288 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003289 // wasn't promoted because of the C90 rule that doesn't
3290 // allow promoting non-lvalue arrays. Warn, then
3291 // force the promotion here.
3292 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3293 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003294 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3295 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003296 LHSTy = LHSExp->getType();
3297
3298 BaseExpr = LHSExp;
3299 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003300 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003301 } else if (RHSTy->isArrayType()) {
3302 // Same as previous, except for 123[f().a] case
3303 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3304 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003305 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3306 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003307 RHSTy = RHSExp->getType();
3308
3309 BaseExpr = RHSExp;
3310 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003311 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003312 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003313 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3314 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003315 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003316 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003317 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003318 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3319 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003320
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003321 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003322 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3323 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003324 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3325
Douglas Gregore7450f52009-03-24 19:52:54 +00003326 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003327 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3328 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003329 // incomplete types are not object types.
3330 if (ResultType->isFunctionType()) {
3331 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3332 << ResultType << BaseExpr->getSourceRange();
3333 return ExprError();
3334 }
Mike Stump1eb44332009-09-09 15:08:12 +00003335
David Blaikie4e4d0842012-03-11 07:00:24 +00003336 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003337 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003338 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3339 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003340
3341 // C forbids expressions of unqualified void type from being l-values.
3342 // See IsCForbiddenLValueType.
3343 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003344 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003345 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003346 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003347 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Chris Lattner1efaa952009-04-24 00:30:45 +00003349 // Diagnose bad cases where we step over interface counts.
John McCall260611a2012-06-20 06:18:46 +00003350 if (ResultType->isObjCObjectType() && LangOpts.ObjCRuntime.isNonFragile()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003351 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3352 << ResultType << BaseExpr->getSourceRange();
3353 return ExprError();
3354 }
Mike Stump1eb44332009-09-09 15:08:12 +00003355
John McCall09431682010-11-18 19:01:18 +00003356 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003357 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003358
Mike Stumpeed9cac2009-02-19 03:04:26 +00003359 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003360 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003361}
3362
John McCall60d7b3a2010-08-24 06:29:42 +00003363ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003364 FunctionDecl *FD,
3365 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003366 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003367 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003368 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003369 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003370 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003371 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003372 return ExprError();
3373 }
3374
3375 if (Param->hasUninstantiatedDefaultArg()) {
3376 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003377
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003378 // Instantiate the expression.
3379 MultiLevelTemplateArgumentList ArgList
3380 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003381
Nico Weber08e41a62010-11-29 18:19:25 +00003382 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003383 = ArgList.getInnermost();
3384 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3385 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003386
Nico Weber08e41a62010-11-29 18:19:25 +00003387 ExprResult Result;
3388 {
3389 // C++ [dcl.fct.default]p5:
3390 // The names in the [default argument] expression are bound, and
3391 // the semantic constraints are checked, at the point where the
3392 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003393 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003394 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003395 Result = SubstExpr(UninstExpr, ArgList);
3396 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003397 if (Result.isInvalid())
3398 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003399
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003400 // Check the expression as an initializer for the parameter.
3401 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003402 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003403 InitializationKind Kind
3404 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003405 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003406 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003407
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003408 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3409 Result = InitSeq.Perform(*this, Entity, Kind,
3410 MultiExprArg(*this, &ResultE, 1));
3411 if (Result.isInvalid())
3412 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003413
David Blaikiec1c07252012-04-30 18:21:31 +00003414 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003415 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003416 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003417 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003418 }
3419
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003420 // If the default expression creates temporaries, we need to
3421 // push them to the current stack of expression temporaries so they'll
3422 // be properly destroyed.
3423 // FIXME: We should really be rebuilding the default argument with new
3424 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003425 // We don't need to do that with block decls, though, because
3426 // blocks in default argument expression can never capture anything.
3427 if (isa<ExprWithCleanups>(Param->getInit())) {
3428 // Set the "needs cleanups" bit regardless of whether there are
3429 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003430 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003431
3432 // Append all the objects to the cleanup list. Right now, this
3433 // should always be a no-op, because blocks in default argument
3434 // expressions should never be able to capture anything.
3435 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3436 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003437 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003438
3439 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003440 // Just mark all of the declarations in this potentially-evaluated expression
3441 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003442 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3443 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003444 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003445}
3446
Richard Smith831421f2012-06-25 20:30:08 +00003447
3448Sema::VariadicCallType
3449Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3450 Expr *Fn) {
3451 if (Proto && Proto->isVariadic()) {
3452 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3453 return VariadicConstructor;
3454 else if (Fn && Fn->getType()->isBlockPointerType())
3455 return VariadicBlock;
3456 else if (FDecl) {
3457 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3458 if (Method->isInstance())
3459 return VariadicMethod;
3460 }
3461 return VariadicFunction;
3462 }
3463 return VariadicDoesNotApply;
3464}
3465
Douglas Gregor88a35142008-12-22 05:46:06 +00003466/// ConvertArgumentsForCall - Converts the arguments specified in
3467/// Args/NumArgs to the parameter types of the function FDecl with
3468/// function prototype Proto. Call is the call expression itself, and
3469/// Fn is the function expression. For a C++ member function, this
3470/// routine does not attempt to convert the object argument. Returns
3471/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003472bool
3473Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003474 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003475 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003476 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003477 SourceLocation RParenLoc,
3478 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003479 // Bail out early if calling a builtin with custom typechecking.
3480 // We don't need to do this in the
3481 if (FDecl)
3482 if (unsigned ID = FDecl->getBuiltinID())
3483 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3484 return false;
3485
Mike Stumpeed9cac2009-02-19 03:04:26 +00003486 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003487 // assignment, to the types of the corresponding parameter, ...
3488 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003489 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003490 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003491 unsigned FnKind = Fn->getType()->isBlockPointerType()
3492 ? 1 /* block */
3493 : (IsExecConfig ? 3 /* kernel function (exec config) */
3494 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003495
Douglas Gregor88a35142008-12-22 05:46:06 +00003496 // If too few arguments are available (and we don't have default
3497 // arguments for the remaining parameters), don't make the call.
3498 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003499 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003500 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3501 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3502 ? diag::err_typecheck_call_too_few_args_one
3503 : diag::err_typecheck_call_too_few_args_at_least_one)
3504 << FnKind
3505 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3506 else
3507 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3508 ? diag::err_typecheck_call_too_few_args
3509 : diag::err_typecheck_call_too_few_args_at_least)
3510 << FnKind
3511 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003512
3513 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003514 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003515 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3516 << FDecl;
3517
3518 return true;
3519 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003520 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 }
3522
3523 // If too many are passed and not variadic, error on the extras and drop
3524 // them.
3525 if (NumArgs > NumArgsInProto) {
3526 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003527 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3528 Diag(Args[NumArgsInProto]->getLocStart(),
3529 MinArgs == NumArgsInProto
3530 ? diag::err_typecheck_call_too_many_args_one
3531 : diag::err_typecheck_call_too_many_args_at_most_one)
3532 << FnKind
3533 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3534 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3535 Args[NumArgs-1]->getLocEnd());
3536 else
3537 Diag(Args[NumArgsInProto]->getLocStart(),
3538 MinArgs == NumArgsInProto
3539 ? diag::err_typecheck_call_too_many_args
3540 : diag::err_typecheck_call_too_many_args_at_most)
3541 << FnKind
3542 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3543 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3544 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003545
3546 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003547 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003548 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3549 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003550
Douglas Gregor88a35142008-12-22 05:46:06 +00003551 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003552 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003553 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003554 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003555 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003556 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003557 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3558
Daniel Dunbar96a00142012-03-09 18:35:03 +00003559 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003560 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003561 if (Invalid)
3562 return true;
3563 unsigned TotalNumArgs = AllArgs.size();
3564 for (unsigned i = 0; i < TotalNumArgs; ++i)
3565 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003566
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003567 return false;
3568}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003569
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003570bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3571 FunctionDecl *FDecl,
3572 const FunctionProtoType *Proto,
3573 unsigned FirstProtoArg,
3574 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003575 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003576 VariadicCallType CallType,
3577 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003578 unsigned NumArgsInProto = Proto->getNumArgs();
3579 unsigned NumArgsToCheck = NumArgs;
3580 bool Invalid = false;
3581 if (NumArgs != NumArgsInProto)
3582 // Use default arguments for missing arguments
3583 NumArgsToCheck = NumArgsInProto;
3584 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003585 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003586 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003588
Douglas Gregor88a35142008-12-22 05:46:06 +00003589 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003590 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003591 if (ArgIx < NumArgs) {
3592 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003593
Daniel Dunbar96a00142012-03-09 18:35:03 +00003594 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003595 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003596 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003597 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003598
Douglas Gregora188ff22009-12-22 16:09:06 +00003599 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003600 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003601 if (FDecl && i < FDecl->getNumParams())
3602 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003603
John McCall5acb0c92011-10-17 18:40:02 +00003604 // Strip the unbridged-cast placeholder expression off, if applicable.
3605 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3606 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3607 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3608 Arg = stripARCUnbridgedCast(Arg);
3609
Douglas Gregora188ff22009-12-22 16:09:06 +00003610 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003611 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003612 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3613 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003614 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003615 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003616 Owned(Arg),
3617 /*TopLevelOfInitList=*/false,
3618 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003619 if (ArgE.isInvalid())
3620 return true;
3621
3622 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003623 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003624 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003625
John McCall60d7b3a2010-08-24 06:29:42 +00003626 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003627 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003628 if (ArgExpr.isInvalid())
3629 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003630
Anders Carlsson56c5e332009-08-25 03:49:14 +00003631 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003632 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003633
3634 // Check for array bounds violations for each argument to the call. This
3635 // check only triggers warnings when the argument isn't a more complex Expr
3636 // with its own checking, such as a BinaryOperator.
3637 CheckArrayAccess(Arg);
3638
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003639 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3640 CheckStaticArrayArgument(CallLoc, Param, Arg);
3641
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003642 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003643 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003644
Douglas Gregor88a35142008-12-22 05:46:06 +00003645 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003646 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003647 // Assume that extern "C" functions with variadic arguments that
3648 // return __unknown_anytype aren't *really* variadic.
3649 if (Proto->getResultType() == Context.UnknownAnyTy &&
3650 FDecl && FDecl->isExternC()) {
3651 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3652 ExprResult arg;
3653 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3654 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3655 else
3656 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3657 Invalid |= arg.isInvalid();
3658 AllArgs.push_back(arg.take());
3659 }
3660
3661 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3662 } else {
3663 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003664 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3665 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003666 Invalid |= Arg.isInvalid();
3667 AllArgs.push_back(Arg.take());
3668 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003669 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003670
3671 // Check for array bounds violations.
3672 for (unsigned i = ArgIx; i != NumArgs; ++i)
3673 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003674 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003675 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003676}
3677
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003678static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3679 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3680 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3681 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3682 << ATL->getLocalSourceRange();
3683}
3684
3685/// CheckStaticArrayArgument - If the given argument corresponds to a static
3686/// array parameter, check that it is non-null, and that if it is formed by
3687/// array-to-pointer decay, the underlying array is sufficiently large.
3688///
3689/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3690/// array type derivation, then for each call to the function, the value of the
3691/// corresponding actual argument shall provide access to the first element of
3692/// an array with at least as many elements as specified by the size expression.
3693void
3694Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3695 ParmVarDecl *Param,
3696 const Expr *ArgExpr) {
3697 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003698 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003699 return;
3700
3701 QualType OrigTy = Param->getOriginalType();
3702
3703 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3704 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3705 return;
3706
3707 if (ArgExpr->isNullPointerConstant(Context,
3708 Expr::NPC_NeverValueDependent)) {
3709 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3710 DiagnoseCalleeStaticArrayParam(*this, Param);
3711 return;
3712 }
3713
3714 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3715 if (!CAT)
3716 return;
3717
3718 const ConstantArrayType *ArgCAT =
3719 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3720 if (!ArgCAT)
3721 return;
3722
3723 if (ArgCAT->getSize().ult(CAT->getSize())) {
3724 Diag(CallLoc, diag::warn_static_array_too_small)
3725 << ArgExpr->getSourceRange()
3726 << (unsigned) ArgCAT->getSize().getZExtValue()
3727 << (unsigned) CAT->getSize().getZExtValue();
3728 DiagnoseCalleeStaticArrayParam(*this, Param);
3729 }
3730}
3731
John McCall755d8492011-04-12 00:42:48 +00003732/// Given a function expression of unknown-any type, try to rebuild it
3733/// to have a function type.
3734static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3735
Steve Narofff69936d2007-09-16 03:34:24 +00003736/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003737/// This provides the location of the left/right parens and a list of comma
3738/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003739ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003740Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003741 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003742 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003743 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003744
3745 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003746 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003747 if (Result.isInvalid()) return ExprError();
3748 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Richard Trieuccd891a2011-09-09 01:45:06 +00003750 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003751
David Blaikie4e4d0842012-03-11 07:00:24 +00003752 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003753 // If this is a pseudo-destructor expression, build the call immediately.
3754 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3755 if (NumArgs > 0) {
3756 // Pseudo-destructor calls should not have any arguments.
3757 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003758 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003759 SourceRange(Args[0]->getLocStart(),
3760 Args[NumArgs-1]->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Douglas Gregora71d8192009-09-04 17:36:40 +00003763 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003764 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Douglas Gregor17330012009-02-04 15:01:18 +00003767 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003768 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003769 // FIXME: Will need to cache the results of name lookup (including ADL) in
3770 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003771 bool Dependent = false;
3772 if (Fn->isTypeDependent())
3773 Dependent = true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003774 else if (Expr::hasAnyTypeDependentArguments(
3775 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregor17330012009-02-04 15:01:18 +00003776 Dependent = true;
3777
Peter Collingbournee08ce652011-02-09 21:07:24 +00003778 if (Dependent) {
3779 if (ExecConfig) {
3780 return Owned(new (Context) CUDAKernelCallExpr(
3781 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3782 Context.DependentTy, VK_RValue, RParenLoc));
3783 } else {
3784 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3785 Context.DependentTy, VK_RValue,
3786 RParenLoc));
3787 }
3788 }
Douglas Gregor17330012009-02-04 15:01:18 +00003789
3790 // Determine whether this is a call to an object (C++ [over.call.object]).
3791 if (Fn->getType()->isRecordType())
3792 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003793 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003794
John McCall755d8492011-04-12 00:42:48 +00003795 if (Fn->getType() == Context.UnknownAnyTy) {
3796 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3797 if (result.isInvalid()) return ExprError();
3798 Fn = result.take();
3799 }
3800
John McCall864c0412011-04-26 20:42:42 +00003801 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003802 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003803 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003804 }
John McCall864c0412011-04-26 20:42:42 +00003805 }
John McCall129e2df2009-11-30 22:42:35 +00003806
John McCall864c0412011-04-26 20:42:42 +00003807 // Check for overloaded calls. This can happen even in C due to extensions.
3808 if (Fn->getType() == Context.OverloadTy) {
3809 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3810
Douglas Gregoree697e62011-10-13 18:10:35 +00003811 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003812 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003813 OverloadExpr *ovl = find.Expression;
3814 if (isa<UnresolvedLookupExpr>(ovl)) {
3815 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3816 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3817 RParenLoc, ExecConfig);
3818 } else {
John McCallaa81e162009-12-01 22:10:20 +00003819 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003820 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003821 }
3822 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003823 }
3824
Douglas Gregorfa047642009-02-04 00:32:51 +00003825 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003826 if (Fn->getType() == Context.UnknownAnyTy) {
3827 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3828 if (result.isInvalid()) return ExprError();
3829 Fn = result.take();
3830 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003831
Eli Friedmanefa42f72009-12-26 03:35:45 +00003832 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003833
John McCall3b4294e2009-12-16 12:17:52 +00003834 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003835 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3836 if (UnOp->getOpcode() == UO_AddrOf)
3837 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3838
John McCall3b4294e2009-12-16 12:17:52 +00003839 if (isa<DeclRefExpr>(NakedFn))
3840 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003841 else if (isa<MemberExpr>(NakedFn))
3842 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003843
Peter Collingbournee08ce652011-02-09 21:07:24 +00003844 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003845 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003846}
3847
3848ExprResult
3849Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003850 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003851 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3852 if (!ConfigDecl)
3853 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3854 << "cudaConfigureCall");
3855 QualType ConfigQTy = ConfigDecl->getType();
3856
3857 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003858 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003859 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003860
Peter Collingbourne1f240762011-10-02 23:49:29 +00003861 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3862 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003863}
3864
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003865/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3866///
3867/// __builtin_astype( value, dst type )
3868///
Richard Trieuccd891a2011-09-09 01:45:06 +00003869ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003870 SourceLocation BuiltinLoc,
3871 SourceLocation RParenLoc) {
3872 ExprValueKind VK = VK_RValue;
3873 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003874 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3875 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003876 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3877 return ExprError(Diag(BuiltinLoc,
3878 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003879 << DstTy
3880 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003881 << E->getSourceRange());
3882 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003883 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003884}
3885
John McCall3b4294e2009-12-16 12:17:52 +00003886/// BuildResolvedCallExpr - Build a call to a resolved expression,
3887/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003888/// unary-convert to an expression of function-pointer or
3889/// block-pointer type.
3890///
3891/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003892ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003893Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3894 SourceLocation LParenLoc,
3895 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003896 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003897 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003898 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3899
Chris Lattner04421082008-04-08 04:40:51 +00003900 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003901 ExprResult Result = UsualUnaryConversions(Fn);
3902 if (Result.isInvalid())
3903 return ExprError();
3904 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003905
Chris Lattner925e60d2007-12-28 05:29:59 +00003906 // Make the call expr early, before semantic checks. This guarantees cleanup
3907 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003908 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003909 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003910 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3911 cast<CallExpr>(Config),
3912 Args, NumArgs,
3913 Context.BoolTy,
3914 VK_RValue,
3915 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003916 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003917 TheCall = new (Context) CallExpr(Context, Fn,
3918 Args, NumArgs,
3919 Context.BoolTy,
3920 VK_RValue,
3921 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003922
John McCall8e10f3b2011-02-26 05:39:39 +00003923 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3924
3925 // Bail out early if calling a builtin with custom typechecking.
3926 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3927 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3928
John McCall1de4d4e2011-04-07 08:22:57 +00003929 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003930 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003931 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003932 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3933 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003934 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003935 if (FuncT == 0)
3936 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3937 << Fn->getType() << Fn->getSourceRange());
3938 } else if (const BlockPointerType *BPT =
3939 Fn->getType()->getAs<BlockPointerType>()) {
3940 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3941 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003942 // Handle calls to expressions of unknown-any type.
3943 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003944 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003945 if (rewrite.isInvalid()) return ExprError();
3946 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003947 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003948 goto retry;
3949 }
3950
Sebastian Redl0eb23302009-01-19 00:08:26 +00003951 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3952 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003953 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003954
David Blaikie4e4d0842012-03-11 07:00:24 +00003955 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003956 if (Config) {
3957 // CUDA: Kernel calls must be to global functions
3958 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3959 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3960 << FDecl->getName() << Fn->getSourceRange());
3961
3962 // CUDA: Kernel function must have 'void' return type
3963 if (!FuncT->getResultType()->isVoidType())
3964 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3965 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003966 } else {
3967 // CUDA: Calls to global functions must be configured
3968 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3969 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3970 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003971 }
3972 }
3973
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003974 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003975 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003976 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003977 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003978 return ExprError();
3979
Chris Lattner925e60d2007-12-28 05:29:59 +00003980 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003981 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003982 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003983
Richard Smith831421f2012-06-25 20:30:08 +00003984 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
3985 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00003986 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003987 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003988 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003989 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003990 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003991
Douglas Gregor74734d52009-04-02 15:37:10 +00003992 if (FDecl) {
3993 // Check if we have too few/too many template arguments, based
3994 // on our knowledge of the function definition.
3995 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003996 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00003997 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00003998 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003999 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4000 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004001 }
Douglas Gregor46542412010-10-25 20:39:23 +00004002
4003 // If the function we're calling isn't a function prototype, but we have
4004 // a function prototype from a prior declaratiom, use that prototype.
4005 if (!FDecl->hasPrototype())
4006 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004007 }
4008
Steve Naroffb291ab62007-08-28 23:30:39 +00004009 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004010 for (unsigned i = 0; i != NumArgs; i++) {
4011 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004012
4013 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004014 InitializedEntity Entity
4015 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004016 Proto->getArgType(i),
4017 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004018 ExprResult ArgE = PerformCopyInitialization(Entity,
4019 SourceLocation(),
4020 Owned(Arg));
4021 if (ArgE.isInvalid())
4022 return true;
4023
4024 Arg = ArgE.takeAs<Expr>();
4025
4026 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004027 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4028
4029 if (ArgE.isInvalid())
4030 return true;
4031
4032 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004033 }
4034
Daniel Dunbar96a00142012-03-09 18:35:03 +00004035 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004036 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004037 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004038 return ExprError();
4039
Chris Lattner925e60d2007-12-28 05:29:59 +00004040 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004041 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004042 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004043
Douglas Gregor88a35142008-12-22 05:46:06 +00004044 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4045 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004046 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4047 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004048
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004049 // Check for sentinels
4050 if (NDecl)
4051 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Chris Lattner59907c42007-08-10 20:18:51 +00004053 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004054 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004055 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004056 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004057
John McCall8e10f3b2011-02-26 05:39:39 +00004058 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004059 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004060 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004061 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004062 return ExprError();
4063 }
Chris Lattner59907c42007-08-10 20:18:51 +00004064
John McCall9ae2f072010-08-23 23:25:46 +00004065 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004066}
4067
John McCall60d7b3a2010-08-24 06:29:42 +00004068ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004069Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004070 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004071 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004072 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004073 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004074
4075 TypeSourceInfo *TInfo;
4076 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4077 if (!TInfo)
4078 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4079
John McCall9ae2f072010-08-23 23:25:46 +00004080 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004081}
4082
John McCall60d7b3a2010-08-24 06:29:42 +00004083ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004084Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004085 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004086 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004087
Eli Friedman6223c222008-05-20 05:22:08 +00004088 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004089 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004090 diag::err_illegal_decl_array_incomplete_type,
4091 SourceRange(LParenLoc,
4092 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004093 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004094 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004095 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004096 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004097 } else if (!literalType->isDependentType() &&
4098 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004099 diag::err_typecheck_decl_incomplete_type,
4100 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004101 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004102
Douglas Gregor99a2e602009-12-16 01:38:02 +00004103 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004104 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004105 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004106 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004107 SourceRange(LParenLoc, RParenLoc),
4108 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004109 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004110 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00004111 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004112 &literalType);
4113 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004114 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004115 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004116
Chris Lattner371f2582008-12-04 23:50:19 +00004117 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004118 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004119 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004120 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004121 }
Eli Friedman08544622009-12-22 02:35:53 +00004122
John McCallf89e55a2010-11-18 06:31:45 +00004123 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004124 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004125
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004126 return MaybeBindToTemporary(
4127 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004128 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004129}
4130
John McCall60d7b3a2010-08-24 06:29:42 +00004131ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004132Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004133 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004134 unsigned NumInit = InitArgList.size();
4135 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004136
John McCall3c3b7f92011-10-25 17:37:35 +00004137 // Immediately handle non-overload placeholders. Overloads can be
4138 // resolved contextually, but everything else here can't.
4139 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004140 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004141 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4142
4143 // Ignore failures; dropping the entire initializer list because
4144 // of one failure would be terrible for indexing/etc.
4145 if (result.isInvalid()) continue;
4146
4147 InitList[I] = result.take();
4148 }
4149 }
4150
Steve Naroff08d92e42007-09-15 18:49:24 +00004151 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004152 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004153
Ted Kremenek709210f2010-04-13 23:39:13 +00004154 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4155 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004156 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004157 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004158}
4159
John McCalldc05b112011-09-10 01:16:55 +00004160/// Do an explicit extend of the given block pointer if we're in ARC.
4161static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4162 assert(E.get()->getType()->isBlockPointerType());
4163 assert(E.get()->isRValue());
4164
4165 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004166 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004167
4168 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004169 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004170 /*base path*/ 0, VK_RValue);
4171 S.ExprNeedsCleanups = true;
4172}
4173
4174/// Prepare a conversion of the given expression to an ObjC object
4175/// pointer type.
4176CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4177 QualType type = E.get()->getType();
4178 if (type->isObjCObjectPointerType()) {
4179 return CK_BitCast;
4180 } else if (type->isBlockPointerType()) {
4181 maybeExtendBlockObject(*this, E);
4182 return CK_BlockPointerToObjCPointerCast;
4183 } else {
4184 assert(type->isPointerType());
4185 return CK_CPointerToObjCPointerCast;
4186 }
4187}
4188
John McCallf3ea8cf2010-11-14 08:17:51 +00004189/// Prepares for a scalar cast, performing all the necessary stages
4190/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004191CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004192 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4193 // Also, callers should have filtered out the invalid cases with
4194 // pointers. Everything else should be possible.
4195
John Wiegley429bb272011-04-08 18:41:53 +00004196 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004197 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004198 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004199
John McCall1d9b3b22011-09-09 05:25:32 +00004200 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004201 case Type::STK_MemberPointer:
4202 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004203
John McCall1d9b3b22011-09-09 05:25:32 +00004204 case Type::STK_CPointer:
4205 case Type::STK_BlockPointer:
4206 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004207 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004208 case Type::STK_CPointer:
4209 return CK_BitCast;
4210 case Type::STK_BlockPointer:
4211 return (SrcKind == Type::STK_BlockPointer
4212 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4213 case Type::STK_ObjCObjectPointer:
4214 if (SrcKind == Type::STK_ObjCObjectPointer)
4215 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004216 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004217 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004218 maybeExtendBlockObject(*this, Src);
4219 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004220 case Type::STK_Bool:
4221 return CK_PointerToBoolean;
4222 case Type::STK_Integral:
4223 return CK_PointerToIntegral;
4224 case Type::STK_Floating:
4225 case Type::STK_FloatingComplex:
4226 case Type::STK_IntegralComplex:
4227 case Type::STK_MemberPointer:
4228 llvm_unreachable("illegal cast from pointer");
4229 }
David Blaikie7530c032012-01-17 06:56:22 +00004230 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004231
John McCalldaa8e4e2010-11-15 09:13:47 +00004232 case Type::STK_Bool: // casting from bool is like casting from an integer
4233 case Type::STK_Integral:
4234 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004235 case Type::STK_CPointer:
4236 case Type::STK_ObjCObjectPointer:
4237 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004238 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004239 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004240 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004241 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004242 case Type::STK_Bool:
4243 return CK_IntegralToBoolean;
4244 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004245 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004246 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004247 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004248 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004249 Src = ImpCastExprToType(Src.take(),
4250 DestTy->castAs<ComplexType>()->getElementType(),
4251 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004252 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004253 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004254 Src = ImpCastExprToType(Src.take(),
4255 DestTy->castAs<ComplexType>()->getElementType(),
4256 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004257 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004258 case Type::STK_MemberPointer:
4259 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004260 }
David Blaikie7530c032012-01-17 06:56:22 +00004261 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004262
John McCalldaa8e4e2010-11-15 09:13:47 +00004263 case Type::STK_Floating:
4264 switch (DestTy->getScalarTypeKind()) {
4265 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004266 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004267 case Type::STK_Bool:
4268 return CK_FloatingToBoolean;
4269 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004270 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004271 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004272 Src = ImpCastExprToType(Src.take(),
4273 DestTy->castAs<ComplexType>()->getElementType(),
4274 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004275 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004276 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004277 Src = ImpCastExprToType(Src.take(),
4278 DestTy->castAs<ComplexType>()->getElementType(),
4279 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004280 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004281 case Type::STK_CPointer:
4282 case Type::STK_ObjCObjectPointer:
4283 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004284 llvm_unreachable("valid float->pointer cast?");
4285 case Type::STK_MemberPointer:
4286 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004287 }
David Blaikie7530c032012-01-17 06:56:22 +00004288 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004289
John McCalldaa8e4e2010-11-15 09:13:47 +00004290 case Type::STK_FloatingComplex:
4291 switch (DestTy->getScalarTypeKind()) {
4292 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004293 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004294 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004295 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004296 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004297 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4298 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004299 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004300 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004301 return CK_FloatingCast;
4302 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004303 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004304 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004305 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004306 Src = ImpCastExprToType(Src.take(),
4307 SrcTy->castAs<ComplexType>()->getElementType(),
4308 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004309 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004310 case Type::STK_CPointer:
4311 case Type::STK_ObjCObjectPointer:
4312 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004313 llvm_unreachable("valid complex float->pointer cast?");
4314 case Type::STK_MemberPointer:
4315 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004316 }
David Blaikie7530c032012-01-17 06:56:22 +00004317 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004318
John McCalldaa8e4e2010-11-15 09:13:47 +00004319 case Type::STK_IntegralComplex:
4320 switch (DestTy->getScalarTypeKind()) {
4321 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004322 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004323 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004324 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004325 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004326 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4327 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004328 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004329 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004330 return CK_IntegralCast;
4331 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004332 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004333 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004334 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004335 Src = ImpCastExprToType(Src.take(),
4336 SrcTy->castAs<ComplexType>()->getElementType(),
4337 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004338 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004339 case Type::STK_CPointer:
4340 case Type::STK_ObjCObjectPointer:
4341 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004342 llvm_unreachable("valid complex int->pointer cast?");
4343 case Type::STK_MemberPointer:
4344 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004345 }
David Blaikie7530c032012-01-17 06:56:22 +00004346 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004347 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004348
John McCallf3ea8cf2010-11-14 08:17:51 +00004349 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004350}
4351
Anders Carlssonc3516322009-10-16 02:48:28 +00004352bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004353 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004354 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004355
Anders Carlssona64db8f2007-11-27 05:51:55 +00004356 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004357 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004358 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004359 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004360 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004361 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004362 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004363 } else
4364 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004365 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004366 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004367
John McCall2de56d12010-08-25 11:45:40 +00004368 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004369 return false;
4370}
4371
John Wiegley429bb272011-04-08 18:41:53 +00004372ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4373 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004374 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004375
Anders Carlsson16a89042009-10-16 05:23:41 +00004376 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004377
Nate Begeman9b10da62009-06-27 22:05:55 +00004378 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4379 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004380 // In OpenCL, casts between vectors of different types are not allowed.
4381 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004382 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004383 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004384 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004385 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004386 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004387 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004388 return ExprError();
4389 }
John McCall2de56d12010-08-25 11:45:40 +00004390 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004391 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004392 }
4393
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004394 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004395 // conversion will take place first from scalar to elt type, and then
4396 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004397 if (SrcTy->isPointerType())
4398 return Diag(R.getBegin(),
4399 diag::err_invalid_conversion_between_vector_and_scalar)
4400 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004401
4402 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004403 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004404 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004405 if (CastExprRes.isInvalid())
4406 return ExprError();
4407 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004408
John McCall2de56d12010-08-25 11:45:40 +00004409 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004410 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004411}
4412
John McCall60d7b3a2010-08-24 06:29:42 +00004413ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004414Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4415 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004416 SourceLocation RParenLoc, Expr *CastExpr) {
4417 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004418 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004419
Richard Trieuccd891a2011-09-09 01:45:06 +00004420 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004421 if (D.isInvalidType())
4422 return ExprError();
4423
David Blaikie4e4d0842012-03-11 07:00:24 +00004424 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004425 // Check that there are no default arguments (C++ only).
4426 CheckExtraCXXDefaultArguments(D);
4427 }
4428
John McCalle82247a2011-10-01 05:17:03 +00004429 checkUnusedDeclAttributes(D);
4430
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004431 QualType castType = castTInfo->getType();
4432 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004434 bool isVectorLiteral = false;
4435
4436 // Check for an altivec or OpenCL literal,
4437 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004438 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4439 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004440 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004441 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004442 if (PLE && PLE->getNumExprs() == 0) {
4443 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4444 return ExprError();
4445 }
4446 if (PE || PLE->getNumExprs() == 1) {
4447 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4448 if (!E->getType()->isVectorType())
4449 isVectorLiteral = true;
4450 }
4451 else
4452 isVectorLiteral = true;
4453 }
4454
4455 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4456 // then handle it as such.
4457 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004458 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004459
Nate Begeman2ef13e52009-08-10 23:49:36 +00004460 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004461 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4462 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004463 if (isa<ParenListExpr>(CastExpr)) {
4464 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004465 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004466 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004467 }
John McCallb042fdf2010-01-15 18:56:44 +00004468
Richard Trieuccd891a2011-09-09 01:45:06 +00004469 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004470}
4471
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004472ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4473 SourceLocation RParenLoc, Expr *E,
4474 TypeSourceInfo *TInfo) {
4475 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4476 "Expected paren or paren list expression");
4477
4478 Expr **exprs;
4479 unsigned numExprs;
4480 Expr *subExpr;
4481 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4482 exprs = PE->getExprs();
4483 numExprs = PE->getNumExprs();
4484 } else {
4485 subExpr = cast<ParenExpr>(E)->getSubExpr();
4486 exprs = &subExpr;
4487 numExprs = 1;
4488 }
4489
4490 QualType Ty = TInfo->getType();
4491 assert(Ty->isVectorType() && "Expected vector type");
4492
Chris Lattner5f9e2722011-07-23 10:55:15 +00004493 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004494 const VectorType *VTy = Ty->getAs<VectorType>();
4495 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4496
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004497 // '(...)' form of vector initialization in AltiVec: the number of
4498 // initializers must be one or must match the size of the vector.
4499 // If a single value is specified in the initializer then it will be
4500 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004501 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004502 // The number of initializers must be one or must match the size of the
4503 // vector. If a single value is specified in the initializer then it will
4504 // be replicated to all the components of the vector
4505 if (numExprs == 1) {
4506 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004507 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4508 if (Literal.isInvalid())
4509 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004510 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004511 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004512 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4513 }
4514 else if (numExprs < numElems) {
4515 Diag(E->getExprLoc(),
4516 diag::err_incorrect_number_of_vector_initializers);
4517 return ExprError();
4518 }
4519 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004520 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004521 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004522 else {
4523 // For OpenCL, when the number of initializers is a single value,
4524 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004525 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004526 VTy->getVectorKind() == VectorType::GenericVector &&
4527 numExprs == 1) {
4528 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004529 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4530 if (Literal.isInvalid())
4531 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004532 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004533 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004534 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4535 }
4536
Benjamin Kramer14c59822012-02-14 12:06:21 +00004537 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004538 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004539 // FIXME: This means that pretty-printing the final AST will produce curly
4540 // braces instead of the original commas.
4541 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4542 &initExprs[0],
4543 initExprs.size(), RParenLoc);
4544 initE->setType(Ty);
4545 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4546}
4547
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004548/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4549/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004550ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004551Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4552 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004553 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004554 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004555
John McCall60d7b3a2010-08-24 06:29:42 +00004556 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004557
Nate Begeman2ef13e52009-08-10 23:49:36 +00004558 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004559 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4560 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004561
John McCall9ae2f072010-08-23 23:25:46 +00004562 if (Result.isInvalid()) return ExprError();
4563
4564 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004565}
4566
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004567ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4568 SourceLocation R,
4569 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004570 unsigned nexprs = Val.size();
4571 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004572 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004573 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004574 return Owned(expr);
4575}
4576
Chandler Carruth82214a82011-02-18 23:54:50 +00004577/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004578/// constant and the other is not a pointer. Returns true if a diagnostic is
4579/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004580bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004581 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004582 Expr *NullExpr = LHSExpr;
4583 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004584 Expr::NullPointerConstantKind NullKind =
4585 NullExpr->isNullPointerConstant(Context,
4586 Expr::NPC_ValueDependentIsNotNull);
4587
4588 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004589 NullExpr = RHSExpr;
4590 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004591 NullKind =
4592 NullExpr->isNullPointerConstant(Context,
4593 Expr::NPC_ValueDependentIsNotNull);
4594 }
4595
4596 if (NullKind == Expr::NPCK_NotNull)
4597 return false;
4598
4599 if (NullKind == Expr::NPCK_ZeroInteger) {
4600 // In this case, check to make sure that we got here from a "NULL"
4601 // string in the source code.
4602 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004603 SourceLocation loc = NullExpr->getExprLoc();
4604 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004605 return false;
4606 }
4607
4608 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4609 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4610 << NonPointerExpr->getType() << DiagType
4611 << NonPointerExpr->getSourceRange();
4612 return true;
4613}
4614
Richard Trieu26f96072011-09-02 01:51:02 +00004615/// \brief Return false if the condition expression is valid, true otherwise.
4616static bool checkCondition(Sema &S, Expr *Cond) {
4617 QualType CondTy = Cond->getType();
4618
4619 // C99 6.5.15p2
4620 if (CondTy->isScalarType()) return false;
4621
4622 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004623 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004624 return false;
4625
4626 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004627 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004628 diag::err_typecheck_cond_expect_scalar :
4629 diag::err_typecheck_cond_expect_scalar_or_vector)
4630 << CondTy;
4631 return true;
4632}
4633
4634/// \brief Return false if the two expressions can be converted to a vector,
4635/// true otherwise
4636static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4637 ExprResult &RHS,
4638 QualType CondTy) {
4639 // Both operands should be of scalar type.
4640 if (!LHS.get()->getType()->isScalarType()) {
4641 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4642 << CondTy;
4643 return true;
4644 }
4645 if (!RHS.get()->getType()->isScalarType()) {
4646 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4647 << CondTy;
4648 return true;
4649 }
4650
4651 // Implicity convert these scalars to the type of the condition.
4652 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4653 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4654 return false;
4655}
4656
4657/// \brief Handle when one or both operands are void type.
4658static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4659 ExprResult &RHS) {
4660 Expr *LHSExpr = LHS.get();
4661 Expr *RHSExpr = RHS.get();
4662
4663 if (!LHSExpr->getType()->isVoidType())
4664 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4665 << RHSExpr->getSourceRange();
4666 if (!RHSExpr->getType()->isVoidType())
4667 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4668 << LHSExpr->getSourceRange();
4669 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4670 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4671 return S.Context.VoidTy;
4672}
4673
4674/// \brief Return false if the NullExpr can be promoted to PointerTy,
4675/// true otherwise.
4676static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4677 QualType PointerTy) {
4678 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4679 !NullExpr.get()->isNullPointerConstant(S.Context,
4680 Expr::NPC_ValueDependentIsNull))
4681 return true;
4682
4683 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4684 return false;
4685}
4686
4687/// \brief Checks compatibility between two pointers and return the resulting
4688/// type.
4689static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4690 ExprResult &RHS,
4691 SourceLocation Loc) {
4692 QualType LHSTy = LHS.get()->getType();
4693 QualType RHSTy = RHS.get()->getType();
4694
4695 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4696 // Two identical pointers types are always compatible.
4697 return LHSTy;
4698 }
4699
4700 QualType lhptee, rhptee;
4701
4702 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004703 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4704 lhptee = LHSBTy->getPointeeType();
4705 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004706 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004707 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4708 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004709 }
4710
Eli Friedmanae916a12012-04-05 22:30:04 +00004711 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4712 // differently qualified versions of compatible types, the result type is
4713 // a pointer to an appropriately qualified version of the composite
4714 // type.
4715
4716 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4717 // clause doesn't make sense for our extensions. E.g. address space 2 should
4718 // be incompatible with address space 3: they may live on different devices or
4719 // anything.
4720 Qualifiers lhQual = lhptee.getQualifiers();
4721 Qualifiers rhQual = rhptee.getQualifiers();
4722
4723 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4724 lhQual.removeCVRQualifiers();
4725 rhQual.removeCVRQualifiers();
4726
4727 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4728 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4729
4730 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4731
4732 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004733 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4734 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4735 << RHS.get()->getSourceRange();
4736 // In this situation, we assume void* type. No especially good
4737 // reason, but this is what gcc does, and we do have to pick
4738 // to get a consistent AST.
4739 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4740 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4741 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4742 return incompatTy;
4743 }
4744
4745 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004746 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4747 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004748
Eli Friedmanae916a12012-04-05 22:30:04 +00004749 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4750 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4751 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004752}
4753
4754/// \brief Return the resulting type when the operands are both block pointers.
4755static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4756 ExprResult &LHS,
4757 ExprResult &RHS,
4758 SourceLocation Loc) {
4759 QualType LHSTy = LHS.get()->getType();
4760 QualType RHSTy = RHS.get()->getType();
4761
4762 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4763 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4764 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4765 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4766 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4767 return destType;
4768 }
4769 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4770 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4771 << RHS.get()->getSourceRange();
4772 return QualType();
4773 }
4774
4775 // We have 2 block pointer types.
4776 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4777}
4778
4779/// \brief Return the resulting type when the operands are both pointers.
4780static QualType
4781checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4782 ExprResult &RHS,
4783 SourceLocation Loc) {
4784 // get the pointer types
4785 QualType LHSTy = LHS.get()->getType();
4786 QualType RHSTy = RHS.get()->getType();
4787
4788 // get the "pointed to" types
4789 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4790 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4791
4792 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4793 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4794 // Figure out necessary qualifiers (C99 6.5.15p6)
4795 QualType destPointee
4796 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4797 QualType destType = S.Context.getPointerType(destPointee);
4798 // Add qualifiers if necessary.
4799 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4800 // Promote to void*.
4801 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4802 return destType;
4803 }
4804 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4805 QualType destPointee
4806 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4807 QualType destType = S.Context.getPointerType(destPointee);
4808 // Add qualifiers if necessary.
4809 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4810 // Promote to void*.
4811 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4812 return destType;
4813 }
4814
4815 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4816}
4817
4818/// \brief Return false if the first expression is not an integer and the second
4819/// expression is not a pointer, true otherwise.
4820static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4821 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004822 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004823 if (!PointerExpr->getType()->isPointerType() ||
4824 !Int.get()->getType()->isIntegerType())
4825 return false;
4826
Richard Trieuccd891a2011-09-09 01:45:06 +00004827 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4828 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004829
4830 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4831 << Expr1->getType() << Expr2->getType()
4832 << Expr1->getSourceRange() << Expr2->getSourceRange();
4833 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4834 CK_IntegralToPointer);
4835 return true;
4836}
4837
Richard Trieu33fc7572011-09-06 20:06:39 +00004838/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4839/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004840/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004841QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4842 ExprResult &RHS, ExprValueKind &VK,
4843 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004844 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004845
Richard Trieu33fc7572011-09-06 20:06:39 +00004846 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4847 if (!LHSResult.isUsable()) return QualType();
4848 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004849
Richard Trieu33fc7572011-09-06 20:06:39 +00004850 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4851 if (!RHSResult.isUsable()) return QualType();
4852 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004853
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004854 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004855 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004856 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004857
4858 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004859 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004860
John Wiegley429bb272011-04-08 18:41:53 +00004861 Cond = UsualUnaryConversions(Cond.take());
4862 if (Cond.isInvalid())
4863 return QualType();
4864 LHS = UsualUnaryConversions(LHS.take());
4865 if (LHS.isInvalid())
4866 return QualType();
4867 RHS = UsualUnaryConversions(RHS.take());
4868 if (RHS.isInvalid())
4869 return QualType();
4870
4871 QualType CondTy = Cond.get()->getType();
4872 QualType LHSTy = LHS.get()->getType();
4873 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004874
Reid Spencer5f016e22007-07-11 17:01:13 +00004875 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004876 if (checkCondition(*this, Cond.get()))
4877 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004878
Chris Lattner70d67a92008-01-06 22:42:25 +00004879 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004880 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004881 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004882
Nate Begeman6155d732010-09-20 22:41:17 +00004883 // OpenCL: If the condition is a vector, and both operands are scalar,
4884 // attempt to implicity convert them to the vector type to act like the
4885 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004886 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004887 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004888 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004889
Chris Lattner70d67a92008-01-06 22:42:25 +00004890 // If both operands have arithmetic type, do the usual arithmetic conversions
4891 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004892 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4893 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004894 if (LHS.isInvalid() || RHS.isInvalid())
4895 return QualType();
4896 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004897 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004898
Chris Lattner70d67a92008-01-06 22:42:25 +00004899 // If both operands are the same structure or union type, the result is that
4900 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004901 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4902 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004903 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004904 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004905 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004906 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004907 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004908 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004909
Chris Lattner70d67a92008-01-06 22:42:25 +00004910 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004911 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004912 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004913 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004914 }
Richard Trieu26f96072011-09-02 01:51:02 +00004915
Steve Naroffb6d54e52008-01-08 01:11:38 +00004916 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4917 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004918 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4919 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004920
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004921 // All objective-c pointer type analysis is done here.
4922 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4923 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004924 if (LHS.isInvalid() || RHS.isInvalid())
4925 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004926 if (!compositeType.isNull())
4927 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004928
4929
Steve Naroff7154a772009-07-01 14:36:47 +00004930 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004931 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4932 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4933 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004934
Steve Naroff7154a772009-07-01 14:36:47 +00004935 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004936 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4937 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4938 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004939
John McCall404cd162010-11-13 01:35:44 +00004940 // GCC compatibility: soften pointer/integer mismatch. Note that
4941 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004942 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4943 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004944 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004945 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4946 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004947 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004948
Chandler Carruth82214a82011-02-18 23:54:50 +00004949 // Emit a better diagnostic if one of the expressions is a null pointer
4950 // constant and the other is not a pointer type. In this case, the user most
4951 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004952 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004953 return QualType();
4954
Chris Lattner70d67a92008-01-06 22:42:25 +00004955 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004956 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004957 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4958 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004959 return QualType();
4960}
4961
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004962/// FindCompositeObjCPointerType - Helper method to find composite type of
4963/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004964QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004965 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004966 QualType LHSTy = LHS.get()->getType();
4967 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004968
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004969 // Handle things like Class and struct objc_class*. Here we case the result
4970 // to the pseudo-builtin, because that will be implicitly cast back to the
4971 // redefinition type if an attempt is made to access its fields.
4972 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004973 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004974 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004975 return LHSTy;
4976 }
4977 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004978 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004979 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004980 return RHSTy;
4981 }
4982 // And the same for struct objc_object* / id
4983 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004984 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004985 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004986 return LHSTy;
4987 }
4988 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004989 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004990 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004991 return RHSTy;
4992 }
4993 // And the same for struct objc_selector* / SEL
4994 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004995 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004996 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004997 return LHSTy;
4998 }
4999 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005000 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005001 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005002 return RHSTy;
5003 }
5004 // Check constraints for Objective-C object pointers types.
5005 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005006
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005007 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5008 // Two identical object pointer types are always compatible.
5009 return LHSTy;
5010 }
John McCall1d9b3b22011-09-09 05:25:32 +00005011 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5012 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005013 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005014
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005015 // If both operands are interfaces and either operand can be
5016 // assigned to the other, use that type as the composite
5017 // type. This allows
5018 // xxx ? (A*) a : (B*) b
5019 // where B is a subclass of A.
5020 //
5021 // Additionally, as for assignment, if either type is 'id'
5022 // allow silent coercion. Finally, if the types are
5023 // incompatible then make sure to use 'id' as the composite
5024 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005025
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005026 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5027 // It could return the composite type.
5028 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5029 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5030 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5031 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5032 } else if ((LHSTy->isObjCQualifiedIdType() ||
5033 RHSTy->isObjCQualifiedIdType()) &&
5034 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5035 // Need to handle "id<xx>" explicitly.
5036 // GCC allows qualified id and any Objective-C type to devolve to
5037 // id. Currently localizing to here until clear this should be
5038 // part of ObjCQualifiedIdTypesAreCompatible.
5039 compositeType = Context.getObjCIdType();
5040 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5041 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005042 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005043 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5044 ;
5045 else {
5046 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5047 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005048 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005049 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005050 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5051 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005052 return incompatTy;
5053 }
5054 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005055 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5056 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005057 return compositeType;
5058 }
5059 // Check Objective-C object pointer types and 'void *'
5060 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005061 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005062 // ARC forbids the implicit conversion of object pointers to 'void *',
5063 // so these types are not compatible.
5064 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5065 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5066 LHS = RHS = true;
5067 return QualType();
5068 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005069 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5070 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5071 QualType destPointee
5072 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5073 QualType destType = Context.getPointerType(destPointee);
5074 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005075 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005076 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005077 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005078 return destType;
5079 }
5080 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005081 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005082 // ARC forbids the implicit conversion of object pointers to 'void *',
5083 // so these types are not compatible.
5084 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5086 LHS = RHS = true;
5087 return QualType();
5088 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005089 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5090 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5091 QualType destPointee
5092 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5093 QualType destType = Context.getPointerType(destPointee);
5094 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005095 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005096 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005097 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005098 return destType;
5099 }
5100 return QualType();
5101}
5102
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005103/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005104/// ParenRange in parentheses.
5105static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005106 const PartialDiagnostic &Note,
5107 SourceRange ParenRange) {
5108 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5109 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5110 EndLoc.isValid()) {
5111 Self.Diag(Loc, Note)
5112 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5113 << FixItHint::CreateInsertion(EndLoc, ")");
5114 } else {
5115 // We can't display the parentheses, so just show the bare note.
5116 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005117 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005118}
5119
5120static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5121 return Opc >= BO_Mul && Opc <= BO_Shr;
5122}
5123
Hans Wennborg2f072b42011-06-09 17:06:51 +00005124/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5125/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005126/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5127/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005128static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005129 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005130 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5131 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005132 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005133 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005134
5135 // Built-in binary operator.
5136 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5137 if (IsArithmeticOp(OP->getOpcode())) {
5138 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005139 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005140 return true;
5141 }
5142 }
5143
5144 // Overloaded operator.
5145 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5146 if (Call->getNumArgs() != 2)
5147 return false;
5148
5149 // Make sure this is really a binary operator that is safe to pass into
5150 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5151 OverloadedOperatorKind OO = Call->getOperator();
5152 if (OO < OO_Plus || OO > OO_Arrow)
5153 return false;
5154
5155 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5156 if (IsArithmeticOp(OpKind)) {
5157 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005158 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005159 return true;
5160 }
5161 }
5162
5163 return false;
5164}
5165
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005166static bool IsLogicOp(BinaryOperatorKind Opc) {
5167 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5168}
5169
Hans Wennborg2f072b42011-06-09 17:06:51 +00005170/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5171/// or is a logical expression such as (x==y) which has int type, but is
5172/// commonly interpreted as boolean.
5173static bool ExprLooksBoolean(Expr *E) {
5174 E = E->IgnoreParenImpCasts();
5175
5176 if (E->getType()->isBooleanType())
5177 return true;
5178 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5179 return IsLogicOp(OP->getOpcode());
5180 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5181 return OP->getOpcode() == UO_LNot;
5182
5183 return false;
5184}
5185
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005186/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5187/// and binary operator are mixed in a way that suggests the programmer assumed
5188/// the conditional operator has higher precedence, for example:
5189/// "int x = a + someBinaryCondition ? 1 : 2".
5190static void DiagnoseConditionalPrecedence(Sema &Self,
5191 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005192 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005193 Expr *LHSExpr,
5194 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005195 BinaryOperatorKind CondOpcode;
5196 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005197
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005198 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005199 return;
5200 if (!ExprLooksBoolean(CondRHS))
5201 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005202
Hans Wennborg2f072b42011-06-09 17:06:51 +00005203 // The condition is an arithmetic binary expression, with a right-
5204 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005205
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005206 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005207 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005208 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005209
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005210 SuggestParentheses(Self, OpLoc,
5211 Self.PDiag(diag::note_precedence_conditional_silence)
5212 << BinaryOperator::getOpcodeStr(CondOpcode),
5213 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005214
5215 SuggestParentheses(Self, OpLoc,
5216 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005217 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005218}
5219
Steve Narofff69936d2007-09-16 03:34:24 +00005220/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005221/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005222ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005223 SourceLocation ColonLoc,
5224 Expr *CondExpr, Expr *LHSExpr,
5225 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005226 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5227 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005228 OpaqueValueExpr *opaqueValue = 0;
5229 Expr *commonExpr = 0;
5230 if (LHSExpr == 0) {
5231 commonExpr = CondExpr;
5232
5233 // We usually want to apply unary conversions *before* saving, except
5234 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005235 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005236 && !commonExpr->isTypeDependent()
5237 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5238 && commonExpr->isGLValue()
5239 && commonExpr->isOrdinaryOrBitFieldObject()
5240 && RHSExpr->isOrdinaryOrBitFieldObject()
5241 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005242 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5243 if (commonRes.isInvalid())
5244 return ExprError();
5245 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005246 }
5247
5248 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5249 commonExpr->getType(),
5250 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005251 commonExpr->getObjectKind(),
5252 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005253 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005254 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005255
John McCallf89e55a2010-11-18 06:31:45 +00005256 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005257 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005258 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5259 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005260 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005261 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5262 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005263 return ExprError();
5264
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005265 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5266 RHS.get());
5267
John McCall56ca35d2011-02-17 10:25:35 +00005268 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005269 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5270 LHS.take(), ColonLoc,
5271 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005272
5273 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005274 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005275 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5276 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005277}
5278
John McCalle4be87e2011-01-31 23:13:11 +00005279// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005280// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005281// routine is it effectively iqnores the qualifiers on the top level pointee.
5282// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5283// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005284static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005285checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5286 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5287 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005288
Reid Spencer5f016e22007-07-11 17:01:13 +00005289 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005290 const Type *lhptee, *rhptee;
5291 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005292 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5293 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005294
John McCalle4be87e2011-01-31 23:13:11 +00005295 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005296
5297 // C99 6.5.16.1p1: This following citation is common to constraints
5298 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5299 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005300 Qualifiers lq;
5301
John McCallf85e1932011-06-15 23:02:42 +00005302 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5303 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5304 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5305 // Ignore lifetime for further calculation.
5306 lhq.removeObjCLifetime();
5307 rhq.removeObjCLifetime();
5308 }
5309
John McCall86c05f32011-02-01 00:10:29 +00005310 if (!lhq.compatiblyIncludes(rhq)) {
5311 // Treat address-space mismatches as fatal. TODO: address subspaces
5312 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5313 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5314
John McCallf85e1932011-06-15 23:02:42 +00005315 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005316 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005317 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005318 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005319 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005320 && (lhptee->isVoidType() || rhptee->isVoidType()))
5321 ; // keep old
5322
John McCallf85e1932011-06-15 23:02:42 +00005323 // Treat lifetime mismatches as fatal.
5324 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5325 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5326
John McCall86c05f32011-02-01 00:10:29 +00005327 // For GCC compatibility, other qualifier mismatches are treated
5328 // as still compatible in C.
5329 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5330 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005331
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5333 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005334 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005335 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005336 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005337 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005338
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005339 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005340 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005341 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005342 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005343
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005344 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005345 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005346 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005347
5348 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005349 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005350 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005351 }
John McCall86c05f32011-02-01 00:10:29 +00005352
Mike Stumpeed9cac2009-02-19 03:04:26 +00005353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005354 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005355 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5356 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005357 // Check if the pointee types are compatible ignoring the sign.
5358 // We explicitly check for char so that we catch "char" vs
5359 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005360 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005361 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005362 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005363 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005364
Chris Lattner6a2b9262009-10-17 20:33:28 +00005365 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005366 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005367 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005368 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005369
John McCall86c05f32011-02-01 00:10:29 +00005370 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005371 // Types are compatible ignoring the sign. Qualifier incompatibility
5372 // takes priority over sign incompatibility because the sign
5373 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005374 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005375 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005376
John McCalle4be87e2011-01-31 23:13:11 +00005377 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005378 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005379
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005380 // If we are a multi-level pointer, it's possible that our issue is simply
5381 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5382 // the eventual target type is the same and the pointers have the same
5383 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005384 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005385 do {
John McCall86c05f32011-02-01 00:10:29 +00005386 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5387 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005388 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005389
John McCall86c05f32011-02-01 00:10:29 +00005390 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005391 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005392 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005393
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005394 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005395 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005396 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005397 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005398 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5399 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005400 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005401}
5402
John McCalle4be87e2011-01-31 23:13:11 +00005403/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005404/// block pointer types are compatible or whether a block and normal pointer
5405/// are compatible. It is more restrict than comparing two function pointer
5406// types.
John McCalle4be87e2011-01-31 23:13:11 +00005407static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005408checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5409 QualType RHSType) {
5410 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5411 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005412
Steve Naroff1c7d0672008-09-04 15:10:53 +00005413 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005414
Steve Naroff1c7d0672008-09-04 15:10:53 +00005415 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005416 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5417 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005418
John McCalle4be87e2011-01-31 23:13:11 +00005419 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005420 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005421 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005422
John McCalle4be87e2011-01-31 23:13:11 +00005423 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005424
Steve Naroff1c7d0672008-09-04 15:10:53 +00005425 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005426 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5427 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005428
Richard Trieu1da27a12011-09-06 20:21:22 +00005429 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005430 return Sema::IncompatibleBlockPointer;
5431
Steve Naroff1c7d0672008-09-04 15:10:53 +00005432 return ConvTy;
5433}
5434
John McCalle4be87e2011-01-31 23:13:11 +00005435/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005436/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005437static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005438checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5439 QualType RHSType) {
5440 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5441 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005442
Richard Trieu1da27a12011-09-06 20:21:22 +00005443 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005444 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005445 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5446 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005447 return Sema::IncompatiblePointer;
5448 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005449 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005450 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005451 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5452 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005453 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005454 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005455 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005456 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5457 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005458
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005459 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5460 // make an exception for id<P>
5461 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005462 return Sema::CompatiblePointerDiscardsQualifiers;
5463
Richard Trieu1da27a12011-09-06 20:21:22 +00005464 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005465 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005466 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005467 return Sema::IncompatibleObjCQualifiedId;
5468 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005469}
5470
John McCall1c23e912010-11-16 02:32:08 +00005471Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005472Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005473 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005474 // Fake up an opaque expression. We don't actually care about what
5475 // cast operations are required, so if CheckAssignmentConstraints
5476 // adds casts to this they'll be wasted, but fortunately that doesn't
5477 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005478 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5479 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005480 CastKind K = CK_Invalid;
5481
Richard Trieu1da27a12011-09-06 20:21:22 +00005482 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005483}
5484
Mike Stumpeed9cac2009-02-19 03:04:26 +00005485/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5486/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005487/// pointers. Here are some objectionable examples that GCC considers warnings:
5488///
5489/// int a, *pint;
5490/// short *pshort;
5491/// struct foo *pfoo;
5492///
5493/// pint = pshort; // warning: assignment from incompatible pointer type
5494/// a = pint; // warning: assignment makes integer from pointer without a cast
5495/// pint = a; // warning: assignment makes pointer from integer without a cast
5496/// pint = pfoo; // warning: assignment from incompatible pointer type
5497///
5498/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005499/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005500///
John McCalldaa8e4e2010-11-15 09:13:47 +00005501/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005502Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005503Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005504 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005505 QualType RHSType = RHS.get()->getType();
5506 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005507
Chris Lattnerfc144e22008-01-04 23:18:45 +00005508 // Get canonical types. We're not formatting these types, just comparing
5509 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005510 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5511 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005512
Eli Friedmanb001de72011-10-06 23:00:33 +00005513
John McCallb6cfa242011-01-31 22:28:28 +00005514 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005515 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005516 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005517 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005518 }
5519
Eli Friedman860a3192012-06-16 02:19:17 +00005520 // If we have an atomic type, try a non-atomic assignment, then just add an
5521 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005522 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005523 Sema::AssignConvertType result =
5524 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5525 if (result != Compatible)
5526 return result;
5527 if (Kind != CK_NoOp)
5528 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5529 Kind = CK_NonAtomicToAtomic;
5530 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005531 }
5532
Douglas Gregor9d293df2008-10-28 00:22:11 +00005533 // If the left-hand side is a reference type, then we are in a
5534 // (rare!) case where we've allowed the use of references in C,
5535 // e.g., as a parameter type in a built-in function. In this case,
5536 // just make sure that the type referenced is compatible with the
5537 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005538 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005539 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005540 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5541 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005542 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005543 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005544 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005545 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005546 }
John McCallb6cfa242011-01-31 22:28:28 +00005547
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005548 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5549 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005550 if (LHSType->isExtVectorType()) {
5551 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005552 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005553 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005554 // CK_VectorSplat does T -> vector T, so first cast to the
5555 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005556 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5557 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005558 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005559 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005560 }
5561 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005562 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005563 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005564 }
Mike Stump1eb44332009-09-09 15:08:12 +00005565
John McCallb6cfa242011-01-31 22:28:28 +00005566 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005567 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5568 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005569 // Allow assignments of an AltiVec vector type to an equivalent GCC
5570 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005571 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005572 Kind = CK_BitCast;
5573 return Compatible;
5574 }
5575
Douglas Gregor255210e2010-08-06 10:14:59 +00005576 // If we are allowing lax vector conversions, and LHS and RHS are both
5577 // vectors, the total size only needs to be the same. This is a bitcast;
5578 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005579 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005580 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005581 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005582 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005583 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005584 }
5585 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005586 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005587
John McCallb6cfa242011-01-31 22:28:28 +00005588 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005589 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005590 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005591 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005592 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005593 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005594
John McCallb6cfa242011-01-31 22:28:28 +00005595 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005596 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005597 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005598 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005599 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005600 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005601 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005602
John McCallb6cfa242011-01-31 22:28:28 +00005603 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005604 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005605 Kind = CK_IntegralToPointer; // FIXME: null?
5606 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005607 }
John McCallb6cfa242011-01-31 22:28:28 +00005608
5609 // C pointers are not compatible with ObjC object pointers,
5610 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005611 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005612 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005613 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005614 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005615 return Compatible;
5616 }
5617
5618 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005619 if (RHSType->isObjCClassType() &&
5620 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005621 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005622 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005623 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005624 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005625
John McCallb6cfa242011-01-31 22:28:28 +00005626 Kind = CK_BitCast;
5627 return IncompatiblePointer;
5628 }
5629
5630 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005631 if (RHSType->getAs<BlockPointerType>()) {
5632 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005633 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005634 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005635 }
Steve Naroffb4406862008-09-29 18:10:17 +00005636 }
John McCallb6cfa242011-01-31 22:28:28 +00005637
Steve Naroff1c7d0672008-09-04 15:10:53 +00005638 return Incompatible;
5639 }
5640
John McCallb6cfa242011-01-31 22:28:28 +00005641 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005642 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005643 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005644 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005645 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005646 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005647 }
5648
5649 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005650 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005651 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005652 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005653 }
5654
John McCallb6cfa242011-01-31 22:28:28 +00005655 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005656 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005657 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005658 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005659 }
Steve Naroffb4406862008-09-29 18:10:17 +00005660
John McCallb6cfa242011-01-31 22:28:28 +00005661 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005662 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005663 if (RHSPT->getPointeeType()->isVoidType()) {
5664 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005665 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005666 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005667
Chris Lattnerfc144e22008-01-04 23:18:45 +00005668 return Incompatible;
5669 }
5670
John McCallb6cfa242011-01-31 22:28:28 +00005671 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005672 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005673 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005674 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005675 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005676 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005677 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005678 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005679 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005680 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005681 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005682 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005683 }
5684
5685 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005686 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005687 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005688 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005689 }
5690
John McCallb6cfa242011-01-31 22:28:28 +00005691 // In general, C pointers are not compatible with ObjC object pointers,
5692 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005693 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005694 Kind = CK_CPointerToObjCPointerCast;
5695
John McCallb6cfa242011-01-31 22:28:28 +00005696 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005697 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005698 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005699 }
5700
5701 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005702 if (LHSType->isObjCClassType() &&
5703 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005704 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005705 return Compatible;
5706 }
5707
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005708 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005709 }
John McCallb6cfa242011-01-31 22:28:28 +00005710
5711 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005712 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005713 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005714 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005715 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005716 }
5717
Steve Naroff14108da2009-07-10 23:34:53 +00005718 return Incompatible;
5719 }
John McCallb6cfa242011-01-31 22:28:28 +00005720
5721 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005722 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005723 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005724 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005725 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005726 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005727 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005728
John McCallb6cfa242011-01-31 22:28:28 +00005729 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005730 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005731 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005732 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005733 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005734
Chris Lattnerfc144e22008-01-04 23:18:45 +00005735 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005736 }
John McCallb6cfa242011-01-31 22:28:28 +00005737
5738 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005739 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005740 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005741 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005742 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005743 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005744 }
Steve Naroff14108da2009-07-10 23:34:53 +00005745
John McCallb6cfa242011-01-31 22:28:28 +00005746 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005747 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005748 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005749 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005750 }
5751
Steve Naroff14108da2009-07-10 23:34:53 +00005752 return Incompatible;
5753 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005754
John McCallb6cfa242011-01-31 22:28:28 +00005755 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005756 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5757 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005758 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005759 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005760 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005761 }
John McCallb6cfa242011-01-31 22:28:28 +00005762
Reid Spencer5f016e22007-07-11 17:01:13 +00005763 return Incompatible;
5764}
5765
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005766/// \brief Constructs a transparent union from an expression that is
5767/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005768static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5769 ExprResult &EResult, QualType UnionType,
5770 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005771 // Build an initializer list that designates the appropriate member
5772 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005773 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005774 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005775 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005776 SourceLocation());
5777 Initializer->setType(UnionType);
5778 Initializer->setInitializedFieldInUnion(Field);
5779
5780 // Build a compound literal constructing a value of the transparent
5781 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005782 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005783 EResult = S.Owned(
5784 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5785 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005786}
5787
5788Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005789Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005790 ExprResult &RHS) {
5791 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005792
Mike Stump1eb44332009-09-09 15:08:12 +00005793 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005794 // transparent_union GCC extension.
5795 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005796 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005797 return Incompatible;
5798
5799 // The field to initialize within the transparent union.
5800 RecordDecl *UD = UT->getDecl();
5801 FieldDecl *InitField = 0;
5802 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005803 for (RecordDecl::field_iterator it = UD->field_begin(),
5804 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005805 it != itend; ++it) {
5806 if (it->getType()->isPointerType()) {
5807 // If the transparent union contains a pointer type, we allow:
5808 // 1) void pointer
5809 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005810 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005811 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005812 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005813 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005814 break;
5815 }
Mike Stump1eb44332009-09-09 15:08:12 +00005816
Richard Trieuf7720da2011-09-06 20:40:12 +00005817 if (RHS.get()->isNullPointerConstant(Context,
5818 Expr::NPC_ValueDependentIsNull)) {
5819 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5820 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005821 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005822 break;
5823 }
5824 }
5825
John McCalldaa8e4e2010-11-15 09:13:47 +00005826 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005827 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005828 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005829 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005830 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005831 break;
5832 }
5833 }
5834
5835 if (!InitField)
5836 return Incompatible;
5837
Richard Trieuf7720da2011-09-06 20:40:12 +00005838 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005839 return Compatible;
5840}
5841
Chris Lattner5cf216b2008-01-04 18:04:52 +00005842Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005843Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5844 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005845 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005846 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005847 // C++ 5.17p3: If the left operand is not of class type, the
5848 // expression is implicitly converted (C++ 4) to the
5849 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005850 ExprResult Res;
5851 if (Diagnose) {
5852 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5853 AA_Assigning);
5854 } else {
5855 ImplicitConversionSequence ICS =
5856 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5857 /*SuppressUserConversions=*/false,
5858 /*AllowExplicit=*/false,
5859 /*InOverloadResolution=*/false,
5860 /*CStyle=*/false,
5861 /*AllowObjCWritebackConversion=*/false);
5862 if (ICS.isFailure())
5863 return Incompatible;
5864 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5865 ICS, AA_Assigning);
5866 }
John Wiegley429bb272011-04-08 18:41:53 +00005867 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005868 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005869 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005870 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005871 !CheckObjCARCUnavailableWeakConversion(LHSType,
5872 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005873 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005874 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005875 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005876 }
5877
5878 // FIXME: Currently, we fall through and treat C++ classes like C
5879 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005880 // FIXME: We also fall through for atomics; not sure what should
5881 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005882 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005883
Steve Naroff529a4ad2007-11-27 17:58:44 +00005884 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5885 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005886 if ((LHSType->isPointerType() ||
5887 LHSType->isObjCObjectPointerType() ||
5888 LHSType->isBlockPointerType())
5889 && RHS.get()->isNullPointerConstant(Context,
5890 Expr::NPC_ValueDependentIsNull)) {
5891 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005892 return Compatible;
5893 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005894
Chris Lattner943140e2007-10-16 02:55:40 +00005895 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005896 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005897 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005898 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005899 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005900 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005901 if (!LHSType->isReferenceType()) {
5902 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5903 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005904 return Incompatible;
5905 }
Steve Narofff1120de2007-08-24 22:33:52 +00005906
John McCalldaa8e4e2010-11-15 09:13:47 +00005907 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005908 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005909 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005910
Steve Narofff1120de2007-08-24 22:33:52 +00005911 // C99 6.5.16.1p2: The value of the right operand is converted to the
5912 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005913 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5914 // so that we can use references in built-in functions even in C.
5915 // The getNonReferenceType() call makes sure that the resulting expression
5916 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005917 if (result != Incompatible && RHS.get()->getType() != LHSType)
5918 RHS = ImpCastExprToType(RHS.take(),
5919 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005920 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005921}
5922
Richard Trieuf7720da2011-09-06 20:40:12 +00005923QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5924 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005925 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005926 << LHS.get()->getType() << RHS.get()->getType()
5927 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005928 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005929}
5930
Richard Trieu08062aa2011-09-06 21:01:04 +00005931QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005932 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005933 if (!IsCompAssign) {
5934 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5935 if (LHS.isInvalid())
5936 return QualType();
5937 }
5938 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5939 if (RHS.isInvalid())
5940 return QualType();
5941
Mike Stumpeed9cac2009-02-19 03:04:26 +00005942 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005943 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005944 QualType LHSType =
5945 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5946 QualType RHSType =
5947 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005948
Nate Begemanbe2341d2008-07-14 18:02:46 +00005949 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005950 if (LHSType == RHSType)
5951 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005952
Douglas Gregor255210e2010-08-06 10:14:59 +00005953 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005954 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5955 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5956 if (LHSType->isExtVectorType()) {
5957 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5958 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005959 }
5960
Richard Trieuccd891a2011-09-09 01:45:06 +00005961 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005962 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5963 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005964 }
5965
David Blaikie4e4d0842012-03-11 07:00:24 +00005966 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005967 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005968 // If we are allowing lax vector conversions, and LHS and RHS are both
5969 // vectors, the total size only needs to be the same. This is a
5970 // bitcast; no bits are changed but the result type is different.
5971 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005972 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5973 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005974 }
5975
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005976 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5977 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5978 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005979 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005980 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005981 std::swap(RHS, LHS);
5982 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005983 }
Mike Stump1eb44332009-09-09 15:08:12 +00005984
Nate Begemandde25982009-06-28 19:12:57 +00005985 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005986 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005987 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005988 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5989 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005990 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005991 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005992 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005993 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5994 if (swapped) std::swap(RHS, LHS);
5995 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005996 }
5997 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005998 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5999 RHSType->isRealFloatingType()) {
6000 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006001 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006002 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006003 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006004 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6005 if (swapped) std::swap(RHS, LHS);
6006 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006007 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006008 }
6009 }
Mike Stump1eb44332009-09-09 15:08:12 +00006010
Nate Begemandde25982009-06-28 19:12:57 +00006011 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006012 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006013 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006014 << LHS.get()->getType() << RHS.get()->getType()
6015 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006016 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006017}
6018
Richard Trieu481037f2011-09-16 00:53:10 +00006019// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6020// expression. These are mainly cases where the null pointer is used as an
6021// integer instead of a pointer.
6022static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6023 SourceLocation Loc, bool IsCompare) {
6024 // The canonical way to check for a GNU null is with isNullPointerConstant,
6025 // but we use a bit of a hack here for speed; this is a relatively
6026 // hot path, and isNullPointerConstant is slow.
6027 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6028 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6029
6030 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6031
6032 // Avoid analyzing cases where the result will either be invalid (and
6033 // diagnosed as such) or entirely valid and not something to warn about.
6034 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6035 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6036 return;
6037
6038 // Comparison operations would not make sense with a null pointer no matter
6039 // what the other expression is.
6040 if (!IsCompare) {
6041 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6042 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6043 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6044 return;
6045 }
6046
6047 // The rest of the operations only make sense with a null pointer
6048 // if the other expression is a pointer.
6049 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6050 NonNullType->canDecayToPointerType())
6051 return;
6052
6053 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6054 << LHSNull /* LHS is NULL */ << NonNullType
6055 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6056}
6057
Richard Trieu08062aa2011-09-06 21:01:04 +00006058QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006059 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006060 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006061 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6062
Richard Trieu08062aa2011-09-06 21:01:04 +00006063 if (LHS.get()->getType()->isVectorType() ||
6064 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006065 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006066
Richard Trieuccd891a2011-09-09 01:45:06 +00006067 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006068 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006069 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006070
David Chisnall7a7ee302012-01-16 17:27:18 +00006071
Eli Friedman860a3192012-06-16 02:19:17 +00006072 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006073 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006074
Chris Lattner7ef655a2010-01-12 21:23:57 +00006075 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006076 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006077 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006078 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006079 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6080 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006081
Chris Lattner7ef655a2010-01-12 21:23:57 +00006082 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006083}
6084
Chris Lattner7ef655a2010-01-12 21:23:57 +00006085QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006086 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006087 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6088
Richard Trieu08062aa2011-09-06 21:01:04 +00006089 if (LHS.get()->getType()->isVectorType() ||
6090 RHS.get()->getType()->isVectorType()) {
6091 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6092 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006093 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006094 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006095 }
Steve Naroff90045e82007-07-13 23:32:42 +00006096
Richard Trieuccd891a2011-09-09 01:45:06 +00006097 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006098 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006099 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006100
Eli Friedman860a3192012-06-16 02:19:17 +00006101 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006102 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006103
Chris Lattner7ef655a2010-01-12 21:23:57 +00006104 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006105 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006106 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006107 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6108 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006109
Chris Lattner7ef655a2010-01-12 21:23:57 +00006110 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006111}
6112
Chandler Carruth13b21be2011-06-27 08:02:19 +00006113/// \brief Diagnose invalid arithmetic on two void pointers.
6114static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006115 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006116 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006117 ? diag::err_typecheck_pointer_arith_void_type
6118 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006119 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6120 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006121}
6122
6123/// \brief Diagnose invalid arithmetic on a void pointer.
6124static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6125 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006126 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006127 ? diag::err_typecheck_pointer_arith_void_type
6128 : diag::ext_gnu_void_ptr)
6129 << 0 /* one pointer */ << Pointer->getSourceRange();
6130}
6131
6132/// \brief Diagnose invalid arithmetic on two function pointers.
6133static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6134 Expr *LHS, Expr *RHS) {
6135 assert(LHS->getType()->isAnyPointerType());
6136 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006137 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006138 ? diag::err_typecheck_pointer_arith_function_type
6139 : diag::ext_gnu_ptr_func_arith)
6140 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6141 // We only show the second type if it differs from the first.
6142 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6143 RHS->getType())
6144 << RHS->getType()->getPointeeType()
6145 << LHS->getSourceRange() << RHS->getSourceRange();
6146}
6147
6148/// \brief Diagnose invalid arithmetic on a function pointer.
6149static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6150 Expr *Pointer) {
6151 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006152 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006153 ? diag::err_typecheck_pointer_arith_function_type
6154 : diag::ext_gnu_ptr_func_arith)
6155 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6156 << 0 /* one pointer, so only one type */
6157 << Pointer->getSourceRange();
6158}
6159
Richard Trieud9f19342011-09-12 18:08:02 +00006160/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006161///
6162/// \returns True if pointer has incomplete type
6163static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6164 Expr *Operand) {
6165 if ((Operand->getType()->isPointerType() &&
6166 !Operand->getType()->isDependentType()) ||
6167 Operand->getType()->isObjCObjectPointerType()) {
6168 QualType PointeeTy = Operand->getType()->getPointeeType();
6169 if (S.RequireCompleteType(
6170 Loc, PointeeTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00006171 diag::err_typecheck_arithmetic_incomplete_type,
6172 PointeeTy, Operand->getSourceRange()))
Richard Trieu097ecd22011-09-02 02:15:37 +00006173 return true;
6174 }
6175 return false;
6176}
6177
Chandler Carruth13b21be2011-06-27 08:02:19 +00006178/// \brief Check the validity of an arithmetic pointer operand.
6179///
6180/// If the operand has pointer type, this code will check for pointer types
6181/// which are invalid in arithmetic operations. These will be diagnosed
6182/// appropriately, including whether or not the use is supported as an
6183/// extension.
6184///
6185/// \returns True when the operand is valid to use (even if as an extension).
6186static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6187 Expr *Operand) {
6188 if (!Operand->getType()->isAnyPointerType()) return true;
6189
6190 QualType PointeeTy = Operand->getType()->getPointeeType();
6191 if (PointeeTy->isVoidType()) {
6192 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006193 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006194 }
6195 if (PointeeTy->isFunctionType()) {
6196 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006197 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006198 }
6199
Richard Trieu097ecd22011-09-02 02:15:37 +00006200 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006201
6202 return true;
6203}
6204
6205/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6206/// operands.
6207///
6208/// This routine will diagnose any invalid arithmetic on pointer operands much
6209/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6210/// for emitting a single diagnostic even for operations where both LHS and RHS
6211/// are (potentially problematic) pointers.
6212///
6213/// \returns True when the operand is valid to use (even if as an extension).
6214static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006215 Expr *LHSExpr, Expr *RHSExpr) {
6216 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6217 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006218 if (!isLHSPointer && !isRHSPointer) return true;
6219
6220 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006221 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6222 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006223
6224 // Check for arithmetic on pointers to incomplete types.
6225 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6226 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6227 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006228 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6229 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6230 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006231
David Blaikie4e4d0842012-03-11 07:00:24 +00006232 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006233 }
6234
6235 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6236 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6237 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006238 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6239 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6240 RHSExpr);
6241 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006242
David Blaikie4e4d0842012-03-11 07:00:24 +00006243 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006244 }
6245
Richard Trieudef75842011-09-06 21:13:51 +00006246 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6247 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006248
Chandler Carruth13b21be2011-06-27 08:02:19 +00006249 return true;
6250}
6251
Richard Trieudb44a6b2011-09-01 22:53:23 +00006252/// \brief Check bad cases where we step over interface counts.
6253static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6254 SourceLocation OpLoc,
6255 Expr *Op) {
6256 assert(Op->getType()->isAnyPointerType());
6257 QualType PointeeTy = Op->getType()->getPointeeType();
John McCall260611a2012-06-20 06:18:46 +00006258 if (!PointeeTy->isObjCObjectType() || S.LangOpts.ObjCRuntime.isFragile())
Richard Trieudb44a6b2011-09-01 22:53:23 +00006259 return true;
6260
6261 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6262 << PointeeTy << Op->getSourceRange();
6263 return false;
6264}
6265
Nico Weber1cb2d742012-03-02 22:01:22 +00006266/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6267/// literal.
6268static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6269 Expr *LHSExpr, Expr *RHSExpr) {
6270 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6271 Expr* IndexExpr = RHSExpr;
6272 if (!StrExpr) {
6273 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6274 IndexExpr = LHSExpr;
6275 }
6276
6277 bool IsStringPlusInt = StrExpr &&
6278 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6279 if (!IsStringPlusInt)
6280 return;
6281
6282 llvm::APSInt index;
6283 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6284 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6285 if (index.isNonNegative() &&
6286 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6287 index.isUnsigned()))
6288 return;
6289 }
6290
6291 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6292 Self.Diag(OpLoc, diag::warn_string_plus_int)
6293 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6294
6295 // Only print a fixit for "str" + int, not for int + "str".
6296 if (IndexExpr == RHSExpr) {
6297 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6298 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6299 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6300 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6301 << FixItHint::CreateInsertion(EndLoc, "]");
6302 } else
6303 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6304}
6305
Richard Trieud9f19342011-09-12 18:08:02 +00006306/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006307static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006308 Expr *LHSExpr, Expr *RHSExpr) {
6309 assert(LHSExpr->getType()->isAnyPointerType());
6310 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006311 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006312 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6313 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006314}
6315
Chris Lattner7ef655a2010-01-12 21:23:57 +00006316QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006317 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6318 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006319 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6320
Richard Trieudef75842011-09-06 21:13:51 +00006321 if (LHS.get()->getType()->isVectorType() ||
6322 RHS.get()->getType()->isVectorType()) {
6323 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006324 if (CompLHSTy) *CompLHSTy = compType;
6325 return compType;
6326 }
Steve Naroff49b45262007-07-13 16:58:59 +00006327
Richard Trieudef75842011-09-06 21:13:51 +00006328 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6329 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006330 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006331
Nico Weber1cb2d742012-03-02 22:01:22 +00006332 // Diagnose "string literal" '+' int.
6333 if (Opc == BO_Add)
6334 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6335
Reid Spencer5f016e22007-07-11 17:01:13 +00006336 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006337 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006338 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006339 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006341
Eli Friedmand72d16e2008-05-18 18:08:51 +00006342 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006343 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006344 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006345 std::swap(PExp, IExp);
6346
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006347 if (!PExp->getType()->isAnyPointerType())
6348 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006349
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006350 if (!IExp->getType()->isIntegerType())
6351 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006352
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006353 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6354 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006355
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006356 // Diagnose bad cases where we step over interface counts.
6357 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6358 return QualType();
6359
6360 // Check array bounds for pointer arithemtic
6361 CheckArrayAccess(PExp, IExp);
6362
6363 if (CompLHSTy) {
6364 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6365 if (LHSTy.isNull()) {
6366 LHSTy = LHS.get()->getType();
6367 if (LHSTy->isPromotableIntegerType())
6368 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006369 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006370 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006371 }
6372
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006373 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006374}
6375
Chris Lattnereca7be62008-04-07 05:30:13 +00006376// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006377QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006378 SourceLocation Loc,
6379 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006380 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6381
Richard Trieudef75842011-09-06 21:13:51 +00006382 if (LHS.get()->getType()->isVectorType() ||
6383 RHS.get()->getType()->isVectorType()) {
6384 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006385 if (CompLHSTy) *CompLHSTy = compType;
6386 return compType;
6387 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006388
Richard Trieudef75842011-09-06 21:13:51 +00006389 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6390 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006391 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006392
Chris Lattner6e4ab612007-12-09 21:53:25 +00006393 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006394
Chris Lattner6e4ab612007-12-09 21:53:25 +00006395 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006396 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006397 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006398 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006399 }
Mike Stump1eb44332009-09-09 15:08:12 +00006400
Chris Lattner6e4ab612007-12-09 21:53:25 +00006401 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006402 if (LHS.get()->getType()->isAnyPointerType()) {
6403 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006404
Chris Lattnerb5f15622009-04-24 23:50:08 +00006405 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006406 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006407 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006408
Chris Lattner6e4ab612007-12-09 21:53:25 +00006409 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006410 if (RHS.get()->getType()->isIntegerType()) {
6411 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006412 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006413
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006414 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006415 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6416 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006417
Richard Trieudef75842011-09-06 21:13:51 +00006418 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6419 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006420 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006421
Chris Lattner6e4ab612007-12-09 21:53:25 +00006422 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006423 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006424 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006425 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006426
David Blaikie4e4d0842012-03-11 07:00:24 +00006427 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006428 // Pointee types must be the same: C++ [expr.add]
6429 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006430 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006431 }
6432 } else {
6433 // Pointee types must be compatible C99 6.5.6p3
6434 if (!Context.typesAreCompatible(
6435 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6436 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006437 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006438 return QualType();
6439 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006440 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006441
Chandler Carruth13b21be2011-06-27 08:02:19 +00006442 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006443 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006444 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006445
Richard Trieudef75842011-09-06 21:13:51 +00006446 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006447 return Context.getPointerDiffType();
6448 }
6449 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006450
Richard Trieudef75842011-09-06 21:13:51 +00006451 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006452}
6453
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006454static bool isScopedEnumerationType(QualType T) {
6455 if (const EnumType *ET = dyn_cast<EnumType>(T))
6456 return ET->getDecl()->isScoped();
6457 return false;
6458}
6459
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006460static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006461 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006462 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006463 llvm::APSInt Right;
6464 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006465 if (RHS.get()->isValueDependent() ||
6466 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006467 return;
6468
6469 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006470 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006471 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006472 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006473 return;
6474 }
6475 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006476 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006477 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006478 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006479 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006480 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006481 return;
6482 }
6483 if (Opc != BO_Shl)
6484 return;
6485
6486 // When left shifting an ICE which is signed, we can check for overflow which
6487 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6488 // integers have defined behavior modulo one more than the maximum value
6489 // representable in the result type, so never warn for those.
6490 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006491 if (LHS.get()->isValueDependent() ||
6492 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6493 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006494 return;
6495 llvm::APInt ResultBits =
6496 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6497 if (LeftBits.uge(ResultBits))
6498 return;
6499 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6500 Result = Result.shl(Right);
6501
Ted Kremenekfa821382011-06-15 00:54:52 +00006502 // Print the bit representation of the signed integer as an unsigned
6503 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006504 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006505 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6506
Chandler Carruth21206d52011-02-23 23:34:11 +00006507 // If we are only missing a sign bit, this is less likely to result in actual
6508 // bugs -- if the result is cast back to an unsigned type, it will have the
6509 // expected value. Thus we place this behind a different warning that can be
6510 // turned off separately if needed.
6511 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006512 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006513 << HexResult.str() << LHSType
6514 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006515 return;
6516 }
6517
6518 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006519 << HexResult.str() << Result.getMinSignedBits() << LHSType
6520 << Left.getBitWidth() << LHS.get()->getSourceRange()
6521 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006522}
6523
Chris Lattnereca7be62008-04-07 05:30:13 +00006524// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006525QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006526 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006527 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006528 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6529
Chris Lattnerca5eede2007-12-12 05:47:28 +00006530 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006531 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6532 !RHS.get()->getType()->hasIntegerRepresentation())
6533 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006534
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006535 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6536 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006537 if (isScopedEnumerationType(LHS.get()->getType()) ||
6538 isScopedEnumerationType(RHS.get()->getType())) {
6539 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006540 }
6541
Nate Begeman2207d792009-10-25 02:26:48 +00006542 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006543 if (LHS.get()->getType()->isVectorType() ||
6544 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006545 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006546
Chris Lattnerca5eede2007-12-12 05:47:28 +00006547 // Shifts don't perform usual arithmetic conversions, they just do integer
6548 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006549
John McCall1bc80af2010-12-16 19:28:59 +00006550 // For the LHS, do usual unary conversions, but then reset them away
6551 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006552 ExprResult OldLHS = LHS;
6553 LHS = UsualUnaryConversions(LHS.take());
6554 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006555 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006556 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006557 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006558
6559 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006560 RHS = UsualUnaryConversions(RHS.take());
6561 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006562 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006563
Ryan Flynnd0439682009-08-07 16:20:20 +00006564 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006565 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006566
Chris Lattnerca5eede2007-12-12 05:47:28 +00006567 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006568 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006569}
6570
Chandler Carruth99919472010-07-10 12:30:03 +00006571static bool IsWithinTemplateSpecialization(Decl *D) {
6572 if (DeclContext *DC = D->getDeclContext()) {
6573 if (isa<ClassTemplateSpecializationDecl>(DC))
6574 return true;
6575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6576 return FD->isFunctionTemplateSpecialization();
6577 }
6578 return false;
6579}
6580
Richard Trieue648ac32011-09-02 03:48:46 +00006581/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006582static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6583 ExprResult &RHS) {
6584 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6585 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006586
6587 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6588 if (!LHSEnumType)
6589 return;
6590 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6591 if (!RHSEnumType)
6592 return;
6593
6594 // Ignore anonymous enums.
6595 if (!LHSEnumType->getDecl()->getIdentifier())
6596 return;
6597 if (!RHSEnumType->getDecl()->getIdentifier())
6598 return;
6599
6600 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6601 return;
6602
6603 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6604 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006605 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006606}
6607
Richard Trieu7be1be02011-09-02 02:55:45 +00006608/// \brief Diagnose bad pointer comparisons.
6609static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006610 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006611 bool IsError) {
6612 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006613 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006614 << LHS.get()->getType() << RHS.get()->getType()
6615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006616}
6617
6618/// \brief Returns false if the pointers are converted to a composite type,
6619/// true otherwise.
6620static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006621 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006622 // C++ [expr.rel]p2:
6623 // [...] Pointer conversions (4.10) and qualification
6624 // conversions (4.4) are performed on pointer operands (or on
6625 // a pointer operand and a null pointer constant) to bring
6626 // them to their composite pointer type. [...]
6627 //
6628 // C++ [expr.eq]p1 uses the same notion for (in)equality
6629 // comparisons of pointers.
6630
6631 // C++ [expr.eq]p2:
6632 // In addition, pointers to members can be compared, or a pointer to
6633 // member and a null pointer constant. Pointer to member conversions
6634 // (4.11) and qualification conversions (4.4) are performed to bring
6635 // them to a common type. If one operand is a null pointer constant,
6636 // the common type is the type of the other operand. Otherwise, the
6637 // common type is a pointer to member type similar (4.4) to the type
6638 // of one of the operands, with a cv-qualification signature (4.4)
6639 // that is the union of the cv-qualification signatures of the operand
6640 // types.
6641
Richard Trieuba261492011-09-06 21:27:33 +00006642 QualType LHSType = LHS.get()->getType();
6643 QualType RHSType = RHS.get()->getType();
6644 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6645 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006646
6647 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006648 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006649 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006650 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006651 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006652 return true;
6653 }
6654
6655 if (NonStandardCompositeType)
6656 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006657 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6658 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006659
Richard Trieuba261492011-09-06 21:27:33 +00006660 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6661 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006662 return false;
6663}
6664
6665static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006666 ExprResult &LHS,
6667 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006668 bool IsError) {
6669 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6670 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006671 << LHS.get()->getType() << RHS.get()->getType()
6672 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006673}
6674
Jordan Rose9f63a452012-06-08 21:14:25 +00006675static bool isObjCObjectLiteral(ExprResult &E) {
6676 switch (E.get()->getStmtClass()) {
6677 case Stmt::ObjCArrayLiteralClass:
6678 case Stmt::ObjCDictionaryLiteralClass:
6679 case Stmt::ObjCStringLiteralClass:
6680 case Stmt::ObjCBoxedExprClass:
6681 return true;
6682 default:
6683 // Note that ObjCBoolLiteral is NOT an object literal!
6684 return false;
6685 }
6686}
6687
6688static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6689 SourceLocation Loc,
6690 ExprResult &LHS,
6691 ExprResult &RHS,
6692 bool CanFix = false) {
6693 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6694
6695 unsigned LiteralKind;
6696 switch (Literal->getStmtClass()) {
6697 case Stmt::ObjCStringLiteralClass:
6698 // "string literal"
6699 LiteralKind = 0;
6700 break;
6701 case Stmt::ObjCArrayLiteralClass:
6702 // "array literal"
6703 LiteralKind = 1;
6704 break;
6705 case Stmt::ObjCDictionaryLiteralClass:
6706 // "dictionary literal"
6707 LiteralKind = 2;
6708 break;
6709 case Stmt::ObjCBoxedExprClass: {
6710 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6711 switch (Inner->getStmtClass()) {
6712 case Stmt::IntegerLiteralClass:
6713 case Stmt::FloatingLiteralClass:
6714 case Stmt::CharacterLiteralClass:
6715 case Stmt::ObjCBoolLiteralExprClass:
6716 case Stmt::CXXBoolLiteralExprClass:
6717 // "numeric literal"
6718 LiteralKind = 3;
6719 break;
6720 case Stmt::ImplicitCastExprClass: {
6721 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6722 // Boolean literals can be represented by implicit casts.
6723 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6724 LiteralKind = 3;
6725 break;
6726 }
6727 // FALLTHROUGH
6728 }
6729 default:
6730 // "boxed expression"
6731 LiteralKind = 4;
6732 break;
6733 }
6734 break;
6735 }
6736 default:
6737 llvm_unreachable("Unknown Objective-C object literal kind");
6738 }
6739
6740 return S.Diag(Loc, diag::err_objc_literal_comparison)
6741 << LiteralKind << CanFix << Literal->getSourceRange();
6742}
6743
6744static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6745 ExprResult &LHS,
6746 ExprResult &RHS,
6747 BinaryOperatorKind Op) {
6748 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6749
6750 // Get the LHS object's interface type.
6751 QualType Type = LHS.get()->getType();
6752 QualType InterfaceType;
6753 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6754 InterfaceType = PTy->getPointeeType();
6755 if (const ObjCObjectType *iQFaceTy =
6756 InterfaceType->getAsObjCQualifiedInterfaceType())
6757 InterfaceType = iQFaceTy->getBaseType();
6758 } else {
6759 // If this is not actually an Objective-C object, bail out.
6760 return ExprEmpty();
6761 }
6762
6763 // If the RHS isn't an Objective-C object, bail out.
6764 if (!RHS.get()->getType()->isObjCObjectPointerType())
6765 return ExprEmpty();
6766
6767 // Try to find the -isEqual: method.
6768 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6769 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6770 InterfaceType,
6771 /*instance=*/true);
6772 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6773
6774 if (!Method && ReceiverIsId) {
6775 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6776 /*receiverId=*/true,
6777 /*warn=*/false);
6778 }
6779
6780 if (!Method)
6781 return ExprEmpty();
6782
6783 QualType T = Method->param_begin()[0]->getType();
6784 if (!T->isObjCObjectPointerType())
6785 return ExprEmpty();
6786
6787 QualType R = Method->getResultType();
6788 if (!R->isScalarType())
6789 return ExprEmpty();
6790
6791 // At this point we know we have a good -isEqual: method.
6792 // Emit the diagnostic and fixit.
6793 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6794 LHS, RHS, true);
6795
6796 Expr *LHSExpr = LHS.take();
6797 Expr *RHSExpr = RHS.take();
6798
6799 SourceLocation Start = LHSExpr->getLocStart();
6800 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6801 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6802
6803 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6804 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6805 << FixItHint::CreateInsertion(End, "]");
6806
6807 // Finally, build the call to -isEqual: (and possible logical not).
6808 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6809 /*SuperLoc=*/SourceLocation(),
6810 IsEqualSel, Method,
6811 OpLoc, OpLoc, OpLoc,
6812 MultiExprArg(S, &RHSExpr, 1),
6813 /*isImplicit=*/false);
6814
6815 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6816
6817 if (Op == BO_NE)
6818 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6819 return CallCond;
6820}
6821
Douglas Gregor0c6db942009-05-04 06:07:12 +00006822// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006823QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006824 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006825 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006826 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6827
John McCall2de56d12010-08-25 11:45:40 +00006828 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006829
Chris Lattner02dd4b12009-12-05 05:40:13 +00006830 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006831 if (LHS.get()->getType()->isVectorType() ||
6832 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006833 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006834
Richard Trieuf1775fb2011-09-06 21:43:51 +00006835 QualType LHSType = LHS.get()->getType();
6836 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006837
Richard Trieuf1775fb2011-09-06 21:43:51 +00006838 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6839 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006840
Richard Trieuf1775fb2011-09-06 21:43:51 +00006841 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006842
Richard Trieuf1775fb2011-09-06 21:43:51 +00006843 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006844 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006845 !LHS.get()->getLocStart().isMacroID() &&
6846 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006847 // For non-floating point types, check for self-comparisons of the form
6848 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6849 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006850 //
6851 // NOTE: Don't warn about comparison expressions resulting from macro
6852 // expansion. Also don't warn about comparisons which are only self
6853 // comparisons within a template specialization. The warnings should catch
6854 // obvious cases in the definition of the template anyways. The idea is to
6855 // warn when the typed comparison operator will always evaluate to the same
6856 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006857 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006858 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006859 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006860 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006861 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006862 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006863 << (Opc == BO_EQ
6864 || Opc == BO_LE
6865 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006866 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006867 !DRL->getDecl()->getType()->isReferenceType() &&
6868 !DRR->getDecl()->getType()->isReferenceType()) {
6869 // what is it always going to eval to?
6870 char always_evals_to;
6871 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006872 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006873 always_evals_to = 0; // false
6874 break;
John McCall2de56d12010-08-25 11:45:40 +00006875 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006876 always_evals_to = 1; // true
6877 break;
6878 default:
6879 // best we can say is 'a constant'
6880 always_evals_to = 2; // e.g. array1 <= array2
6881 break;
6882 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006883 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006884 << 1 // array
6885 << always_evals_to);
6886 }
6887 }
Chandler Carruth99919472010-07-10 12:30:03 +00006888 }
Mike Stump1eb44332009-09-09 15:08:12 +00006889
Chris Lattner55660a72009-03-08 19:39:53 +00006890 if (isa<CastExpr>(LHSStripped))
6891 LHSStripped = LHSStripped->IgnoreParenCasts();
6892 if (isa<CastExpr>(RHSStripped))
6893 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006894
Chris Lattner55660a72009-03-08 19:39:53 +00006895 // Warn about comparisons against a string constant (unless the other
6896 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006897 Expr *literalString = 0;
6898 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006899 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006900 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006901 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006902 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006903 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006904 } else if ((isa<StringLiteral>(RHSStripped) ||
6905 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006906 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006907 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006908 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006909 literalStringStripped = RHSStripped;
6910 }
6911
6912 if (literalString) {
6913 std::string resultComparison;
6914 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006915 case BO_LT: resultComparison = ") < 0"; break;
6916 case BO_GT: resultComparison = ") > 0"; break;
6917 case BO_LE: resultComparison = ") <= 0"; break;
6918 case BO_GE: resultComparison = ") >= 0"; break;
6919 case BO_EQ: resultComparison = ") == 0"; break;
6920 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006921 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006922 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006923
Ted Kremenek351ba912011-02-23 01:52:04 +00006924 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006925 PDiag(diag::warn_stringcompare)
6926 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006927 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006928 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006929 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006930
Douglas Gregord64fdd02010-06-08 19:50:34 +00006931 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006932 if (LHS.get()->getType()->isArithmeticType() &&
6933 RHS.get()->getType()->isArithmeticType()) {
6934 UsualArithmeticConversions(LHS, RHS);
6935 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006936 return QualType();
6937 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006938 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006939 LHS = UsualUnaryConversions(LHS.take());
6940 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006941 return QualType();
6942
Richard Trieuf1775fb2011-09-06 21:43:51 +00006943 RHS = UsualUnaryConversions(RHS.take());
6944 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006945 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006946 }
6947
Richard Trieuf1775fb2011-09-06 21:43:51 +00006948 LHSType = LHS.get()->getType();
6949 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006950
Douglas Gregor447b69e2008-11-19 03:25:36 +00006951 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006952 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006953
Richard Trieuccd891a2011-09-09 01:45:06 +00006954 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006955 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006956 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006957 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006958 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006959 if (LHSType->hasFloatingRepresentation())
6960 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006961
Richard Trieuf1775fb2011-09-06 21:43:51 +00006962 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006963 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006964 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006965
Richard Trieuf1775fb2011-09-06 21:43:51 +00006966 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006967 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006968 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006969 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006970
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006971 // All of the following pointer-related warnings are GCC extensions, except
6972 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006973 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006974 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006975 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006976 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006977 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006978
David Blaikie4e4d0842012-03-11 07:00:24 +00006979 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006980 if (LCanPointeeTy == RCanPointeeTy)
6981 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006982 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006983 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6984 // Valid unless comparison between non-null pointer and function pointer
6985 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006986 // In a SFINAE context, we treat this as a hard error to maintain
6987 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006988 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6989 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006990 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006991 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006992
6993 if (isSFINAEContext())
6994 return QualType();
6995
Richard Trieuf1775fb2011-09-06 21:43:51 +00006996 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006997 return ResultTy;
6998 }
6999 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007000
Richard Trieuf1775fb2011-09-06 21:43:51 +00007001 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007002 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007003 else
7004 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007005 }
Eli Friedman3075e762009-08-23 00:27:47 +00007006 // C99 6.5.9p2 and C99 6.5.8p2
7007 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7008 RCanPointeeTy.getUnqualifiedType())) {
7009 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007010 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007011 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007012 << LHSType << RHSType << LHS.get()->getSourceRange()
7013 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007014 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007015 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007016 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7017 // Valid unless comparison between non-null pointer and function pointer
7018 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007019 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007020 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007021 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007022 } else {
7023 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007024 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007025 }
John McCall34d6f932011-03-11 04:25:25 +00007026 if (LCanPointeeTy != RCanPointeeTy) {
7027 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007028 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007029 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007030 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007031 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007032 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007033 }
Mike Stump1eb44332009-09-09 15:08:12 +00007034
David Blaikie4e4d0842012-03-11 07:00:24 +00007035 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007036 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007037 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007038 return ResultTy;
7039
Mike Stump1eb44332009-09-09 15:08:12 +00007040 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007041 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007042 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007043 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007044 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007045 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7046 RHS = ImpCastExprToType(RHS.take(), LHSType,
7047 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007048 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007049 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007050 return ResultTy;
7051 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007052 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007053 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007054 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007055 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7056 LHS = ImpCastExprToType(LHS.take(), RHSType,
7057 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007058 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007059 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007060 return ResultTy;
7061 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007062
7063 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007064 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007065 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7066 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007067 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007068 else
7069 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007070 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007071
7072 // Handle scoped enumeration types specifically, since they don't promote
7073 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007074 if (LHS.get()->getType()->isEnumeralType() &&
7075 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7076 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007077 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007078 }
Mike Stump1eb44332009-09-09 15:08:12 +00007079
Steve Naroff1c7d0672008-09-04 15:10:53 +00007080 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007081 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007082 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007083 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7084 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007085
Steve Naroff1c7d0672008-09-04 15:10:53 +00007086 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007087 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007088 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007089 << LHSType << RHSType << LHS.get()->getSourceRange()
7090 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007091 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007092 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007093 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007094 }
John Wiegley429bb272011-04-08 18:41:53 +00007095
Steve Naroff59f53942008-09-28 01:11:11 +00007096 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007097 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007098 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7099 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007100 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007101 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007102 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007103 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007104 ->getPointeeType()->isVoidType())))
7105 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007106 << LHSType << RHSType << LHS.get()->getSourceRange()
7107 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007108 }
John McCall34d6f932011-03-11 04:25:25 +00007109 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007110 LHS = ImpCastExprToType(LHS.take(), RHSType,
7111 RHSType->isPointerType() ? CK_BitCast
7112 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007113 else
John McCall1d9b3b22011-09-09 05:25:32 +00007114 RHS = ImpCastExprToType(RHS.take(), LHSType,
7115 LHSType->isPointerType() ? CK_BitCast
7116 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007117 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007118 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007119
Richard Trieuf1775fb2011-09-06 21:43:51 +00007120 if (LHSType->isObjCObjectPointerType() ||
7121 RHSType->isObjCObjectPointerType()) {
7122 const PointerType *LPT = LHSType->getAs<PointerType>();
7123 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007124 if (LPT || RPT) {
7125 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7126 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007127
Steve Naroffa8069f12008-11-17 19:49:16 +00007128 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007129 !Context.typesAreCompatible(LHSType, RHSType)) {
7130 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007131 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007132 }
John McCall34d6f932011-03-11 04:25:25 +00007133 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007134 LHS = ImpCastExprToType(LHS.take(), RHSType,
7135 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007136 else
John McCall1d9b3b22011-09-09 05:25:32 +00007137 RHS = ImpCastExprToType(RHS.take(), LHSType,
7138 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007139 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007140 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007141 if (LHSType->isObjCObjectPointerType() &&
7142 RHSType->isObjCObjectPointerType()) {
7143 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7144 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007145 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007146 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7147 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7148
John McCall34d6f932011-03-11 04:25:25 +00007149 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007150 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007151 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007152 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007153 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007154 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007155 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007156 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7157 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007158 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007159 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007160 if ((LHSIsNull && LHSType->isIntegerType()) ||
7161 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007162 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007163 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007164 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007165 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007166 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007167 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7168 isError = true;
7169 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007170 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007171
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007172 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007173 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007174 << LHSType << RHSType << LHS.get()->getSourceRange()
7175 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007176 if (isError)
7177 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007178 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007179
Richard Trieuf1775fb2011-09-06 21:43:51 +00007180 if (LHSType->isIntegerType())
7181 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007182 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007183 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007184 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007185 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007186 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007187 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007188
Steve Naroff39218df2008-09-04 16:56:14 +00007189 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007190 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007191 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7192 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007193 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007194 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007195 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007196 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7197 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007198 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007199 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007200
Richard Trieuf1775fb2011-09-06 21:43:51 +00007201 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007202}
7203
Tanya Lattner4f692c22012-01-16 21:02:28 +00007204
7205// Return a signed type that is of identical size and number of elements.
7206// For floating point vectors, return an integer type of identical size
7207// and number of elements.
7208QualType Sema::GetSignedVectorType(QualType V) {
7209 const VectorType *VTy = V->getAs<VectorType>();
7210 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7211 if (TypeSize == Context.getTypeSize(Context.CharTy))
7212 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7213 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7214 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7215 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7216 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7217 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7218 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7219 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7220 "Unhandled vector element size in vector compare");
7221 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7222}
7223
Nate Begemanbe2341d2008-07-14 18:02:46 +00007224/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007225/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007226/// like a scalar comparison, a vector comparison produces a vector of integer
7227/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007228QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007229 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007230 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007231 // Check to make sure we're operating on vectors of the same type and width,
7232 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007233 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007234 if (vType.isNull())
7235 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007236
Richard Trieu9f60dee2011-09-07 01:19:57 +00007237 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007238
Anton Yartsev7870b132011-03-27 15:36:07 +00007239 // If AltiVec, the comparison results in a numeric type, i.e.
7240 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007241 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007242 return Context.getLogicalOperationType();
7243
Nate Begemanbe2341d2008-07-14 18:02:46 +00007244 // For non-floating point types, check for self-comparisons of the form
7245 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7246 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007247 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007248 if (DeclRefExpr* DRL
7249 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7250 if (DeclRefExpr* DRR
7251 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007252 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007253 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007254 PDiag(diag::warn_comparison_always)
7255 << 0 // self-
7256 << 2 // "a constant"
7257 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007258 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007259
Nate Begemanbe2341d2008-07-14 18:02:46 +00007260 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007261 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007262 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007263 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007264 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007265
7266 // Return a signed type for the vector.
7267 return GetSignedVectorType(LHSType);
7268}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007269
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007270QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7271 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007272 // Ensure that either both operands are of the same vector type, or
7273 // one operand is of a vector type and the other is of its element type.
7274 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7275 if (vType.isNull() || vType->isFloatingType())
7276 return InvalidOperands(Loc, LHS, RHS);
7277
7278 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007279}
7280
Reid Spencer5f016e22007-07-11 17:01:13 +00007281inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007282 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007283 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7284
Richard Trieu9f60dee2011-09-07 01:19:57 +00007285 if (LHS.get()->getType()->isVectorType() ||
7286 RHS.get()->getType()->isVectorType()) {
7287 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7288 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007289 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007290
Richard Trieu9f60dee2011-09-07 01:19:57 +00007291 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007292 }
Steve Naroff90045e82007-07-13 23:32:42 +00007293
Richard Trieu9f60dee2011-09-07 01:19:57 +00007294 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7295 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007296 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007297 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007298 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007299 LHS = LHSResult.take();
7300 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007301
Eli Friedman860a3192012-06-16 02:19:17 +00007302 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007303 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007304 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007305}
7306
7307inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007308 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007309
Tanya Lattner4f692c22012-01-16 21:02:28 +00007310 // Check vector operands differently.
7311 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7312 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7313
Chris Lattner90a8f272010-07-13 19:41:32 +00007314 // Diagnose cases where the user write a logical and/or but probably meant a
7315 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7316 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007317 if (LHS.get()->getType()->isIntegerType() &&
7318 !LHS.get()->getType()->isBooleanType() &&
7319 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007320 // Don't warn in macros or template instantiations.
7321 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007322 // If the RHS can be constant folded, and if it constant folds to something
7323 // that isn't 0 or 1 (which indicate a potential logical operation that
7324 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007325 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007326 llvm::APSInt Result;
7327 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007328 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007329 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007330 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007331 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007332 << (Opc == BO_LAnd ? "&&" : "||");
7333 // Suggest replacing the logical operator with the bitwise version
7334 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7335 << (Opc == BO_LAnd ? "&" : "|")
7336 << FixItHint::CreateReplacement(SourceRange(
7337 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007338 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007339 Opc == BO_LAnd ? "&" : "|");
7340 if (Opc == BO_LAnd)
7341 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7342 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7343 << FixItHint::CreateRemoval(
7344 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007345 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007346 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007347 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007348 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007349 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007350 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007351
David Blaikie4e4d0842012-03-11 07:00:24 +00007352 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007353 LHS = UsualUnaryConversions(LHS.take());
7354 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007355 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007356
Richard Trieu9f60dee2011-09-07 01:19:57 +00007357 RHS = UsualUnaryConversions(RHS.take());
7358 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007359 return QualType();
7360
Richard Trieu9f60dee2011-09-07 01:19:57 +00007361 if (!LHS.get()->getType()->isScalarType() ||
7362 !RHS.get()->getType()->isScalarType())
7363 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007364
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007365 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007366 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007367
John McCall75f7c0f2010-06-04 00:29:51 +00007368 // The following is safe because we only use this method for
7369 // non-overloadable operands.
7370
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007371 // C++ [expr.log.and]p1
7372 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007373 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007374 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7375 if (LHSRes.isInvalid())
7376 return InvalidOperands(Loc, LHS, RHS);
7377 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007378
Richard Trieu9f60dee2011-09-07 01:19:57 +00007379 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7380 if (RHSRes.isInvalid())
7381 return InvalidOperands(Loc, LHS, RHS);
7382 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007383
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007384 // C++ [expr.log.and]p2
7385 // C++ [expr.log.or]p2
7386 // The result is a bool.
7387 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007388}
7389
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007390/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7391/// is a read-only property; return true if so. A readonly property expression
7392/// depends on various declarations and thus must be treated specially.
7393///
Mike Stump1eb44332009-09-09 15:08:12 +00007394static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007395 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7396 if (!PropExpr) return false;
7397 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007398
John McCall3c3b7f92011-10-25 17:37:35 +00007399 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7400 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007401 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007402 PropExpr->getBase()->getType();
7403
John McCall3c3b7f92011-10-25 17:37:35 +00007404 if (const ObjCObjectPointerType *OPT =
7405 BaseType->getAsObjCInterfacePointerType())
7406 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7407 if (S.isPropertyReadonly(PDecl, IFace))
7408 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007409 return false;
7410}
7411
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007412static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007413 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7414 if (!ME) return false;
7415 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7416 ObjCMessageExpr *Base =
7417 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7418 if (!Base) return false;
7419 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007420}
7421
John McCall78dae242012-03-13 00:37:01 +00007422/// Is the given expression (which must be 'const') a reference to a
7423/// variable which was originally non-const, but which has become
7424/// 'const' due to being captured within a block?
7425enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7426static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7427 assert(E->isLValue() && E->getType().isConstQualified());
7428 E = E->IgnoreParens();
7429
7430 // Must be a reference to a declaration from an enclosing scope.
7431 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7432 if (!DRE) return NCCK_None;
7433 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7434
7435 // The declaration must be a variable which is not declared 'const'.
7436 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7437 if (!var) return NCCK_None;
7438 if (var->getType().isConstQualified()) return NCCK_None;
7439 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7440
7441 // Decide whether the first capture was for a block or a lambda.
7442 DeclContext *DC = S.CurContext;
7443 while (DC->getParent() != var->getDeclContext())
7444 DC = DC->getParent();
7445 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7446}
7447
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007448/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7449/// emit an error and return true. If so, return false.
7450static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007451 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007452 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007453 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007454 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007455 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7456 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007457 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7458 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007459 if (IsLV == Expr::MLV_Valid)
7460 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007461
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007462 unsigned Diag = 0;
7463 bool NeedType = false;
7464 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007465 case Expr::MLV_ConstQualified:
7466 Diag = diag::err_typecheck_assign_const;
7467
John McCall78dae242012-03-13 00:37:01 +00007468 // Use a specialized diagnostic when we're assigning to an object
7469 // from an enclosing function or block.
7470 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7471 if (NCCK == NCCK_Block)
7472 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7473 else
7474 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7475 break;
7476 }
7477
John McCall7acddac2011-06-17 06:42:21 +00007478 // In ARC, use some specialized diagnostics for occasions where we
7479 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007480 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007481 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7482 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7483 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7484
John McCall7acddac2011-06-17 06:42:21 +00007485 // Use the normal diagnostic if it's pseudo-__strong but the
7486 // user actually wrote 'const'.
7487 if (var->isARCPseudoStrong() &&
7488 (!var->getTypeSourceInfo() ||
7489 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7490 // There are two pseudo-strong cases:
7491 // - self
John McCallf85e1932011-06-15 23:02:42 +00007492 ObjCMethodDecl *method = S.getCurMethodDecl();
7493 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007494 Diag = method->isClassMethod()
7495 ? diag::err_typecheck_arc_assign_self_class_method
7496 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007497
7498 // - fast enumeration variables
7499 else
John McCallf85e1932011-06-15 23:02:42 +00007500 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007501
John McCallf85e1932011-06-15 23:02:42 +00007502 SourceRange Assign;
7503 if (Loc != OrigLoc)
7504 Assign = SourceRange(OrigLoc, OrigLoc);
7505 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7506 // We need to preserve the AST regardless, so migration tool
7507 // can do its job.
7508 return false;
7509 }
7510 }
7511 }
7512
7513 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007514 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007515 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007516 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7517 NeedType = true;
7518 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007519 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007520 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7521 NeedType = true;
7522 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007523 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007524 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7525 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007526 case Expr::MLV_Valid:
7527 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007528 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007529 case Expr::MLV_MemberFunction:
7530 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007531 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7532 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007533 case Expr::MLV_IncompleteType:
7534 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007535 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007536 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007537 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007538 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7539 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007540 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007541 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007542 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007543 case Expr::MLV_InvalidMessageExpression:
7544 Diag = diag::error_readonly_message_assignment;
7545 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007546 case Expr::MLV_SubObjCPropertySetting:
7547 Diag = diag::error_no_subobject_property_setting;
7548 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007549 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007550
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007551 SourceRange Assign;
7552 if (Loc != OrigLoc)
7553 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007554 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007555 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007556 else
Mike Stump1eb44332009-09-09 15:08:12 +00007557 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007558 return true;
7559}
7560
7561
7562
7563// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007564QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007565 SourceLocation Loc,
7566 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007567 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7568
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007569 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007570 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007571 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007572
Richard Trieu268942b2011-09-07 01:33:52 +00007573 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007574 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7575 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007576 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007577 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007578 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007579 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007580 if (RHS.isInvalid())
7581 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007582 // Special case of NSObject attributes on c-style pointer types.
7583 if (ConvTy == IncompatiblePointer &&
7584 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007585 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007586 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007587 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007588 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007589
John McCallf89e55a2010-11-18 06:31:45 +00007590 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007591 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007592 Diag(Loc, diag::err_objc_object_assignment)
7593 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007594
Chris Lattner2c156472008-08-21 18:04:13 +00007595 // If the RHS is a unary plus or minus, check to see if they = and + are
7596 // right next to each other. If so, the user may have typo'd "x =+ 4"
7597 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007598 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007599 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7600 RHSCheck = ICE->getSubExpr();
7601 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007602 if ((UO->getOpcode() == UO_Plus ||
7603 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007604 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007605 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007606 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007607 // And there is a space or other character before the subexpr of the
7608 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007609 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007610 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007611 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007612 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007613 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007614 }
Chris Lattner2c156472008-08-21 18:04:13 +00007615 }
John McCallf85e1932011-06-15 23:02:42 +00007616
7617 if (ConvTy == Compatible) {
7618 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007619 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007620 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007621 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007622 }
Chris Lattner2c156472008-08-21 18:04:13 +00007623 } else {
7624 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007625 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007626 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007627
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007628 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007629 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007630 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007631
Richard Trieu268942b2011-09-07 01:33:52 +00007632 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007633
Reid Spencer5f016e22007-07-11 17:01:13 +00007634 // C99 6.5.16p3: The type of an assignment expression is the type of the
7635 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007636 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007637 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7638 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007639 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007640 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007641 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007642 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007643}
7644
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007645// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007646static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007647 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007648 LHS = S.CheckPlaceholderExpr(LHS.take());
7649 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007650 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007651 return QualType();
7652
John McCallcf2e5062010-10-12 07:14:40 +00007653 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7654 // operands, but not unary promotions.
7655 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007656
John McCallf6a16482010-12-04 03:47:34 +00007657 // So we treat the LHS as a ignored value, and in C++ we allow the
7658 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007659 LHS = S.IgnoredValueConversions(LHS.take());
7660 if (LHS.isInvalid())
7661 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007662
Eli Friedmana6115062012-05-24 00:47:05 +00007663 S.DiagnoseUnusedExprResult(LHS.get());
7664
David Blaikie4e4d0842012-03-11 07:00:24 +00007665 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007666 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7667 if (RHS.isInvalid())
7668 return QualType();
7669 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007670 S.RequireCompleteType(Loc, RHS.get()->getType(),
7671 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007672 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007673
John Wiegley429bb272011-04-08 18:41:53 +00007674 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007675}
7676
Steve Naroff49b45262007-07-13 16:58:59 +00007677/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7678/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007679static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7680 ExprValueKind &VK,
7681 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007682 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007683 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007684 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007685
Chris Lattner3528d352008-11-21 07:05:48 +00007686 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007687 // Atomic types can be used for increment / decrement where the non-atomic
7688 // versions can, so ignore the _Atomic() specifier for the purpose of
7689 // checking.
7690 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7691 ResType = ResAtomicType->getValueType();
7692
Chris Lattner3528d352008-11-21 07:05:48 +00007693 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007694
David Blaikie4e4d0842012-03-11 07:00:24 +00007695 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007696 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007697 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007698 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007699 return QualType();
7700 }
7701 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007702 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007703 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007704 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007705 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007706 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007707 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007708 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007709
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007710 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007711 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007712 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007713 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007714 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007715 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007716 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007717 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007718 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007719 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007720 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007721 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007722 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007723 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007724 } else {
John McCall09431682010-11-18 19:01:18 +00007725 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007726 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007727 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007728 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007729 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007730 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007731 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007732 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007733 // In C++, a prefix increment is the same type as the operand. Otherwise
7734 // (in C or with postfix), the increment is the unqualified type of the
7735 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007736 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007737 VK = VK_LValue;
7738 return ResType;
7739 } else {
7740 VK = VK_RValue;
7741 return ResType.getUnqualifiedType();
7742 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007743}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007744
7745
Anders Carlsson369dee42008-02-01 07:15:58 +00007746/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007747/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007748/// where the declaration is needed for type checking. We only need to
7749/// handle cases when the expression references a function designator
7750/// or is an lvalue. Here are some examples:
7751/// - &(x) => x
7752/// - &*****f => f for f a function designator.
7753/// - &s.xx => s
7754/// - &s.zz[1].yy -> s, if zz is an array
7755/// - *(x + 1) -> x, if x is an array
7756/// - &"123"[2] -> 0
7757/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007758static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007759 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007760 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007761 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007762 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007763 // If this is an arrow operator, the address is an offset from
7764 // the base's value, so the object the base refers to is
7765 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007766 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007767 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007768 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007769 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007770 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007771 // FIXME: This code shouldn't be necessary! We should catch the implicit
7772 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007773 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7774 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7775 if (ICE->getSubExpr()->getType()->isArrayType())
7776 return getPrimaryDecl(ICE->getSubExpr());
7777 }
7778 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007779 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007780 case Stmt::UnaryOperatorClass: {
7781 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007782
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007783 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007784 case UO_Real:
7785 case UO_Imag:
7786 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007787 return getPrimaryDecl(UO->getSubExpr());
7788 default:
7789 return 0;
7790 }
7791 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007792 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007793 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007794 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007795 // If the result of an implicit cast is an l-value, we care about
7796 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007797 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007798 default:
7799 return 0;
7800 }
7801}
7802
Richard Trieu5520f232011-09-07 21:46:33 +00007803namespace {
7804 enum {
7805 AO_Bit_Field = 0,
7806 AO_Vector_Element = 1,
7807 AO_Property_Expansion = 2,
7808 AO_Register_Variable = 3,
7809 AO_No_Error = 4
7810 };
7811}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007812/// \brief Diagnose invalid operand for address of operations.
7813///
7814/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007815static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7816 Expr *E, unsigned Type) {
7817 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7818}
7819
Reid Spencer5f016e22007-07-11 17:01:13 +00007820/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007821/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007822/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007823/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007824/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007825/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007826/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007827static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007828 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007829 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7830 if (PTy->getKind() == BuiltinType::Overload) {
7831 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7832 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7833 << OrigOp.get()->getSourceRange();
7834 return QualType();
7835 }
7836
7837 return S.Context.OverloadTy;
7838 }
7839
7840 if (PTy->getKind() == BuiltinType::UnknownAny)
7841 return S.Context.UnknownAnyTy;
7842
7843 if (PTy->getKind() == BuiltinType::BoundMember) {
7844 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7845 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007846 return QualType();
7847 }
John McCall3c3b7f92011-10-25 17:37:35 +00007848
7849 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7850 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007851 }
John McCall9c72c602010-08-27 09:08:28 +00007852
John McCall3c3b7f92011-10-25 17:37:35 +00007853 if (OrigOp.get()->isTypeDependent())
7854 return S.Context.DependentTy;
7855
7856 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007857
John McCall9c72c602010-08-27 09:08:28 +00007858 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007859 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007860
David Blaikie4e4d0842012-03-11 07:00:24 +00007861 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007862 // Implement C99-only parts of addressof rules.
7863 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007864 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007865 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7866 // (assuming the deref expression is valid).
7867 return uOp->getSubExpr()->getType();
7868 }
7869 // Technically, there should be a check for array subscript
7870 // expressions here, but the result of one is always an lvalue anyway.
7871 }
John McCall5808ce42011-02-03 08:15:49 +00007872 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007873 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007874 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007875
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007876 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007877 bool sfinae = S.isSFINAEContext();
7878 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7879 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007880 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007881 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007882 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007883 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007884 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007885 } else if (lval == Expr::LV_MemberFunction) {
7886 // If it's an instance method, make a member pointer.
7887 // The expression must have exactly the form &A::foo.
7888
7889 // If the underlying expression isn't a decl ref, give up.
7890 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007891 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007892 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007893 return QualType();
7894 }
7895 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7896 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7897
7898 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007899 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007900 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007901 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007902
7903 // The method was named without a qualifier.
7904 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007905 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007906 << op->getSourceRange();
7907 }
7908
John McCall09431682010-11-18 19:01:18 +00007909 return S.Context.getMemberPointerType(op->getType(),
7910 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007911 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007912 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007913 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007914 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007915 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007916 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007917 AddressOfError = AO_Property_Expansion;
7918 } else {
7919 // FIXME: emit more specific diag...
7920 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7921 << op->getSourceRange();
7922 return QualType();
7923 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007924 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007925 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007926 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007927 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007928 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007929 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007930 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007931 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007932 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007933 // with the register storage-class specifier.
7934 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007935 // in C++ it is not error to take address of a register
7936 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007937 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007938 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007939 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007940 }
John McCallba135432009-11-21 08:51:07 +00007941 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007942 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007943 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007944 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007945 // Could be a pointer to member, though, if there is an explicit
7946 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007947 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007948 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007949 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007950 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007951 S.Diag(OpLoc,
7952 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007953 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007954 return QualType();
7955 }
Mike Stump1eb44332009-09-09 15:08:12 +00007956
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007957 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7958 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007959 return S.Context.getMemberPointerType(op->getType(),
7960 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007961 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007962 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007963 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007964 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007965 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007966
Richard Trieu5520f232011-09-07 21:46:33 +00007967 if (AddressOfError != AO_No_Error) {
7968 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7969 return QualType();
7970 }
7971
Eli Friedman441cf102009-05-16 23:27:50 +00007972 if (lval == Expr::LV_IncompleteVoidType) {
7973 // Taking the address of a void variable is technically illegal, but we
7974 // allow it in cases which are otherwise valid.
7975 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007976 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007977 }
7978
Reid Spencer5f016e22007-07-11 17:01:13 +00007979 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007980 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007981 return S.Context.getObjCObjectPointerType(op->getType());
7982 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007983}
7984
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007985/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007986static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7987 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007988 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007989 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007990
John Wiegley429bb272011-04-08 18:41:53 +00007991 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7992 if (ConvResult.isInvalid())
7993 return QualType();
7994 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007995 QualType OpTy = Op->getType();
7996 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007997
7998 if (isa<CXXReinterpretCastExpr>(Op)) {
7999 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8000 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8001 Op->getSourceRange());
8002 }
8003
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008004 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8005 // is an incomplete type or void. It would be possible to warn about
8006 // dereferencing a void pointer, but it's completely well-defined, and such a
8007 // warning is unlikely to catch any mistakes.
8008 if (const PointerType *PT = OpTy->getAs<PointerType>())
8009 Result = PT->getPointeeType();
8010 else if (const ObjCObjectPointerType *OPT =
8011 OpTy->getAs<ObjCObjectPointerType>())
8012 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008013 else {
John McCallfb8721c2011-04-10 19:13:55 +00008014 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008015 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008016 if (PR.take() != Op)
8017 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008018 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008019
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008020 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008021 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008022 << OpTy << Op->getSourceRange();
8023 return QualType();
8024 }
John McCall09431682010-11-18 19:01:18 +00008025
8026 // Dereferences are usually l-values...
8027 VK = VK_LValue;
8028
8029 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008030 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008031 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008032
8033 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008034}
8035
John McCall2de56d12010-08-25 11:45:40 +00008036static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008037 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008038 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008039 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008040 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008041 case tok::periodstar: Opc = BO_PtrMemD; break;
8042 case tok::arrowstar: Opc = BO_PtrMemI; break;
8043 case tok::star: Opc = BO_Mul; break;
8044 case tok::slash: Opc = BO_Div; break;
8045 case tok::percent: Opc = BO_Rem; break;
8046 case tok::plus: Opc = BO_Add; break;
8047 case tok::minus: Opc = BO_Sub; break;
8048 case tok::lessless: Opc = BO_Shl; break;
8049 case tok::greatergreater: Opc = BO_Shr; break;
8050 case tok::lessequal: Opc = BO_LE; break;
8051 case tok::less: Opc = BO_LT; break;
8052 case tok::greaterequal: Opc = BO_GE; break;
8053 case tok::greater: Opc = BO_GT; break;
8054 case tok::exclaimequal: Opc = BO_NE; break;
8055 case tok::equalequal: Opc = BO_EQ; break;
8056 case tok::amp: Opc = BO_And; break;
8057 case tok::caret: Opc = BO_Xor; break;
8058 case tok::pipe: Opc = BO_Or; break;
8059 case tok::ampamp: Opc = BO_LAnd; break;
8060 case tok::pipepipe: Opc = BO_LOr; break;
8061 case tok::equal: Opc = BO_Assign; break;
8062 case tok::starequal: Opc = BO_MulAssign; break;
8063 case tok::slashequal: Opc = BO_DivAssign; break;
8064 case tok::percentequal: Opc = BO_RemAssign; break;
8065 case tok::plusequal: Opc = BO_AddAssign; break;
8066 case tok::minusequal: Opc = BO_SubAssign; break;
8067 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8068 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8069 case tok::ampequal: Opc = BO_AndAssign; break;
8070 case tok::caretequal: Opc = BO_XorAssign; break;
8071 case tok::pipeequal: Opc = BO_OrAssign; break;
8072 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008073 }
8074 return Opc;
8075}
8076
John McCall2de56d12010-08-25 11:45:40 +00008077static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008078 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008079 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008080 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008081 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008082 case tok::plusplus: Opc = UO_PreInc; break;
8083 case tok::minusminus: Opc = UO_PreDec; break;
8084 case tok::amp: Opc = UO_AddrOf; break;
8085 case tok::star: Opc = UO_Deref; break;
8086 case tok::plus: Opc = UO_Plus; break;
8087 case tok::minus: Opc = UO_Minus; break;
8088 case tok::tilde: Opc = UO_Not; break;
8089 case tok::exclaim: Opc = UO_LNot; break;
8090 case tok::kw___real: Opc = UO_Real; break;
8091 case tok::kw___imag: Opc = UO_Imag; break;
8092 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008093 }
8094 return Opc;
8095}
8096
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008097/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8098/// This warning is only emitted for builtin assignment operations. It is also
8099/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008100static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008101 SourceLocation OpLoc) {
8102 if (!S.ActiveTemplateInstantiations.empty())
8103 return;
8104 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8105 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008106 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8107 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8108 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8109 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8110 if (!LHSDeclRef || !RHSDeclRef ||
8111 LHSDeclRef->getLocation().isMacroID() ||
8112 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008113 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008114 const ValueDecl *LHSDecl =
8115 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8116 const ValueDecl *RHSDecl =
8117 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8118 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008119 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008120 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008121 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008122 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008123 if (RefTy->getPointeeType().isVolatileQualified())
8124 return;
8125
8126 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008127 << LHSDeclRef->getType()
8128 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008129}
8130
Douglas Gregoreaebc752008-11-06 23:29:22 +00008131/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8132/// operator @p Opc at location @c TokLoc. This routine only supports
8133/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008134ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008135 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008136 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008137 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008138 // The syntax only allows initializer lists on the RHS of assignment,
8139 // so we don't need to worry about accepting invalid code for
8140 // non-assignment operators.
8141 // C++11 5.17p9:
8142 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8143 // of x = {} is x = T().
8144 InitializationKind Kind =
8145 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8146 InitializedEntity Entity =
8147 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8148 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8149 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8150 MultiExprArg(&RHSExpr, 1));
8151 if (Init.isInvalid())
8152 return Init;
8153 RHSExpr = Init.take();
8154 }
8155
Richard Trieu78ea78b2011-09-07 01:49:20 +00008156 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008157 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008158 // The following two variables are used for compound assignment operators
8159 QualType CompLHSTy; // Type of LHS after promotions for computation
8160 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008161 ExprValueKind VK = VK_RValue;
8162 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008163
8164 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008165 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008166 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008167 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008168 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8169 VK = LHS.get()->getValueKind();
8170 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008171 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008172 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008173 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008174 break;
John McCall2de56d12010-08-25 11:45:40 +00008175 case BO_PtrMemD:
8176 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008177 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008178 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008179 break;
John McCall2de56d12010-08-25 11:45:40 +00008180 case BO_Mul:
8181 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008182 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008183 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008184 break;
John McCall2de56d12010-08-25 11:45:40 +00008185 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008186 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008187 break;
John McCall2de56d12010-08-25 11:45:40 +00008188 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008189 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008190 break;
John McCall2de56d12010-08-25 11:45:40 +00008191 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008192 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008193 break;
John McCall2de56d12010-08-25 11:45:40 +00008194 case BO_Shl:
8195 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008196 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008197 break;
John McCall2de56d12010-08-25 11:45:40 +00008198 case BO_LE:
8199 case BO_LT:
8200 case BO_GE:
8201 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008202 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008203 break;
John McCall2de56d12010-08-25 11:45:40 +00008204 case BO_EQ:
8205 case BO_NE:
Jordan Rose9f63a452012-06-08 21:14:25 +00008206 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8207 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8208 LHS, RHS, Opc);
8209 if (IsEqualCall.isUsable())
8210 return IsEqualCall;
8211 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8212 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008213 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008214 break;
John McCall2de56d12010-08-25 11:45:40 +00008215 case BO_And:
8216 case BO_Xor:
8217 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008218 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008219 break;
John McCall2de56d12010-08-25 11:45:40 +00008220 case BO_LAnd:
8221 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008222 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008223 break;
John McCall2de56d12010-08-25 11:45:40 +00008224 case BO_MulAssign:
8225 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008226 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008227 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008228 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008229 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8230 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008231 break;
John McCall2de56d12010-08-25 11:45:40 +00008232 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008233 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008234 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008235 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8236 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008237 break;
John McCall2de56d12010-08-25 11:45:40 +00008238 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008239 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008240 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8241 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008242 break;
John McCall2de56d12010-08-25 11:45:40 +00008243 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008244 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8245 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8246 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008247 break;
John McCall2de56d12010-08-25 11:45:40 +00008248 case BO_ShlAssign:
8249 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008250 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008251 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008252 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8253 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008254 break;
John McCall2de56d12010-08-25 11:45:40 +00008255 case BO_AndAssign:
8256 case BO_XorAssign:
8257 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008258 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008259 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008260 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8261 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008262 break;
John McCall2de56d12010-08-25 11:45:40 +00008263 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008264 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008265 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008266 VK = RHS.get()->getValueKind();
8267 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008268 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008269 break;
8270 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008271 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008272 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008273
8274 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008275 CheckArrayAccess(LHS.get());
8276 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008277
Eli Friedmanab3a8522009-03-28 01:22:36 +00008278 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008279 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008280 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008281 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008282 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008283 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008284 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008285 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008286 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008287 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008288 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008289}
8290
Sebastian Redlaee3c932009-10-27 12:10:02 +00008291/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8292/// operators are mixed in a way that suggests that the programmer forgot that
8293/// comparison operators have higher precedence. The most typical example of
8294/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008295static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008296 SourceLocation OpLoc, Expr *LHSExpr,
8297 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008298 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008299 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8300 RHSopc = static_cast<BinOp::Opcode>(-1);
8301 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8302 LHSopc = BO->getOpcode();
8303 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8304 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008305
8306 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008307 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008308 return;
8309
8310 // Bitwise operations are sometimes used as eager logical ops.
8311 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008312 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8313 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008314 return;
8315
Richard Trieu78ea78b2011-09-07 01:49:20 +00008316 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8317 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008318 if (!isLeftComp && !isRightComp) return;
8319
Richard Trieu78ea78b2011-09-07 01:49:20 +00008320 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8321 OpLoc)
8322 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8323 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8324 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008325 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008326 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8327 RHSExpr->getLocEnd())
8328 : SourceRange(LHSExpr->getLocStart(),
8329 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008330
8331 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8332 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8333 SuggestParentheses(Self, OpLoc,
8334 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008335 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008336 SuggestParentheses(Self, OpLoc,
8337 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8338 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008339}
8340
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008341/// \brief It accepts a '&' expr that is inside a '|' one.
8342/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8343/// in parentheses.
8344static void
8345EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8346 BinaryOperator *Bop) {
8347 assert(Bop->getOpcode() == BO_And);
8348 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8349 << Bop->getSourceRange() << OpLoc;
8350 SuggestParentheses(Self, Bop->getOperatorLoc(),
8351 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8352 Bop->getSourceRange());
8353}
8354
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008355/// \brief It accepts a '&&' expr that is inside a '||' one.
8356/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8357/// in parentheses.
8358static void
8359EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008360 BinaryOperator *Bop) {
8361 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008362 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8363 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008364 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008365 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008366 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008367}
8368
8369/// \brief Returns true if the given expression can be evaluated as a constant
8370/// 'true'.
8371static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8372 bool Res;
8373 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8374}
8375
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008376/// \brief Returns true if the given expression can be evaluated as a constant
8377/// 'false'.
8378static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8379 bool Res;
8380 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8381}
8382
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008383/// \brief Look for '&&' in the left hand of a '||' expr.
8384static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008385 Expr *LHSExpr, Expr *RHSExpr) {
8386 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008387 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008388 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008389 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008390 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008391 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8392 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8393 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8394 } else if (Bop->getOpcode() == BO_LOr) {
8395 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8396 // If it's "a || b && 1 || c" we didn't warn earlier for
8397 // "a || b && 1", but warn now.
8398 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8399 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8400 }
8401 }
8402 }
8403}
8404
8405/// \brief Look for '&&' in the right hand of a '||' expr.
8406static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008407 Expr *LHSExpr, Expr *RHSExpr) {
8408 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008409 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008410 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008411 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008412 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008413 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8414 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8415 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008416 }
8417 }
8418}
8419
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008420/// \brief Look for '&' in the left or right hand of a '|' expr.
8421static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8422 Expr *OrArg) {
8423 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8424 if (Bop->getOpcode() == BO_And)
8425 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8426 }
8427}
8428
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008429/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008430/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008431static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008432 SourceLocation OpLoc, Expr *LHSExpr,
8433 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008434 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008435 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008436 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008437
8438 // Diagnose "arg1 & arg2 | arg3"
8439 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008440 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8441 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008442 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008443
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008444 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8445 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008446 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008447 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8448 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008449 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008450}
8451
Reid Spencer5f016e22007-07-11 17:01:13 +00008452// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008453ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008454 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008455 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008456 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008457 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8458 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008459
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008460 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008461 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008462
Richard Trieubefece12011-09-07 02:02:10 +00008463 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008464}
8465
John McCall3c3b7f92011-10-25 17:37:35 +00008466/// Build an overloaded binary operator expression in the given scope.
8467static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8468 BinaryOperatorKind Opc,
8469 Expr *LHS, Expr *RHS) {
8470 // Find all of the overloaded operators visible from this
8471 // point. We perform both an operator-name lookup from the local
8472 // scope and an argument-dependent lookup based on the types of
8473 // the arguments.
8474 UnresolvedSet<16> Functions;
8475 OverloadedOperatorKind OverOp
8476 = BinaryOperator::getOverloadedOperator(Opc);
8477 if (Sc && OverOp != OO_None)
8478 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8479 RHS->getType(), Functions);
8480
8481 // Build the (potentially-overloaded, potentially-dependent)
8482 // binary operation.
8483 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8484}
8485
John McCall60d7b3a2010-08-24 06:29:42 +00008486ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008487 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008488 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008489 // We want to end up calling one of checkPseudoObjectAssignment
8490 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8491 // both expressions are overloadable or either is type-dependent),
8492 // or CreateBuiltinBinOp (in any other case). We also want to get
8493 // any placeholder types out of the way.
8494
John McCall3c3b7f92011-10-25 17:37:35 +00008495 // Handle pseudo-objects in the LHS.
8496 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8497 // Assignments with a pseudo-object l-value need special analysis.
8498 if (pty->getKind() == BuiltinType::PseudoObject &&
8499 BinaryOperator::isAssignmentOp(Opc))
8500 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8501
8502 // Don't resolve overloads if the other type is overloadable.
8503 if (pty->getKind() == BuiltinType::Overload) {
8504 // We can't actually test that if we still have a placeholder,
8505 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008506 // code below are valid when the LHS is an overload set. Note
8507 // that an overload set can be dependently-typed, but it never
8508 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008509 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8510 if (resolvedRHS.isInvalid()) return ExprError();
8511 RHSExpr = resolvedRHS.take();
8512
John McCallac516502011-10-28 01:04:34 +00008513 if (RHSExpr->isTypeDependent() ||
8514 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008515 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8516 }
8517
8518 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8519 if (LHS.isInvalid()) return ExprError();
8520 LHSExpr = LHS.take();
8521 }
8522
8523 // Handle pseudo-objects in the RHS.
8524 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8525 // An overload in the RHS can potentially be resolved by the type
8526 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008527 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8528 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8529 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8530
Eli Friedman87884912012-01-17 21:27:43 +00008531 if (LHSExpr->getType()->isOverloadableType())
8532 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8533
John McCall3c3b7f92011-10-25 17:37:35 +00008534 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008535 }
John McCall3c3b7f92011-10-25 17:37:35 +00008536
8537 // Don't resolve overloads if the other type is overloadable.
8538 if (pty->getKind() == BuiltinType::Overload &&
8539 LHSExpr->getType()->isOverloadableType())
8540 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8541
8542 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8543 if (!resolvedRHS.isUsable()) return ExprError();
8544 RHSExpr = resolvedRHS.take();
8545 }
8546
David Blaikie4e4d0842012-03-11 07:00:24 +00008547 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008548 // If either expression is type-dependent, always build an
8549 // overloaded op.
8550 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8551 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008552
John McCallac516502011-10-28 01:04:34 +00008553 // Otherwise, build an overloaded op if either expression has an
8554 // overloadable type.
8555 if (LHSExpr->getType()->isOverloadableType() ||
8556 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008557 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008558 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008559
Douglas Gregoreaebc752008-11-06 23:29:22 +00008560 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008561 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008562}
8563
John McCall60d7b3a2010-08-24 06:29:42 +00008564ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008565 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008566 Expr *InputExpr) {
8567 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008568 ExprValueKind VK = VK_RValue;
8569 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008570 QualType resultType;
8571 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008572 case UO_PreInc:
8573 case UO_PreDec:
8574 case UO_PostInc:
8575 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008576 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008577 Opc == UO_PreInc ||
8578 Opc == UO_PostInc,
8579 Opc == UO_PreInc ||
8580 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008581 break;
John McCall2de56d12010-08-25 11:45:40 +00008582 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008583 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008584 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008585 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008586 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8587 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008588 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008589 }
John McCall2de56d12010-08-25 11:45:40 +00008590 case UO_Plus:
8591 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008592 Input = UsualUnaryConversions(Input.take());
8593 if (Input.isInvalid()) return ExprError();
8594 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008595 if (resultType->isDependentType())
8596 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008597 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8598 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008599 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008600 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008601 resultType->isEnumeralType())
8602 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008603 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008604 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008605 resultType->isPointerType())
8606 break;
8607
Sebastian Redl0eb23302009-01-19 00:08:26 +00008608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008609 << resultType << Input.get()->getSourceRange());
8610
John McCall2de56d12010-08-25 11:45:40 +00008611 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008612 Input = UsualUnaryConversions(Input.take());
8613 if (Input.isInvalid()) return ExprError();
8614 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008615 if (resultType->isDependentType())
8616 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008617 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8618 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8619 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008620 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008621 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008622 else if (resultType->hasIntegerRepresentation())
8623 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008624 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008625 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008626 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008627 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008628 break;
John Wiegley429bb272011-04-08 18:41:53 +00008629
John McCall2de56d12010-08-25 11:45:40 +00008630 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008631 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008632 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8633 if (Input.isInvalid()) return ExprError();
8634 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008635
8636 // Though we still have to promote half FP to float...
8637 if (resultType->isHalfType()) {
8638 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8639 resultType = Context.FloatTy;
8640 }
8641
Sebastian Redl28507842009-02-26 14:39:58 +00008642 if (resultType->isDependentType())
8643 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008644 if (resultType->isScalarType()) {
8645 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008646 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008647 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8648 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008649 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8650 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008651 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008652 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008653 // Vector logical not returns the signed variant of the operand type.
8654 resultType = GetSignedVectorType(resultType);
8655 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008656 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008658 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008659 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008660
Reid Spencer5f016e22007-07-11 17:01:13 +00008661 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008662 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008663 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008664 break;
John McCall2de56d12010-08-25 11:45:40 +00008665 case UO_Real:
8666 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008667 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008668 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8669 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008670 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008671 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8672 if (Input.get()->getValueKind() != VK_RValue &&
8673 Input.get()->getObjectKind() == OK_Ordinary)
8674 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008675 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008676 // In C, a volatile scalar is read by __imag. In C++, it is not.
8677 Input = DefaultLvalueConversion(Input.take());
8678 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008679 break;
John McCall2de56d12010-08-25 11:45:40 +00008680 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008681 resultType = Input.get()->getType();
8682 VK = Input.get()->getValueKind();
8683 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008684 break;
8685 }
John Wiegley429bb272011-04-08 18:41:53 +00008686 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008687 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008688
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008689 // Check for array bounds violations in the operand of the UnaryOperator,
8690 // except for the '*' and '&' operators that have to be handled specially
8691 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8692 // that are explicitly defined as valid by the standard).
8693 if (Opc != UO_AddrOf && Opc != UO_Deref)
8694 CheckArrayAccess(Input.get());
8695
John Wiegley429bb272011-04-08 18:41:53 +00008696 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008697 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008698}
8699
Douglas Gregord3d08532011-12-14 21:23:13 +00008700/// \brief Determine whether the given expression is a qualified member
8701/// access expression, of a form that could be turned into a pointer to member
8702/// with the address-of operator.
8703static bool isQualifiedMemberAccess(Expr *E) {
8704 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8705 if (!DRE->getQualifier())
8706 return false;
8707
8708 ValueDecl *VD = DRE->getDecl();
8709 if (!VD->isCXXClassMember())
8710 return false;
8711
8712 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8713 return true;
8714 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8715 return Method->isInstance();
8716
8717 return false;
8718 }
8719
8720 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8721 if (!ULE->getQualifier())
8722 return false;
8723
8724 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8725 DEnd = ULE->decls_end();
8726 D != DEnd; ++D) {
8727 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8728 if (Method->isInstance())
8729 return true;
8730 } else {
8731 // Overload set does not contain methods.
8732 break;
8733 }
8734 }
8735
8736 return false;
8737 }
8738
8739 return false;
8740}
8741
John McCall60d7b3a2010-08-24 06:29:42 +00008742ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008743 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008744 // First things first: handle placeholders so that the
8745 // overloaded-operator check considers the right type.
8746 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8747 // Increment and decrement of pseudo-object references.
8748 if (pty->getKind() == BuiltinType::PseudoObject &&
8749 UnaryOperator::isIncrementDecrementOp(Opc))
8750 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8751
8752 // extension is always a builtin operator.
8753 if (Opc == UO_Extension)
8754 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8755
8756 // & gets special logic for several kinds of placeholder.
8757 // The builtin code knows what to do.
8758 if (Opc == UO_AddrOf &&
8759 (pty->getKind() == BuiltinType::Overload ||
8760 pty->getKind() == BuiltinType::UnknownAny ||
8761 pty->getKind() == BuiltinType::BoundMember))
8762 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8763
8764 // Anything else needs to be handled now.
8765 ExprResult Result = CheckPlaceholderExpr(Input);
8766 if (Result.isInvalid()) return ExprError();
8767 Input = Result.take();
8768 }
8769
David Blaikie4e4d0842012-03-11 07:00:24 +00008770 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008771 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8772 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008773 // Find all of the overloaded operators visible from this
8774 // point. We perform both an operator-name lookup from the local
8775 // scope and an argument-dependent lookup based on the types of
8776 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008777 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008778 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008779 if (S && OverOp != OO_None)
8780 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8781 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008782
John McCall9ae2f072010-08-23 23:25:46 +00008783 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008784 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008785
John McCall9ae2f072010-08-23 23:25:46 +00008786 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008787}
8788
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008789// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008790ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008791 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008792 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008793}
8794
Steve Naroff1b273c42007-09-16 14:56:35 +00008795/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008796ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008797 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008798 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008799 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008800 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008801 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008802}
8803
John McCallf85e1932011-06-15 23:02:42 +00008804/// Given the last statement in a statement-expression, check whether
8805/// the result is a producing expression (like a call to an
8806/// ns_returns_retained function) and, if so, rebuild it to hoist the
8807/// release out of the full-expression. Otherwise, return null.
8808/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008809static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008810 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008811 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008812 if (!cleanups) return 0;
8813
8814 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008815 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008816 return 0;
8817
8818 // Splice out the cast. This shouldn't modify any interesting
8819 // features of the statement.
8820 Expr *producer = cast->getSubExpr();
8821 assert(producer->getType() == cast->getType());
8822 assert(producer->getValueKind() == cast->getValueKind());
8823 cleanups->setSubExpr(producer);
8824 return cleanups;
8825}
8826
John McCall73f428c2012-04-04 01:27:53 +00008827void Sema::ActOnStartStmtExpr() {
8828 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8829}
8830
8831void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008832 // Note that function is also called by TreeTransform when leaving a
8833 // StmtExpr scope without rebuilding anything.
8834
John McCall73f428c2012-04-04 01:27:53 +00008835 DiscardCleanupsInEvaluationContext();
8836 PopExpressionEvaluationContext();
8837}
8838
John McCall60d7b3a2010-08-24 06:29:42 +00008839ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008840Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008841 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008842 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8843 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8844
John McCall73f428c2012-04-04 01:27:53 +00008845 if (hasAnyUnrecoverableErrorsInThisFunction())
8846 DiscardCleanupsInEvaluationContext();
8847 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8848 PopExpressionEvaluationContext();
8849
Douglas Gregordd8f5692010-03-10 04:54:39 +00008850 bool isFileScope
8851 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008852 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008853 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008854
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008855 // FIXME: there are a variety of strange constraints to enforce here, for
8856 // example, it is not possible to goto into a stmt expression apparently.
8857 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008858
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008859 // If there are sub stmts in the compound stmt, take the type of the last one
8860 // as the type of the stmtexpr.
8861 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008862 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008863 if (!Compound->body_empty()) {
8864 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008865 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008866 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008867 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8868 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008869 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008870 }
John McCallf85e1932011-06-15 23:02:42 +00008871
John Wiegley429bb272011-04-08 18:41:53 +00008872 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008873 // Do function/array conversion on the last expression, but not
8874 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008875 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8876 if (LastExpr.isInvalid())
8877 return ExprError();
8878 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008879
John Wiegley429bb272011-04-08 18:41:53 +00008880 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008881 // In ARC, if the final expression ends in a consume, splice
8882 // the consume out and bind it later. In the alternate case
8883 // (when dealing with a retainable type), the result
8884 // initialization will create a produce. In both cases the
8885 // result will be +1, and we'll need to balance that out with
8886 // a bind.
8887 if (Expr *rebuiltLastStmt
8888 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8889 LastExpr = rebuiltLastStmt;
8890 } else {
8891 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008892 InitializedEntity::InitializeResult(LPLoc,
8893 Ty,
8894 false),
8895 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008896 LastExpr);
8897 }
8898
John Wiegley429bb272011-04-08 18:41:53 +00008899 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008900 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008901 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008902 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008903 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008904 else
John Wiegley429bb272011-04-08 18:41:53 +00008905 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008906 StmtExprMayBindToTemp = true;
8907 }
8908 }
8909 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008910 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008911
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008912 // FIXME: Check that expression type is complete/non-abstract; statement
8913 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008914 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8915 if (StmtExprMayBindToTemp)
8916 return MaybeBindToTemporary(ResStmtExpr);
8917 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008918}
Steve Naroffd34e9152007-08-01 22:05:33 +00008919
John McCall60d7b3a2010-08-24 06:29:42 +00008920ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008921 TypeSourceInfo *TInfo,
8922 OffsetOfComponent *CompPtr,
8923 unsigned NumComponents,
8924 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008925 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008926 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008927 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008928
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008929 // We must have at least one component that refers to the type, and the first
8930 // one is known to be a field designator. Verify that the ArgTy represents
8931 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008932 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008933 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8934 << ArgTy << TypeRange);
8935
8936 // Type must be complete per C99 7.17p3 because a declaring a variable
8937 // with an incomplete type would be ill-formed.
8938 if (!Dependent
8939 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00008940 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008941 return ExprError();
8942
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008943 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8944 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008945 // FIXME: This diagnostic isn't actually visible because the location is in
8946 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008947 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008948 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8949 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008950
8951 bool DidWarnAboutNonPOD = false;
8952 QualType CurrentType = ArgTy;
8953 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008954 SmallVector<OffsetOfNode, 4> Comps;
8955 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008956 for (unsigned i = 0; i != NumComponents; ++i) {
8957 const OffsetOfComponent &OC = CompPtr[i];
8958 if (OC.isBrackets) {
8959 // Offset of an array sub-field. TODO: Should we allow vector elements?
8960 if (!CurrentType->isDependentType()) {
8961 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8962 if(!AT)
8963 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8964 << CurrentType);
8965 CurrentType = AT->getElementType();
8966 } else
8967 CurrentType = Context.DependentTy;
8968
Richard Smithea011432011-10-17 23:29:39 +00008969 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8970 if (IdxRval.isInvalid())
8971 return ExprError();
8972 Expr *Idx = IdxRval.take();
8973
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008974 // The expression must be an integral expression.
8975 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008976 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8977 !Idx->getType()->isIntegerType())
8978 return ExprError(Diag(Idx->getLocStart(),
8979 diag::err_typecheck_subscript_not_integer)
8980 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00008981
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008982 // Record this array index.
8983 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00008984 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008985 continue;
8986 }
8987
8988 // Offset of a field.
8989 if (CurrentType->isDependentType()) {
8990 // We have the offset of a field, but we can't look into the dependent
8991 // type. Just record the identifier of the field.
8992 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8993 CurrentType = Context.DependentTy;
8994 continue;
8995 }
8996
8997 // We need to have a complete type to look into.
8998 if (RequireCompleteType(OC.LocStart, CurrentType,
8999 diag::err_offsetof_incomplete_type))
9000 return ExprError();
9001
9002 // Look for the designated field.
9003 const RecordType *RC = CurrentType->getAs<RecordType>();
9004 if (!RC)
9005 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9006 << CurrentType);
9007 RecordDecl *RD = RC->getDecl();
9008
9009 // C++ [lib.support.types]p5:
9010 // The macro offsetof accepts a restricted set of type arguments in this
9011 // International Standard. type shall be a POD structure or a POD union
9012 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009013 // C++11 [support.types]p4:
9014 // If type is not a standard-layout class (Clause 9), the results are
9015 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009016 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009017 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9018 unsigned DiagID =
9019 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9020 : diag::warn_offsetof_non_pod_type;
9021
9022 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009023 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009024 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009025 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9026 << CurrentType))
9027 DidWarnAboutNonPOD = true;
9028 }
9029
9030 // Look for the field.
9031 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9032 LookupQualifiedName(R, RD);
9033 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009034 IndirectFieldDecl *IndirectMemberDecl = 0;
9035 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009036 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009037 MemberDecl = IndirectMemberDecl->getAnonField();
9038 }
9039
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009040 if (!MemberDecl)
9041 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9042 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9043 OC.LocEnd));
9044
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009045 // C99 7.17p3:
9046 // (If the specified member is a bit-field, the behavior is undefined.)
9047 //
9048 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009049 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009050 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9051 << MemberDecl->getDeclName()
9052 << SourceRange(BuiltinLoc, RParenLoc);
9053 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9054 return ExprError();
9055 }
Eli Friedman19410a72010-08-05 10:11:36 +00009056
9057 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009058 if (IndirectMemberDecl)
9059 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009060
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009061 // If the member was found in a base class, introduce OffsetOfNodes for
9062 // the base class indirections.
9063 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9064 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009065 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009066 CXXBasePath &Path = Paths.front();
9067 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9068 B != BEnd; ++B)
9069 Comps.push_back(OffsetOfNode(B->Base));
9070 }
Eli Friedman19410a72010-08-05 10:11:36 +00009071
Francois Pichet87c2e122010-11-21 06:08:52 +00009072 if (IndirectMemberDecl) {
9073 for (IndirectFieldDecl::chain_iterator FI =
9074 IndirectMemberDecl->chain_begin(),
9075 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9076 assert(isa<FieldDecl>(*FI));
9077 Comps.push_back(OffsetOfNode(OC.LocStart,
9078 cast<FieldDecl>(*FI), OC.LocEnd));
9079 }
9080 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009081 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009082
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009083 CurrentType = MemberDecl->getType().getNonReferenceType();
9084 }
9085
9086 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9087 TInfo, Comps.data(), Comps.size(),
9088 Exprs.data(), Exprs.size(), RParenLoc));
9089}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009090
John McCall60d7b3a2010-08-24 06:29:42 +00009091ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009092 SourceLocation BuiltinLoc,
9093 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009094 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009095 OffsetOfComponent *CompPtr,
9096 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009097 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009098
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009099 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009100 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009101 if (ArgTy.isNull())
9102 return ExprError();
9103
Eli Friedman5a15dc12010-08-05 10:15:45 +00009104 if (!ArgTInfo)
9105 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9106
9107 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009108 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009109}
9110
9111
John McCall60d7b3a2010-08-24 06:29:42 +00009112ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009113 Expr *CondExpr,
9114 Expr *LHSExpr, Expr *RHSExpr,
9115 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009116 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9117
John McCallf89e55a2010-11-18 06:31:45 +00009118 ExprValueKind VK = VK_RValue;
9119 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009120 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009121 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009122 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009123 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009124 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009125 } else {
9126 // The conditional expression is required to be a constant expression.
9127 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009128 ExprResult CondICE
9129 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9130 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009131 if (CondICE.isInvalid())
9132 return ExprError();
9133 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009134
Sebastian Redl28507842009-02-26 14:39:58 +00009135 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009136 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9137
9138 resType = ActiveExpr->getType();
9139 ValueDependent = ActiveExpr->isValueDependent();
9140 VK = ActiveExpr->getValueKind();
9141 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009142 }
9143
Sebastian Redlf53597f2009-03-15 17:47:39 +00009144 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009145 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009146 resType->isDependentType(),
9147 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009148}
9149
Steve Naroff4eb206b2008-09-03 18:15:37 +00009150//===----------------------------------------------------------------------===//
9151// Clang Extensions.
9152//===----------------------------------------------------------------------===//
9153
9154/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009155void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009156 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009157 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009158 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009159 if (CurScope)
9160 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009161 else
9162 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009163
Eli Friedman84b007f2012-01-26 03:00:14 +00009164 getCurBlock()->HasImplicitReturnType = true;
9165
John McCall538773c2011-11-11 03:19:12 +00009166 // Enter a new evaluation context to insulate the block from any
9167 // cleanups from the enclosing full-expression.
9168 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009169}
9170
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009171void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9172 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009173 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009174 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009175 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009176
John McCallbf1a0282010-06-04 23:28:52 +00009177 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009178 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009179
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009180 // FIXME: We should allow unexpanded parameter packs here, but that would,
9181 // in turn, make the block expression contain unexpanded parameter packs.
9182 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9183 // Drop the parameters.
9184 FunctionProtoType::ExtProtoInfo EPI;
9185 EPI.HasTrailingReturn = false;
9186 EPI.TypeQuals |= DeclSpec::TQ_const;
9187 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9188 EPI);
9189 Sig = Context.getTrivialTypeSourceInfo(T);
9190 }
9191
John McCall711c52b2011-01-05 12:14:39 +00009192 // GetTypeForDeclarator always produces a function type for a block
9193 // literal signature. Furthermore, it is always a FunctionProtoType
9194 // unless the function was written with a typedef.
9195 assert(T->isFunctionType() &&
9196 "GetTypeForDeclarator made a non-function block signature");
9197
9198 // Look for an explicit signature in that function type.
9199 FunctionProtoTypeLoc ExplicitSignature;
9200
9201 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9202 if (isa<FunctionProtoTypeLoc>(tmp)) {
9203 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9204
9205 // Check whether that explicit signature was synthesized by
9206 // GetTypeForDeclarator. If so, don't save that as part of the
9207 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009208 if (ExplicitSignature.getLocalRangeBegin() ==
9209 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009210 // This would be much cheaper if we stored TypeLocs instead of
9211 // TypeSourceInfos.
9212 TypeLoc Result = ExplicitSignature.getResultLoc();
9213 unsigned Size = Result.getFullDataSize();
9214 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9215 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9216
9217 ExplicitSignature = FunctionProtoTypeLoc();
9218 }
John McCall82dc0092010-06-04 11:21:44 +00009219 }
Mike Stump1eb44332009-09-09 15:08:12 +00009220
John McCall711c52b2011-01-05 12:14:39 +00009221 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9222 CurBlock->FunctionType = T;
9223
9224 const FunctionType *Fn = T->getAs<FunctionType>();
9225 QualType RetTy = Fn->getResultType();
9226 bool isVariadic =
9227 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9228
John McCallc71a4912010-06-04 19:02:56 +00009229 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009230
John McCall82dc0092010-06-04 11:21:44 +00009231 // Don't allow returning a objc interface by value.
9232 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009233 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009234 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9235 return;
9236 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009237
John McCall82dc0092010-06-04 11:21:44 +00009238 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009239 // return type. TODO: what should we do with declarators like:
9240 // ^ * { ... }
9241 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009242 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009243 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009244 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009245 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009246 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009247
John McCall82dc0092010-06-04 11:21:44 +00009248 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009249 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009250 if (ExplicitSignature) {
9251 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9252 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009253 if (Param->getIdentifier() == 0 &&
9254 !Param->isImplicit() &&
9255 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009256 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009257 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009258 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009259 }
John McCall82dc0092010-06-04 11:21:44 +00009260
9261 // Fake up parameter variables if we have a typedef, like
9262 // ^ fntype { ... }
9263 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9264 for (FunctionProtoType::arg_type_iterator
9265 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9266 ParmVarDecl *Param =
9267 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009268 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009269 *I);
John McCallc71a4912010-06-04 19:02:56 +00009270 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009271 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009272 }
John McCall82dc0092010-06-04 11:21:44 +00009273
John McCallc71a4912010-06-04 19:02:56 +00009274 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009275 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009276 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009277 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9278 CurBlock->TheDecl->param_end(),
9279 /*CheckParameterNames=*/false);
9280 }
9281
John McCall82dc0092010-06-04 11:21:44 +00009282 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009283 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009284
John McCall82dc0092010-06-04 11:21:44 +00009285 // Put the parameter variables in scope. We can bail out immediately
9286 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009287 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009288 return;
9289
Steve Naroff090276f2008-10-10 01:28:17 +00009290 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009291 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9292 (*AI)->setOwningFunction(CurBlock->TheDecl);
9293
Steve Naroff090276f2008-10-10 01:28:17 +00009294 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009295 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009296 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009297
Steve Naroff090276f2008-10-10 01:28:17 +00009298 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009299 }
John McCall7a9813c2010-01-22 00:28:27 +00009300 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009301}
9302
9303/// ActOnBlockError - If there is an error parsing a block, this callback
9304/// is invoked to pop the information about the block from the action impl.
9305void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009306 // Leave the expression-evaluation context.
9307 DiscardCleanupsInEvaluationContext();
9308 PopExpressionEvaluationContext();
9309
Steve Naroff4eb206b2008-09-03 18:15:37 +00009310 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009311 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009312 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009313}
9314
9315/// ActOnBlockStmtExpr - This is called when the body of a block statement
9316/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009317ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009318 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009319 // If blocks are disabled, emit an error.
9320 if (!LangOpts.Blocks)
9321 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009322
John McCall538773c2011-11-11 03:19:12 +00009323 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009324 if (hasAnyUnrecoverableErrorsInThisFunction())
9325 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009326 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9327 PopExpressionEvaluationContext();
9328
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009329 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009330
Steve Naroff090276f2008-10-10 01:28:17 +00009331 PopDeclContext();
9332
Steve Naroff4eb206b2008-09-03 18:15:37 +00009333 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009334 if (!BSI->ReturnType.isNull())
9335 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009336
Mike Stump56925862009-07-28 22:04:01 +00009337 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009338 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009339
John McCall469a1eb2011-02-02 13:00:07 +00009340 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009341 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9342 SmallVector<BlockDecl::Capture, 4> Captures;
9343 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9344 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9345 if (Cap.isThisCapture())
9346 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009347 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009348 Cap.isNested(), Cap.getCopyExpr());
9349 Captures.push_back(NewCap);
9350 }
9351 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9352 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009353
John McCallc71a4912010-06-04 19:02:56 +00009354 // If the user wrote a function type in some form, try to use that.
9355 if (!BSI->FunctionType.isNull()) {
9356 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9357
9358 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9359 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9360
9361 // Turn protoless block types into nullary block types.
9362 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009363 FunctionProtoType::ExtProtoInfo EPI;
9364 EPI.ExtInfo = Ext;
9365 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009366
9367 // Otherwise, if we don't need to change anything about the function type,
9368 // preserve its sugar structure.
9369 } else if (FTy->getResultType() == RetTy &&
9370 (!NoReturn || FTy->getNoReturnAttr())) {
9371 BlockTy = BSI->FunctionType;
9372
9373 // Otherwise, make the minimal modifications to the function type.
9374 } else {
9375 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009376 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9377 EPI.TypeQuals = 0; // FIXME: silently?
9378 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009379 BlockTy = Context.getFunctionType(RetTy,
9380 FPT->arg_type_begin(),
9381 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009382 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009383 }
9384
9385 // If we don't have a function type, just build one from nothing.
9386 } else {
John McCalle23cf432010-12-14 08:05:40 +00009387 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009388 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009389 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009390 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009391
John McCallc71a4912010-06-04 19:02:56 +00009392 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9393 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009394 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009395
Chris Lattner17a78302009-04-19 05:28:12 +00009396 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009397 if (getCurFunction()->NeedsScopeChecking() &&
9398 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009399 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009400
Chris Lattnere476bdc2011-02-17 23:58:47 +00009401 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009402
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009403 computeNRVO(Body, getCurBlock());
9404
Benjamin Kramerd2486192011-07-12 14:11:05 +00009405 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9406 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009407 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009408
John McCall80ee6e82011-11-10 05:35:25 +00009409 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009410 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009411 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009412 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009413 ExprCleanupObjects.push_back(Result->getBlockDecl());
9414 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009415
9416 // It also gets a branch-protected scope if any of the captured
9417 // variables needs destruction.
9418 for (BlockDecl::capture_const_iterator
9419 ci = Result->getBlockDecl()->capture_begin(),
9420 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9421 const VarDecl *var = ci->getVariable();
9422 if (var->getType().isDestructedType() != QualType::DK_none) {
9423 getCurFunction()->setHasBranchProtectedScope();
9424 break;
9425 }
9426 }
John McCall80ee6e82011-11-10 05:35:25 +00009427 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009428
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009429 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009430}
9431
John McCall60d7b3a2010-08-24 06:29:42 +00009432ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009433 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009434 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009435 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009436 GetTypeFromParser(Ty, &TInfo);
9437 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009438}
9439
John McCall60d7b3a2010-08-24 06:29:42 +00009440ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009441 Expr *E, TypeSourceInfo *TInfo,
9442 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009443 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009444
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009445 // Get the va_list type
9446 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009447 if (VaListType->isArrayType()) {
9448 // Deal with implicit array decay; for example, on x86-64,
9449 // va_list is an array, but it's supposed to decay to
9450 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009451 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009452 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009453 ExprResult Result = UsualUnaryConversions(E);
9454 if (Result.isInvalid())
9455 return ExprError();
9456 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009457 } else {
9458 // Otherwise, the va_list argument must be an l-value because
9459 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009460 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009461 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009462 return ExprError();
9463 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009464
Douglas Gregordd027302009-05-19 23:10:31 +00009465 if (!E->isTypeDependent() &&
9466 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009467 return ExprError(Diag(E->getLocStart(),
9468 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009469 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009470 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009471
David Majnemer0adde122011-06-14 05:17:32 +00009472 if (!TInfo->getType()->isDependentType()) {
9473 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009474 diag::err_second_parameter_to_va_arg_incomplete,
9475 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009476 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009477
David Majnemer0adde122011-06-14 05:17:32 +00009478 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009479 TInfo->getType(),
9480 diag::err_second_parameter_to_va_arg_abstract,
9481 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009482 return ExprError();
9483
Douglas Gregor4eb75222011-07-30 06:45:27 +00009484 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009485 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009486 TInfo->getType()->isObjCLifetimeType()
9487 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9488 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009489 << TInfo->getType()
9490 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009491 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009492
9493 // Check for va_arg where arguments of the given type will be promoted
9494 // (i.e. this va_arg is guaranteed to have undefined behavior).
9495 QualType PromoteType;
9496 if (TInfo->getType()->isPromotableIntegerType()) {
9497 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9498 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9499 PromoteType = QualType();
9500 }
9501 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9502 PromoteType = Context.DoubleTy;
9503 if (!PromoteType.isNull())
9504 Diag(TInfo->getTypeLoc().getBeginLoc(),
9505 diag::warn_second_parameter_to_va_arg_never_compatible)
9506 << TInfo->getType()
9507 << PromoteType
9508 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009509 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009510
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009511 QualType T = TInfo->getType().getNonLValueExprType(Context);
9512 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009513}
9514
John McCall60d7b3a2010-08-24 06:29:42 +00009515ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009516 // The type of __null will be int or long, depending on the size of
9517 // pointers on the target.
9518 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009519 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9520 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009521 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009522 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009523 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009524 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009525 Ty = Context.LongLongTy;
9526 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009527 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009528 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009529
Sebastian Redlf53597f2009-03-15 17:47:39 +00009530 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009531}
9532
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009533static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009534 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009535 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009536 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009537
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009538 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9539 if (!PT)
9540 return;
9541
9542 // Check if the destination is of type 'id'.
9543 if (!PT->isObjCIdType()) {
9544 // Check if the destination is the 'NSString' interface.
9545 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9546 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9547 return;
9548 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009549
John McCall4b9c2d22011-11-06 09:01:30 +00009550 // Ignore any parens, implicit casts (should only be
9551 // array-to-pointer decays), and not-so-opaque values. The last is
9552 // important for making this trigger for property assignments.
9553 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9554 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9555 if (OV->getSourceExpr())
9556 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9557
9558 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009559 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009560 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009561
Douglas Gregor849b2432010-03-31 17:46:05 +00009562 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009563}
9564
Chris Lattner5cf216b2008-01-04 18:04:52 +00009565bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9566 SourceLocation Loc,
9567 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009568 Expr *SrcExpr, AssignmentAction Action,
9569 bool *Complained) {
9570 if (Complained)
9571 *Complained = false;
9572
Chris Lattner5cf216b2008-01-04 18:04:52 +00009573 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009574 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009575 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009576 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009577 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009578 ConversionFixItGenerator ConvHints;
9579 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009580 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009581
Chris Lattner5cf216b2008-01-04 18:04:52 +00009582 switch (ConvTy) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00009583 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009584 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009585 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009586 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9587 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009588 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009589 case IntToPointer:
9590 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009591 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9592 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009593 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009594 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009595 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009596 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009597 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9598 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009599 if (Hint.isNull() && !CheckInferredResultType) {
9600 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9601 }
9602 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009603 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009604 case IncompatiblePointerSign:
9605 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9606 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009607 case FunctionVoidPointer:
9608 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9609 break;
John McCall86c05f32011-02-01 00:10:29 +00009610 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009611 // Perform array-to-pointer decay if necessary.
9612 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9613
John McCall86c05f32011-02-01 00:10:29 +00009614 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9615 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9616 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9617 DiagKind = diag::err_typecheck_incompatible_address_space;
9618 break;
John McCallf85e1932011-06-15 23:02:42 +00009619
9620
9621 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009622 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009623 break;
John McCall86c05f32011-02-01 00:10:29 +00009624 }
9625
9626 llvm_unreachable("unknown error case for discarding qualifiers!");
9627 // fallthrough
9628 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009629 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009630 // If the qualifiers lost were because we were applying the
9631 // (deprecated) C++ conversion from a string literal to a char*
9632 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9633 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009634 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009635 // bit of refactoring (so that the second argument is an
9636 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009637 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009638 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009639 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009640 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9641 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009642 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9643 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009644 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009645 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009646 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009647 case IntToBlockPointer:
9648 DiagKind = diag::err_int_to_block_pointer;
9649 break;
9650 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009651 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009652 break;
Steve Naroff39579072008-10-14 22:18:38 +00009653 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009654 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009655 // it can give a more specific diagnostic.
9656 DiagKind = diag::warn_incompatible_qualified_id;
9657 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009658 case IncompatibleVectors:
9659 DiagKind = diag::warn_incompatible_vectors;
9660 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009661 case IncompatibleObjCWeakRef:
9662 DiagKind = diag::err_arc_weak_unavailable_assign;
9663 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009664 case Incompatible:
9665 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009666 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9667 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009668 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009669 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009670 break;
9671 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009672
Douglas Gregord4eea832010-04-09 00:35:39 +00009673 QualType FirstType, SecondType;
9674 switch (Action) {
9675 case AA_Assigning:
9676 case AA_Initializing:
9677 // The destination type comes first.
9678 FirstType = DstType;
9679 SecondType = SrcType;
9680 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009681
Douglas Gregord4eea832010-04-09 00:35:39 +00009682 case AA_Returning:
9683 case AA_Passing:
9684 case AA_Converting:
9685 case AA_Sending:
9686 case AA_Casting:
9687 // The source type comes first.
9688 FirstType = SrcType;
9689 SecondType = DstType;
9690 break;
9691 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009692
Anna Zaks67221552011-07-28 19:51:27 +00009693 PartialDiagnostic FDiag = PDiag(DiagKind);
9694 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9695
9696 // If we can fix the conversion, suggest the FixIts.
9697 assert(ConvHints.isNull() || Hint.isNull());
9698 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009699 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9700 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009701 FDiag << *HI;
9702 } else {
9703 FDiag << Hint;
9704 }
9705 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9706
Richard Trieu6efd4c52011-11-23 22:32:32 +00009707 if (MayHaveFunctionDiff)
9708 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9709
Anna Zaks67221552011-07-28 19:51:27 +00009710 Diag(Loc, FDiag);
9711
Richard Trieu6efd4c52011-11-23 22:32:32 +00009712 if (SecondType == Context.OverloadTy)
9713 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9714 FirstType);
9715
Douglas Gregor926df6c2011-06-11 01:09:30 +00009716 if (CheckInferredResultType)
9717 EmitRelatedResultTypeNote(SrcExpr);
9718
Douglas Gregora41a8c52010-04-22 00:20:18 +00009719 if (Complained)
9720 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009721 return isInvalid;
9722}
Anders Carlssone21555e2008-11-30 19:50:32 +00009723
Richard Smith282e7e62012-02-04 09:53:13 +00009724ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9725 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009726 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9727 public:
9728 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9729 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9730 }
9731 } Diagnoser;
9732
9733 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9734}
9735
9736ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9737 llvm::APSInt *Result,
9738 unsigned DiagID,
9739 bool AllowFold) {
9740 class IDDiagnoser : public VerifyICEDiagnoser {
9741 unsigned DiagID;
9742
9743 public:
9744 IDDiagnoser(unsigned DiagID)
9745 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9746
9747 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9748 S.Diag(Loc, DiagID) << SR;
9749 }
9750 } Diagnoser(DiagID);
9751
9752 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9753}
9754
9755void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9756 SourceRange SR) {
9757 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009758}
9759
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009760ExprResult
9761Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009762 VerifyICEDiagnoser &Diagnoser,
9763 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009764 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009765
David Blaikie4e4d0842012-03-11 07:00:24 +00009766 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009767 // C++11 [expr.const]p5:
9768 // If an expression of literal class type is used in a context where an
9769 // integral constant expression is required, then that class type shall
9770 // have a single non-explicit conversion function to an integral or
9771 // unscoped enumeration type
9772 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009773 if (!Diagnoser.Suppress) {
9774 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9775 public:
9776 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9777
9778 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9779 QualType T) {
9780 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9781 }
9782
9783 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9784 SourceLocation Loc,
9785 QualType T) {
9786 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9787 }
9788
9789 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9790 SourceLocation Loc,
9791 QualType T,
9792 QualType ConvTy) {
9793 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9794 }
9795
9796 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9797 CXXConversionDecl *Conv,
9798 QualType ConvTy) {
9799 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9800 << ConvTy->isEnumeralType() << ConvTy;
9801 }
9802
9803 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9804 QualType T) {
9805 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9806 }
9807
9808 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9809 CXXConversionDecl *Conv,
9810 QualType ConvTy) {
9811 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9812 << ConvTy->isEnumeralType() << ConvTy;
9813 }
9814
9815 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9816 SourceLocation Loc,
9817 QualType T,
9818 QualType ConvTy) {
9819 return DiagnosticBuilder::getEmpty();
9820 }
9821 } ConvertDiagnoser;
9822
9823 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9824 ConvertDiagnoser,
9825 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009826 } else {
9827 // The caller wants to silently enquire whether this is an ICE. Don't
9828 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009829 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9830 public:
9831 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9832
9833 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9834 QualType T) {
9835 return DiagnosticBuilder::getEmpty();
9836 }
9837
9838 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9839 SourceLocation Loc,
9840 QualType T) {
9841 return DiagnosticBuilder::getEmpty();
9842 }
9843
9844 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9845 SourceLocation Loc,
9846 QualType T,
9847 QualType ConvTy) {
9848 return DiagnosticBuilder::getEmpty();
9849 }
9850
9851 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9852 CXXConversionDecl *Conv,
9853 QualType ConvTy) {
9854 return DiagnosticBuilder::getEmpty();
9855 }
9856
9857 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9858 QualType T) {
9859 return DiagnosticBuilder::getEmpty();
9860 }
9861
9862 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9863 CXXConversionDecl *Conv,
9864 QualType ConvTy) {
9865 return DiagnosticBuilder::getEmpty();
9866 }
9867
9868 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9869 SourceLocation Loc,
9870 QualType T,
9871 QualType ConvTy) {
9872 return DiagnosticBuilder::getEmpty();
9873 }
9874 } ConvertDiagnoser;
9875
9876 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9877 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009878 }
9879 if (Converted.isInvalid())
9880 return Converted;
9881 E = Converted.take();
9882 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9883 return ExprError();
9884 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9885 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009886 if (!Diagnoser.Suppress)
9887 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009888 return ExprError();
9889 }
9890
Richard Smithdaaefc52011-12-14 23:32:26 +00009891 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9892 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009893 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009894 if (Result)
9895 *Result = E->EvaluateKnownConstInt(Context);
9896 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009897 }
9898
Anders Carlssone21555e2008-11-30 19:50:32 +00009899 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009900 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9901 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009902
Richard Smithdaaefc52011-12-14 23:32:26 +00009903 // Try to evaluate the expression, and produce diagnostics explaining why it's
9904 // not a constant expression as a side-effect.
9905 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9906 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9907
9908 // In C++11, we can rely on diagnostics being produced for any expression
9909 // which is not a constant expression. If no diagnostics were produced, then
9910 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009911 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009912 if (Result)
9913 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009914 return Owned(E);
9915 }
9916
9917 // If our only note is the usual "invalid subexpression" note, just point
9918 // the caret at its location rather than producing an essentially
9919 // redundant note.
9920 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9921 diag::note_invalid_subexpr_in_const_expr) {
9922 DiagLoc = Notes[0].first;
9923 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +00009924 }
9925
9926 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009927 if (!Diagnoser.Suppress) {
9928 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +00009929 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9930 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +00009931 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009932
Richard Smith282e7e62012-02-04 09:53:13 +00009933 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +00009934 }
9935
Douglas Gregorab41fe92012-05-04 22:38:52 +00009936 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +00009937 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9938 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009939
Anders Carlssone21555e2008-11-30 19:50:32 +00009940 if (Result)
9941 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009942 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +00009943}
Douglas Gregore0762c92009-06-19 23:52:42 +00009944
Eli Friedmanef331b72012-01-20 01:26:23 +00009945namespace {
9946 // Handle the case where we conclude a expression which we speculatively
9947 // considered to be unevaluated is actually evaluated.
9948 class TransformToPE : public TreeTransform<TransformToPE> {
9949 typedef TreeTransform<TransformToPE> BaseTransform;
9950
9951 public:
9952 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9953
9954 // Make sure we redo semantic analysis
9955 bool AlwaysRebuild() { return true; }
9956
Eli Friedman56ff2832012-02-06 23:29:57 +00009957 // Make sure we handle LabelStmts correctly.
9958 // FIXME: This does the right thing, but maybe we need a more general
9959 // fix to TreeTransform?
9960 StmtResult TransformLabelStmt(LabelStmt *S) {
9961 S->getDecl()->setStmt(0);
9962 return BaseTransform::TransformLabelStmt(S);
9963 }
9964
Eli Friedmanef331b72012-01-20 01:26:23 +00009965 // We need to special-case DeclRefExprs referring to FieldDecls which
9966 // are not part of a member pointer formation; normal TreeTransforming
9967 // doesn't catch this case because of the way we represent them in the AST.
9968 // FIXME: This is a bit ugly; is it really the best way to handle this
9969 // case?
9970 //
9971 // Error on DeclRefExprs referring to FieldDecls.
9972 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9973 if (isa<FieldDecl>(E->getDecl()) &&
9974 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9975 return SemaRef.Diag(E->getLocation(),
9976 diag::err_invalid_non_static_member_use)
9977 << E->getDecl() << E->getSourceRange();
9978
9979 return BaseTransform::TransformDeclRefExpr(E);
9980 }
9981
9982 // Exception: filter out member pointer formation
9983 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9984 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9985 return E;
9986
9987 return BaseTransform::TransformUnaryOperator(E);
9988 }
9989
Douglas Gregore2c59132012-02-09 08:14:43 +00009990 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9991 // Lambdas never need to be transformed.
9992 return E;
9993 }
Eli Friedmanef331b72012-01-20 01:26:23 +00009994 };
Eli Friedman93c878e2012-01-18 01:05:54 +00009995}
9996
Eli Friedmanef331b72012-01-20 01:26:23 +00009997ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +00009998 assert(ExprEvalContexts.back().Context == Unevaluated &&
9999 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010000 ExprEvalContexts.back().Context =
10001 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10002 if (ExprEvalContexts.back().Context == Unevaluated)
10003 return E;
10004 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010005}
10006
Douglas Gregor2afce722009-11-26 00:44:06 +000010007void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010008Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010009 Decl *LambdaContextDecl,
10010 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010011 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010012 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010013 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010014 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010015 LambdaContextDecl,
10016 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010017 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010018 if (!MaybeODRUseExprs.empty())
10019 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010020}
10021
Richard Trieu67e29332011-08-02 04:35:43 +000010022void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010023 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010024
Douglas Gregore2c59132012-02-09 08:14:43 +000010025 if (!Rec.Lambdas.empty()) {
10026 if (Rec.Context == Unevaluated) {
10027 // C++11 [expr.prim.lambda]p2:
10028 // A lambda-expression shall not appear in an unevaluated operand
10029 // (Clause 5).
10030 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10031 Diag(Rec.Lambdas[I]->getLocStart(),
10032 diag::err_lambda_unevaluated_operand);
10033 } else {
10034 // Mark the capture expressions odr-used. This was deferred
10035 // during lambda expression creation.
10036 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10037 LambdaExpr *Lambda = Rec.Lambdas[I];
10038 for (LambdaExpr::capture_init_iterator
10039 C = Lambda->capture_init_begin(),
10040 CEnd = Lambda->capture_init_end();
10041 C != CEnd; ++C) {
10042 MarkDeclarationsReferencedInExpr(*C);
10043 }
10044 }
10045 }
10046 }
10047
Douglas Gregor2afce722009-11-26 00:44:06 +000010048 // When are coming out of an unevaluated context, clear out any
10049 // temporaries that we may have created as part of the evaluation of
10050 // the expression in that context: they aren't relevant because they
10051 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010052 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010053 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10054 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010055 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010056 CleanupVarDeclMarking();
10057 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010058 // Otherwise, merge the contexts together.
10059 } else {
10060 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010061 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10062 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010063 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010064
10065 // Pop the current expression evaluation context off the stack.
10066 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010067}
Douglas Gregore0762c92009-06-19 23:52:42 +000010068
John McCallf85e1932011-06-15 23:02:42 +000010069void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010070 ExprCleanupObjects.erase(
10071 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10072 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010073 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010074 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010075}
10076
Eli Friedman71b8fb52012-01-21 01:01:51 +000010077ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10078 if (!E->getType()->isVariablyModifiedType())
10079 return E;
10080 return TranformToPotentiallyEvaluated(E);
10081}
10082
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010083static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010084 // Do not mark anything as "used" within a dependent context; wait for
10085 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010086 if (SemaRef.CurContext->isDependentContext())
10087 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010088
Eli Friedman5f2987c2012-02-02 03:46:19 +000010089 switch (SemaRef.ExprEvalContexts.back().Context) {
10090 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010091 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010092 // (Depending on how you read the standard, we actually do need to do
10093 // something here for null pointer constants, but the standard's
10094 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010095 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010096
Eli Friedman5f2987c2012-02-02 03:46:19 +000010097 case Sema::ConstantEvaluated:
10098 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010099 // We are in a potentially evaluated expression (or a constant-expression
10100 // in C++03); we need to do implicit template instantiation, implicitly
10101 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010102 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010103
Eli Friedman5f2987c2012-02-02 03:46:19 +000010104 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010105 // Referenced declarations will only be used if the construct in the
10106 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010107 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010108 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010109 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010110}
10111
10112/// \brief Mark a function referenced, and check whether it is odr-used
10113/// (C++ [basic.def.odr]p2, C99 6.9p3)
10114void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10115 assert(Func && "No function?");
10116
10117 Func->setReferenced();
10118
Richard Smith57b9c4e2012-02-14 22:25:15 +000010119 // Don't mark this function as used multiple times, unless it's a constexpr
10120 // function which we need to instantiate.
10121 if (Func->isUsed(false) &&
10122 !(Func->isConstexpr() && !Func->getBody() &&
10123 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010124 return;
10125
10126 if (!IsPotentiallyEvaluatedContext(*this))
10127 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010128
Douglas Gregore0762c92009-06-19 23:52:42 +000010129 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010130 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010131 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010132 if (Constructor->isDefaultConstructor()) {
10133 if (Constructor->isTrivial())
10134 return;
10135 if (!Constructor->isUsed(false))
10136 DefineImplicitDefaultConstructor(Loc, Constructor);
10137 } else if (Constructor->isCopyConstructor()) {
10138 if (!Constructor->isUsed(false))
10139 DefineImplicitCopyConstructor(Loc, Constructor);
10140 } else if (Constructor->isMoveConstructor()) {
10141 if (!Constructor->isUsed(false))
10142 DefineImplicitMoveConstructor(Loc, Constructor);
10143 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010144 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010145
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010146 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010147 } else if (CXXDestructorDecl *Destructor =
10148 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010149 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10150 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010151 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010152 if (Destructor->isVirtual())
10153 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010154 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010155 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10156 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010157 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010158 if (!MethodDecl->isUsed(false)) {
10159 if (MethodDecl->isCopyAssignmentOperator())
10160 DefineImplicitCopyAssignment(Loc, MethodDecl);
10161 else
10162 DefineImplicitMoveAssignment(Loc, MethodDecl);
10163 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010164 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10165 MethodDecl->getParent()->isLambda()) {
10166 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10167 if (Conversion->isLambdaToBlockPointerConversion())
10168 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10169 else
10170 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010171 } else if (MethodDecl->isVirtual())
10172 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010173 }
John McCall15e310a2011-02-19 02:53:41 +000010174
Eli Friedman5f2987c2012-02-02 03:46:19 +000010175 // Recursive functions should be marked when used from another function.
10176 // FIXME: Is this really right?
10177 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010178
Richard Smithe6975e92012-04-17 00:58:00 +000010179 // Instantiate the exception specification for any function which is
10180 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010181 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10182 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +000010183 InstantiateExceptionSpec(Loc, Func);
10184
Eli Friedman5f2987c2012-02-02 03:46:19 +000010185 // Implicit instantiation of function templates and member functions of
10186 // class templates.
10187 if (Func->isImplicitlyInstantiable()) {
10188 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010189 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010190 if (FunctionTemplateSpecializationInfo *SpecInfo
10191 = Func->getTemplateSpecializationInfo()) {
10192 if (SpecInfo->getPointOfInstantiation().isInvalid())
10193 SpecInfo->setPointOfInstantiation(Loc);
10194 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010195 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010196 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010197 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10198 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010199 } else if (MemberSpecializationInfo *MSInfo
10200 = Func->getMemberSpecializationInfo()) {
10201 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010202 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010203 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010204 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010205 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010206 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10207 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010208 }
Mike Stump1eb44332009-09-09 15:08:12 +000010209
Richard Smith57b9c4e2012-02-14 22:25:15 +000010210 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010211 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10212 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010213 PendingLocalImplicitInstantiations.push_back(
10214 std::make_pair(Func, PointOfInstantiation));
10215 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010216 // Do not defer instantiations of constexpr functions, to avoid the
10217 // expression evaluator needing to call back into Sema if it sees a
10218 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010219 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010220 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010221 PendingInstantiations.push_back(std::make_pair(Func,
10222 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010223 // Notify the consumer that a function was implicitly instantiated.
10224 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10225 }
John McCall15e310a2011-02-19 02:53:41 +000010226 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010227 } else {
10228 // Walk redefinitions, as some of them may be instantiable.
10229 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10230 e(Func->redecls_end()); i != e; ++i) {
10231 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10232 MarkFunctionReferenced(Loc, *i);
10233 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010234 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010235
10236 // Keep track of used but undefined functions.
10237 if (!Func->isPure() && !Func->hasBody() &&
10238 Func->getLinkage() != ExternalLinkage) {
10239 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10240 if (old.isInvalid()) old = Loc;
10241 }
10242
10243 Func->setUsed(true);
10244}
10245
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010246static void
10247diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10248 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010249 DeclContext *VarDC = var->getDeclContext();
10250
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010251 // If the parameter still belongs to the translation unit, then
10252 // we're actually just using one parameter in the declaration of
10253 // the next.
10254 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010255 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010256 return;
10257
Eli Friedman0a294222012-02-07 00:15:00 +000010258 // For C code, don't diagnose about capture if we're not actually in code
10259 // right now; it's impossible to write a non-constant expression outside of
10260 // function context, so we'll get other (more useful) diagnostics later.
10261 //
10262 // For C++, things get a bit more nasty... it would be nice to suppress this
10263 // diagnostic for certain cases like using a local variable in an array bound
10264 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010265 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010266 return;
10267
Eli Friedman0a294222012-02-07 00:15:00 +000010268 if (isa<CXXMethodDecl>(VarDC) &&
10269 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10270 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10271 << var->getIdentifier();
10272 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10273 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10274 << var->getIdentifier() << fn->getDeclName();
10275 } else if (isa<BlockDecl>(VarDC)) {
10276 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10277 << var->getIdentifier();
10278 } else {
10279 // FIXME: Is there any other context where a local variable can be
10280 // declared?
10281 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10282 << var->getIdentifier();
10283 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010284
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010285 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10286 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010287
10288 // FIXME: Add additional diagnostic info about class etc. which prevents
10289 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010290}
10291
Douglas Gregorf8af9822012-02-12 18:42:33 +000010292/// \brief Capture the given variable in the given lambda expression.
10293static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010294 VarDecl *Var, QualType FieldType,
10295 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010296 SourceLocation Loc,
10297 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010298 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010299
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010300 // Build the non-static data member.
10301 FieldDecl *Field
10302 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10303 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010304 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010305 Field->setImplicit(true);
10306 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010307 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010308
10309 // C++11 [expr.prim.lambda]p21:
10310 // When the lambda-expression is evaluated, the entities that
10311 // are captured by copy are used to direct-initialize each
10312 // corresponding non-static data member of the resulting closure
10313 // object. (For array members, the array elements are
10314 // direct-initialized in increasing subscript order.) These
10315 // initializations are performed in the (unspecified) order in
10316 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010317
Douglas Gregore2c59132012-02-09 08:14:43 +000010318 // Introduce a new evaluation context for the initialization, so
10319 // that temporaries introduced as part of the capture are retained
10320 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010321 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10322
Douglas Gregor73d90922012-02-10 09:26:04 +000010323 // C++ [expr.prim.labda]p12:
10324 // An entity captured by a lambda-expression is odr-used (3.2) in
10325 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010326 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10327 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010328 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010329 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010330
10331 // When the field has array type, create index variables for each
10332 // dimension of the array. We use these index variables to subscript
10333 // the source array, and other clients (e.g., CodeGen) will perform
10334 // the necessary iteration with these index variables.
10335 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010336 QualType BaseType = FieldType;
10337 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010338 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010339 while (const ConstantArrayType *Array
10340 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010341 // Create the iteration variable for this array index.
10342 IdentifierInfo *IterationVarName = 0;
10343 {
10344 SmallString<8> Str;
10345 llvm::raw_svector_ostream OS(Str);
10346 OS << "__i" << IndexVariables.size();
10347 IterationVarName = &S.Context.Idents.get(OS.str());
10348 }
10349 VarDecl *IterationVar
10350 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10351 IterationVarName, SizeType,
10352 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10353 SC_None, SC_None);
10354 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010355 LSI->ArrayIndexVars.push_back(IterationVar);
10356
Douglas Gregor18fe0842012-02-09 02:45:47 +000010357 // Create a reference to the iteration variable.
10358 ExprResult IterationVarRef
10359 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10360 assert(!IterationVarRef.isInvalid() &&
10361 "Reference to invented variable cannot fail!");
10362 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10363 assert(!IterationVarRef.isInvalid() &&
10364 "Conversion of invented variable cannot fail!");
10365
10366 // Subscript the array with this iteration variable.
10367 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10368 Ref, Loc, IterationVarRef.take(), Loc);
10369 if (Subscript.isInvalid()) {
10370 S.CleanupVarDeclMarking();
10371 S.DiscardCleanupsInEvaluationContext();
10372 S.PopExpressionEvaluationContext();
10373 return ExprError();
10374 }
10375
10376 Ref = Subscript.take();
10377 BaseType = Array->getElementType();
10378 }
10379
10380 // Construct the entity that we will be initializing. For an array, this
10381 // will be first element in the array, which may require several levels
10382 // of array-subscript entities.
10383 SmallVector<InitializedEntity, 4> Entities;
10384 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010385 Entities.push_back(
10386 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010387 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10388 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10389 0,
10390 Entities.back()));
10391
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010392 InitializationKind InitKind
10393 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010394 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010395 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010396 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10397 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010398 MultiExprArg(S, &Ref, 1));
10399
10400 // If this initialization requires any cleanups (e.g., due to a
10401 // default argument to a copy constructor), note that for the
10402 // lambda.
10403 if (S.ExprNeedsCleanups)
10404 LSI->ExprNeedsCleanups = true;
10405
10406 // Exit the expression evaluation context used for the capture.
10407 S.CleanupVarDeclMarking();
10408 S.DiscardCleanupsInEvaluationContext();
10409 S.PopExpressionEvaluationContext();
10410 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010411}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010412
Douglas Gregor999713e2012-02-18 09:37:24 +000010413bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10414 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10415 bool BuildAndDiagnose,
10416 QualType &CaptureType,
10417 QualType &DeclRefType) {
10418 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010419
Eli Friedmanb942cb22012-02-03 22:47:37 +000010420 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010421 if (Var->getDeclContext() == DC) return true;
10422 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010423
Douglas Gregorf8af9822012-02-12 18:42:33 +000010424 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010425
Douglas Gregor999713e2012-02-18 09:37:24 +000010426 // Walk up the stack to determine whether we can capture the variable,
10427 // performing the "simple" checks that don't depend on type. We stop when
10428 // we've either hit the declared scope of the variable or find an existing
10429 // capture of that variable.
10430 CaptureType = Var->getType();
10431 DeclRefType = CaptureType.getNonReferenceType();
10432 bool Explicit = (Kind != TryCapture_Implicit);
10433 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010434 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010435 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010436 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010437 DeclContext *ParentDC;
10438 if (isa<BlockDecl>(DC))
10439 ParentDC = DC->getParent();
10440 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010441 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010442 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10443 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010444 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010445 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010446 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010447 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010448 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010449
Eli Friedmanb942cb22012-02-03 22:47:37 +000010450 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010451 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010452
Eli Friedmanb942cb22012-02-03 22:47:37 +000010453 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010454 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010455 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010456 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010457
10458 // Retrieve the capture type for this variable.
10459 CaptureType = CSI->getCapture(Var).getCaptureType();
10460
10461 // Compute the type of an expression that refers to this variable.
10462 DeclRefType = CaptureType.getNonReferenceType();
10463
10464 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10465 if (Cap.isCopyCapture() &&
10466 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10467 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010468 break;
10469 }
10470
Douglas Gregorf8af9822012-02-12 18:42:33 +000010471 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010472 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010473
10474 // Lambdas are not allowed to capture unnamed variables
10475 // (e.g. anonymous unions).
10476 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10477 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010478 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010479 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010480 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10481 Diag(Var->getLocation(), diag::note_declared_at);
10482 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010483 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010484 }
10485
10486 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010487 if (Var->getType()->isVariablyModifiedType()) {
10488 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010489 if (IsBlock)
10490 Diag(Loc, diag::err_ref_vm_type);
10491 else
10492 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10493 Diag(Var->getLocation(), diag::note_previous_decl)
10494 << Var->getDeclName();
10495 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010496 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010497 }
10498
Eli Friedmanb942cb22012-02-03 22:47:37 +000010499 // Lambdas are not allowed to capture __block variables; they don't
10500 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010501 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010502 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010503 Diag(Loc, diag::err_lambda_capture_block)
10504 << Var->getDeclName();
10505 Diag(Var->getLocation(), diag::note_previous_decl)
10506 << Var->getDeclName();
10507 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010508 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010509 }
10510
Douglas Gregorf8af9822012-02-12 18:42:33 +000010511 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10512 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010513 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010514 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10515 Diag(Var->getLocation(), diag::note_previous_decl)
10516 << Var->getDeclName();
10517 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10518 diag::note_lambda_decl);
10519 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010520 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010521 }
10522
10523 FunctionScopesIndex--;
10524 DC = ParentDC;
10525 Explicit = false;
10526 } while (!Var->getDeclContext()->Equals(DC));
10527
Douglas Gregor999713e2012-02-18 09:37:24 +000010528 // Walk back down the scope stack, computing the type of the capture at
10529 // each step, checking type-specific requirements, and adding captures if
10530 // requested.
10531 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10532 ++I) {
10533 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010534
Douglas Gregor999713e2012-02-18 09:37:24 +000010535 // Compute the type of the capture and of a reference to the capture within
10536 // this scope.
10537 if (isa<BlockScopeInfo>(CSI)) {
10538 Expr *CopyExpr = 0;
10539 bool ByRef = false;
10540
10541 // Blocks are not allowed to capture arrays.
10542 if (CaptureType->isArrayType()) {
10543 if (BuildAndDiagnose) {
10544 Diag(Loc, diag::err_ref_array_type);
10545 Diag(Var->getLocation(), diag::note_previous_decl)
10546 << Var->getDeclName();
10547 }
10548 return true;
10549 }
10550
John McCall100c6492012-03-30 05:23:48 +000010551 // Forbid the block-capture of autoreleasing variables.
10552 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10553 if (BuildAndDiagnose) {
10554 Diag(Loc, diag::err_arc_autoreleasing_capture)
10555 << /*block*/ 0;
10556 Diag(Var->getLocation(), diag::note_previous_decl)
10557 << Var->getDeclName();
10558 }
10559 return true;
10560 }
10561
Douglas Gregor999713e2012-02-18 09:37:24 +000010562 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10563 // Block capture by reference does not change the capture or
10564 // declaration reference types.
10565 ByRef = true;
10566 } else {
10567 // Block capture by copy introduces 'const'.
10568 CaptureType = CaptureType.getNonReferenceType().withConst();
10569 DeclRefType = CaptureType;
10570
David Blaikie4e4d0842012-03-11 07:00:24 +000010571 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010572 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10573 // The capture logic needs the destructor, so make sure we mark it.
10574 // Usually this is unnecessary because most local variables have
10575 // their destructors marked at declaration time, but parameters are
10576 // an exception because it's technically only the call site that
10577 // actually requires the destructor.
10578 if (isa<ParmVarDecl>(Var))
10579 FinalizeVarWithDestructor(Var, Record);
10580
10581 // According to the blocks spec, the capture of a variable from
10582 // the stack requires a const copy constructor. This is not true
10583 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010584 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010585 DeclRefType.withConst(),
10586 VK_LValue, Loc);
10587 ExprResult Result
10588 = PerformCopyInitialization(
10589 InitializedEntity::InitializeBlock(Var->getLocation(),
10590 CaptureType, false),
10591 Loc, Owned(DeclRef));
10592
10593 // Build a full-expression copy expression if initialization
10594 // succeeded and used a non-trivial constructor. Recover from
10595 // errors by pretending that the copy isn't necessary.
10596 if (!Result.isInvalid() &&
10597 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10598 ->isTrivial()) {
10599 Result = MaybeCreateExprWithCleanups(Result);
10600 CopyExpr = Result.take();
10601 }
10602 }
10603 }
10604 }
10605
10606 // Actually capture the variable.
10607 if (BuildAndDiagnose)
10608 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10609 SourceLocation(), CaptureType, CopyExpr);
10610 Nested = true;
10611 continue;
10612 }
Douglas Gregor68932842012-02-18 05:51:20 +000010613
Douglas Gregor999713e2012-02-18 09:37:24 +000010614 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10615
10616 // Determine whether we are capturing by reference or by value.
10617 bool ByRef = false;
10618 if (I == N - 1 && Kind != TryCapture_Implicit) {
10619 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010620 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010621 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010622 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010623
10624 // Compute the type of the field that will capture this variable.
10625 if (ByRef) {
10626 // C++11 [expr.prim.lambda]p15:
10627 // An entity is captured by reference if it is implicitly or
10628 // explicitly captured but not captured by copy. It is
10629 // unspecified whether additional unnamed non-static data
10630 // members are declared in the closure type for entities
10631 // captured by reference.
10632 //
10633 // FIXME: It is not clear whether we want to build an lvalue reference
10634 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10635 // to do the former, while EDG does the latter. Core issue 1249 will
10636 // clarify, but for now we follow GCC because it's a more permissive and
10637 // easily defensible position.
10638 CaptureType = Context.getLValueReferenceType(DeclRefType);
10639 } else {
10640 // C++11 [expr.prim.lambda]p14:
10641 // For each entity captured by copy, an unnamed non-static
10642 // data member is declared in the closure type. The
10643 // declaration order of these members is unspecified. The type
10644 // of such a data member is the type of the corresponding
10645 // captured entity if the entity is not a reference to an
10646 // object, or the referenced type otherwise. [Note: If the
10647 // captured entity is a reference to a function, the
10648 // corresponding data member is also a reference to a
10649 // function. - end note ]
10650 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10651 if (!RefType->getPointeeType()->isFunctionType())
10652 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010653 }
John McCall100c6492012-03-30 05:23:48 +000010654
10655 // Forbid the lambda copy-capture of autoreleasing variables.
10656 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10657 if (BuildAndDiagnose) {
10658 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10659 Diag(Var->getLocation(), diag::note_previous_decl)
10660 << Var->getDeclName();
10661 }
10662 return true;
10663 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010664 }
10665
Douglas Gregor999713e2012-02-18 09:37:24 +000010666 // Capture this variable in the lambda.
10667 Expr *CopyExpr = 0;
10668 if (BuildAndDiagnose) {
10669 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010670 DeclRefType, Loc,
10671 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010672 if (!Result.isInvalid())
10673 CopyExpr = Result.take();
10674 }
10675
10676 // Compute the type of a reference to this captured variable.
10677 if (ByRef)
10678 DeclRefType = CaptureType.getNonReferenceType();
10679 else {
10680 // C++ [expr.prim.lambda]p5:
10681 // The closure type for a lambda-expression has a public inline
10682 // function call operator [...]. This function call operator is
10683 // declared const (9.3.1) if and only if the lambda-expression’s
10684 // parameter-declaration-clause is not followed by mutable.
10685 DeclRefType = CaptureType.getNonReferenceType();
10686 if (!LSI->Mutable && !CaptureType->isReferenceType())
10687 DeclRefType.addConst();
10688 }
10689
10690 // Add the capture.
10691 if (BuildAndDiagnose)
10692 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10693 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010694 Nested = true;
10695 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010696
10697 return false;
10698}
10699
10700bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10701 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10702 QualType CaptureType;
10703 QualType DeclRefType;
10704 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10705 /*BuildAndDiagnose=*/true, CaptureType,
10706 DeclRefType);
10707}
10708
10709QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10710 QualType CaptureType;
10711 QualType DeclRefType;
10712
10713 // Determine whether we can capture this variable.
10714 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10715 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10716 return QualType();
10717
10718 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010719}
10720
Eli Friedmand2cce132012-02-02 23:15:15 +000010721static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10722 SourceLocation Loc) {
10723 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010724 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010725 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010726 Var->getLinkage() != ExternalLinkage &&
10727 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010728 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10729 if (old.isInvalid()) old = Loc;
10730 }
10731
Douglas Gregor999713e2012-02-18 09:37:24 +000010732 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010733
Eli Friedmand2cce132012-02-02 23:15:15 +000010734 Var->setUsed(true);
10735}
10736
10737void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10738 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10739 // an object that satisfies the requirements for appearing in a
10740 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10741 // is immediately applied." This function handles the lvalue-to-rvalue
10742 // conversion part.
10743 MaybeODRUseExprs.erase(E->IgnoreParens());
10744}
10745
Eli Friedmanac626012012-02-29 03:16:56 +000010746ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10747 if (!Res.isUsable())
10748 return Res;
10749
10750 // If a constant-expression is a reference to a variable where we delay
10751 // deciding whether it is an odr-use, just assume we will apply the
10752 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10753 // (a non-type template argument), we have special handling anyway.
10754 UpdateMarkingForLValueToRValue(Res.get());
10755 return Res;
10756}
10757
Eli Friedmand2cce132012-02-02 23:15:15 +000010758void Sema::CleanupVarDeclMarking() {
10759 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10760 e = MaybeODRUseExprs.end();
10761 i != e; ++i) {
10762 VarDecl *Var;
10763 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010764 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010765 Var = cast<VarDecl>(DRE->getDecl());
10766 Loc = DRE->getLocation();
10767 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10768 Var = cast<VarDecl>(ME->getMemberDecl());
10769 Loc = ME->getMemberLoc();
10770 } else {
10771 llvm_unreachable("Unexpcted expression");
10772 }
10773
10774 MarkVarDeclODRUsed(*this, Var, Loc);
10775 }
10776
10777 MaybeODRUseExprs.clear();
10778}
10779
10780// Mark a VarDecl referenced, and perform the necessary handling to compute
10781// odr-uses.
10782static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10783 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010784 Var->setReferenced();
10785
Eli Friedmand2cce132012-02-02 23:15:15 +000010786 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010787 return;
10788
10789 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010790 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010791 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10792 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010793 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10794 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010795 (!AlreadyInstantiated ||
10796 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010797 if (!AlreadyInstantiated) {
10798 // This is a modification of an existing AST node. Notify listeners.
10799 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10800 L->StaticDataMemberInstantiated(Var);
10801 MSInfo->setPointOfInstantiation(Loc);
10802 }
10803 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010804 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010805 // Do not defer instantiations of variables which could be used in a
10806 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010807 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010808 else
Richard Smith37ce0102012-02-15 02:42:50 +000010809 SemaRef.PendingInstantiations.push_back(
10810 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010811 }
10812 }
10813
Eli Friedmand2cce132012-02-02 23:15:15 +000010814 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10815 // an object that satisfies the requirements for appearing in a
10816 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10817 // is immediately applied." We check the first part here, and
10818 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10819 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010820 // C++03 depends on whether we get the C++03 version correct. This does not
10821 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010822 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010823 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010824 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010825 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10826 SemaRef.MaybeODRUseExprs.insert(E);
10827 else
10828 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10829}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010830
Eli Friedmand2cce132012-02-02 23:15:15 +000010831/// \brief Mark a variable referenced, and check whether it is odr-used
10832/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10833/// used directly for normal expressions referring to VarDecl.
10834void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10835 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010836}
10837
10838static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10839 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010840 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10841 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10842 return;
10843 }
10844
Eli Friedman5f2987c2012-02-02 03:46:19 +000010845 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010846
10847 // If this is a call to a method via a cast, also mark the method in the
10848 // derived class used in case codegen can devirtualize the call.
10849 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10850 if (!ME)
10851 return;
10852 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10853 if (!MD)
10854 return;
10855 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010856 if (Base->getType()->isDependentType())
10857 return;
10858 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010859 if (!MostDerivedClassDecl)
10860 return;
10861 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010862 if (!DM)
10863 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010864 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010865}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010866
Eli Friedman5f2987c2012-02-02 03:46:19 +000010867/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10868void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10869 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10870}
10871
10872/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10873void Sema::MarkMemberReferenced(MemberExpr *E) {
10874 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10875}
10876
Douglas Gregor73d90922012-02-10 09:26:04 +000010877/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010878/// marks the declaration referenced, and performs odr-use checking for functions
10879/// and variables. This method should not be used when building an normal
10880/// expression which refers to a variable.
10881void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10882 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10883 MarkVariableReferenced(Loc, VD);
10884 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10885 MarkFunctionReferenced(Loc, FD);
10886 else
10887 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010888}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010889
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010890namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010891 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010892 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010893 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010894 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10895 Sema &S;
10896 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010897
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010898 public:
10899 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010900
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010901 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010902
10903 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10904 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010905 };
10906}
10907
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010908bool MarkReferencedDecls::TraverseTemplateArgument(
10909 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010910 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010911 if (Decl *D = Arg.getAsDecl())
10912 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010913 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010914
10915 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010916}
10917
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010918bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010919 if (ClassTemplateSpecializationDecl *Spec
10920 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10921 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010922 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010923 }
10924
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010925 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010926}
10927
10928void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10929 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010930 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010931}
10932
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010933namespace {
10934 /// \brief Helper class that marks all of the declarations referenced by
10935 /// potentially-evaluated subexpressions as "referenced".
10936 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10937 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010938 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010939
10940 public:
10941 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10942
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010943 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10944 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010945
10946 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010947 // If we were asked not to visit local variables, don't.
10948 if (SkipLocalVariables) {
10949 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10950 if (VD->hasLocalStorage())
10951 return;
10952 }
10953
Eli Friedman5f2987c2012-02-02 03:46:19 +000010954 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010955 }
10956
10957 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010958 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010959 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010960 }
10961
John McCall80ee6e82011-11-10 05:35:25 +000010962 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010963 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000010964 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10965 Visit(E->getSubExpr());
10966 }
10967
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010968 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010969 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010970 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010971 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010972 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010973 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010974 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000010975
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010976 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10977 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010978 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010979 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10980 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10981 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010982 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010983 S.LookupDestructor(Record));
10984 }
10985
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010986 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010987 }
10988
10989 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010990 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010991 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010992 }
10993
Douglas Gregor102ff972010-10-19 17:17:35 +000010994 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10995 Visit(E->getExpr());
10996 }
Eli Friedmand2cce132012-02-02 23:15:15 +000010997
10998 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10999 Inherited::VisitImplicitCastExpr(E);
11000
11001 if (E->getCastKind() == CK_LValueToRValue)
11002 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11003 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011004 };
11005}
11006
11007/// \brief Mark any declarations that appear within this expression or any
11008/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011009///
11010/// \param SkipLocalVariables If true, don't mark local variables as
11011/// 'referenced'.
11012void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11013 bool SkipLocalVariables) {
11014 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011015}
11016
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011017/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11018/// of the program being compiled.
11019///
11020/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011021/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011022/// possibility that the code will actually be executable. Code in sizeof()
11023/// expressions, code used only during overload resolution, etc., are not
11024/// potentially evaluated. This routine will suppress such diagnostics or,
11025/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011026/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011027/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011028///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011029/// This routine should be used for all diagnostics that describe the run-time
11030/// behavior of a program, such as passing a non-POD value through an ellipsis.
11031/// Failure to do so will likely result in spurious diagnostics or failures
11032/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011033bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011034 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011035 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011036 case Unevaluated:
11037 // The argument will never be evaluated, so don't complain.
11038 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011039
Richard Smithf6702a32011-12-20 02:08:33 +000011040 case ConstantEvaluated:
11041 // Relevant diagnostics should be produced by constant evaluation.
11042 break;
11043
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011044 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011045 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011046 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011047 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011048 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011049 }
11050 else
11051 Diag(Loc, PD);
11052
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011053 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011054 }
11055
11056 return false;
11057}
11058
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011059bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11060 CallExpr *CE, FunctionDecl *FD) {
11061 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11062 return false;
11063
Richard Smith76f3f692012-02-22 02:04:18 +000011064 // If we're inside a decltype's expression, don't check for a valid return
11065 // type or construct temporaries until we know whether this is the last call.
11066 if (ExprEvalContexts.back().IsDecltype) {
11067 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11068 return false;
11069 }
11070
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011071 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011072 FunctionDecl *FD;
11073 CallExpr *CE;
11074
11075 public:
11076 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11077 : FD(FD), CE(CE) { }
11078
11079 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11080 if (!FD) {
11081 S.Diag(Loc, diag::err_call_incomplete_return)
11082 << T << CE->getSourceRange();
11083 return;
11084 }
11085
11086 S.Diag(Loc, diag::err_call_function_incomplete_return)
11087 << CE->getSourceRange() << FD->getDeclName() << T;
11088 S.Diag(FD->getLocation(),
11089 diag::note_function_with_incomplete_return_type_declared_here)
11090 << FD->getDeclName();
11091 }
11092 } Diagnoser(FD, CE);
11093
11094 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011095 return true;
11096
11097 return false;
11098}
11099
Douglas Gregor92c3a042011-01-19 16:50:08 +000011100// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011101// will prevent this condition from triggering, which is what we want.
11102void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11103 SourceLocation Loc;
11104
John McCalla52ef082009-11-11 02:41:58 +000011105 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011106 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011107
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011108 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011109 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011110 return;
11111
Douglas Gregor92c3a042011-01-19 16:50:08 +000011112 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11113
John McCallc8d8ac52009-11-12 00:06:05 +000011114 // Greylist some idioms by putting them into a warning subcategory.
11115 if (ObjCMessageExpr *ME
11116 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11117 Selector Sel = ME->getSelector();
11118
John McCallc8d8ac52009-11-12 00:06:05 +000011119 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011120 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011121 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11122
11123 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011124 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011125 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11126 }
John McCalla52ef082009-11-11 02:41:58 +000011127
John McCall5a881bb2009-10-12 21:59:07 +000011128 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011129 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011130 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011131 return;
11132
Douglas Gregor92c3a042011-01-19 16:50:08 +000011133 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011134 Loc = Op->getOperatorLoc();
11135 } else {
11136 // Not an assignment.
11137 return;
11138 }
11139
Douglas Gregor55b38842010-04-14 16:09:52 +000011140 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011141
Daniel Dunbar96a00142012-03-09 18:35:03 +000011142 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011143 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11144 Diag(Loc, diag::note_condition_assign_silence)
11145 << FixItHint::CreateInsertion(Open, "(")
11146 << FixItHint::CreateInsertion(Close, ")");
11147
Douglas Gregor92c3a042011-01-19 16:50:08 +000011148 if (IsOrAssign)
11149 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11150 << FixItHint::CreateReplacement(Loc, "!=");
11151 else
11152 Diag(Loc, diag::note_condition_assign_to_comparison)
11153 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011154}
11155
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011156/// \brief Redundant parentheses over an equality comparison can indicate
11157/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011158void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011159 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011160 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011161 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11162 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011163 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011164 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011165 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011166
Richard Trieuccd891a2011-09-09 01:45:06 +000011167 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011168
11169 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011170 if (opE->getOpcode() == BO_EQ &&
11171 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11172 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011173 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011174
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011175 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011176 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011177 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011178 << FixItHint::CreateRemoval(ParenERange.getBegin())
11179 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011180 Diag(Loc, diag::note_equality_comparison_to_assign)
11181 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011182 }
11183}
11184
John Wiegley429bb272011-04-08 18:41:53 +000011185ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011186 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011187 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11188 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011189
John McCall864c0412011-04-26 20:42:42 +000011190 ExprResult result = CheckPlaceholderExpr(E);
11191 if (result.isInvalid()) return ExprError();
11192 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011193
John McCall864c0412011-04-26 20:42:42 +000011194 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011195 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011196 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11197
John Wiegley429bb272011-04-08 18:41:53 +000011198 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11199 if (ERes.isInvalid())
11200 return ExprError();
11201 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011202
11203 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011204 if (!T->isScalarType()) { // C99 6.8.4.1p1
11205 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11206 << T << E->getSourceRange();
11207 return ExprError();
11208 }
John McCall5a881bb2009-10-12 21:59:07 +000011209 }
11210
John Wiegley429bb272011-04-08 18:41:53 +000011211 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011212}
Douglas Gregor586596f2010-05-06 17:25:47 +000011213
John McCall60d7b3a2010-08-24 06:29:42 +000011214ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011215 Expr *SubExpr) {
11216 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011217 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011218
Richard Trieuccd891a2011-09-09 01:45:06 +000011219 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011220}
John McCall2a984ca2010-10-12 00:20:44 +000011221
John McCall1de4d4e2011-04-07 08:22:57 +000011222namespace {
John McCall755d8492011-04-12 00:42:48 +000011223 /// A visitor for rebuilding a call to an __unknown_any expression
11224 /// to have an appropriate type.
11225 struct RebuildUnknownAnyFunction
11226 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11227
11228 Sema &S;
11229
11230 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11231
11232 ExprResult VisitStmt(Stmt *S) {
11233 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011234 }
11235
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011236 ExprResult VisitExpr(Expr *E) {
11237 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11238 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011239 return ExprError();
11240 }
11241
11242 /// Rebuild an expression which simply semantically wraps another
11243 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011244 template <class T> ExprResult rebuildSugarExpr(T *E) {
11245 ExprResult SubResult = Visit(E->getSubExpr());
11246 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011247
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011248 Expr *SubExpr = SubResult.take();
11249 E->setSubExpr(SubExpr);
11250 E->setType(SubExpr->getType());
11251 E->setValueKind(SubExpr->getValueKind());
11252 assert(E->getObjectKind() == OK_Ordinary);
11253 return E;
John McCall755d8492011-04-12 00:42:48 +000011254 }
11255
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011256 ExprResult VisitParenExpr(ParenExpr *E) {
11257 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011258 }
11259
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011260 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11261 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011262 }
11263
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011264 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11265 ExprResult SubResult = Visit(E->getSubExpr());
11266 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011267
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011268 Expr *SubExpr = SubResult.take();
11269 E->setSubExpr(SubExpr);
11270 E->setType(S.Context.getPointerType(SubExpr->getType()));
11271 assert(E->getValueKind() == VK_RValue);
11272 assert(E->getObjectKind() == OK_Ordinary);
11273 return E;
John McCall755d8492011-04-12 00:42:48 +000011274 }
11275
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011276 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11277 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011278
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011279 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011280
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011281 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011282 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011283 !(isa<CXXMethodDecl>(VD) &&
11284 cast<CXXMethodDecl>(VD)->isInstance()))
11285 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011286
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011287 return E;
John McCall755d8492011-04-12 00:42:48 +000011288 }
11289
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011290 ExprResult VisitMemberExpr(MemberExpr *E) {
11291 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011292 }
11293
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011294 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11295 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011296 }
11297 };
11298}
11299
11300/// Given a function expression of unknown-any type, try to rebuild it
11301/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011302static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11303 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11304 if (Result.isInvalid()) return ExprError();
11305 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011306}
11307
11308namespace {
John McCall379b5152011-04-11 07:02:50 +000011309 /// A visitor for rebuilding an expression of type __unknown_anytype
11310 /// into one which resolves the type directly on the referring
11311 /// expression. Strict preservation of the original source
11312 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011313 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011314 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011315
11316 Sema &S;
11317
11318 /// The current destination type.
11319 QualType DestType;
11320
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011321 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11322 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011323
John McCalla5fc4722011-04-09 22:50:59 +000011324 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011325 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011326 }
11327
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011328 ExprResult VisitExpr(Expr *E) {
11329 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11330 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011331 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011332 }
11333
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011334 ExprResult VisitCallExpr(CallExpr *E);
11335 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011336
John McCalla5fc4722011-04-09 22:50:59 +000011337 /// Rebuild an expression which simply semantically wraps another
11338 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011339 template <class T> ExprResult rebuildSugarExpr(T *E) {
11340 ExprResult SubResult = Visit(E->getSubExpr());
11341 if (SubResult.isInvalid()) return ExprError();
11342 Expr *SubExpr = SubResult.take();
11343 E->setSubExpr(SubExpr);
11344 E->setType(SubExpr->getType());
11345 E->setValueKind(SubExpr->getValueKind());
11346 assert(E->getObjectKind() == OK_Ordinary);
11347 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011348 }
John McCall1de4d4e2011-04-07 08:22:57 +000011349
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011350 ExprResult VisitParenExpr(ParenExpr *E) {
11351 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011352 }
11353
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011354 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11355 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011356 }
11357
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011358 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11359 const PointerType *Ptr = DestType->getAs<PointerType>();
11360 if (!Ptr) {
11361 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11362 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011363 return ExprError();
11364 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011365 assert(E->getValueKind() == VK_RValue);
11366 assert(E->getObjectKind() == OK_Ordinary);
11367 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011368
11369 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011370 DestType = Ptr->getPointeeType();
11371 ExprResult SubResult = Visit(E->getSubExpr());
11372 if (SubResult.isInvalid()) return ExprError();
11373 E->setSubExpr(SubResult.take());
11374 return E;
John McCall755d8492011-04-12 00:42:48 +000011375 }
11376
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011377 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011378
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011379 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011380
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011381 ExprResult VisitMemberExpr(MemberExpr *E) {
11382 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011383 }
John McCalla5fc4722011-04-09 22:50:59 +000011384
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011385 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11386 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011387 }
11388 };
11389}
11390
John McCall379b5152011-04-11 07:02:50 +000011391/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011392ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11393 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011394
11395 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011396 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011397 FK_FunctionPointer,
11398 FK_BlockPointer
11399 };
11400
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011401 FnKind Kind;
11402 QualType CalleeType = CalleeExpr->getType();
11403 if (CalleeType == S.Context.BoundMemberTy) {
11404 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11405 Kind = FK_MemberFunction;
11406 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11407 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11408 CalleeType = Ptr->getPointeeType();
11409 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011410 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011411 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11412 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011413 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011414 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011415
11416 // Verify that this is a legal result type of a function.
11417 if (DestType->isArrayType() || DestType->isFunctionType()) {
11418 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011419 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011420 diagID = diag::err_block_returning_array_function;
11421
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011422 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011423 << DestType->isFunctionType() << DestType;
11424 return ExprError();
11425 }
11426
11427 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011428 E->setType(DestType.getNonLValueExprType(S.Context));
11429 E->setValueKind(Expr::getValueKindForType(DestType));
11430 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011431
11432 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011433 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011434 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011435 Proto->arg_type_begin(),
11436 Proto->getNumArgs(),
11437 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011438 else
11439 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011440 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011441
11442 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011443 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011444 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011445 // Nothing to do.
11446 break;
11447
11448 case FK_FunctionPointer:
11449 DestType = S.Context.getPointerType(DestType);
11450 break;
11451
11452 case FK_BlockPointer:
11453 DestType = S.Context.getBlockPointerType(DestType);
11454 break;
11455 }
11456
11457 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011458 ExprResult CalleeResult = Visit(CalleeExpr);
11459 if (!CalleeResult.isUsable()) return ExprError();
11460 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011461
11462 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011463 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011464}
11465
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011466ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011467 // Verify that this is a legal result type of a call.
11468 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011469 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011470 << DestType->isFunctionType() << DestType;
11471 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011472 }
11473
John McCall48218c62011-07-13 17:56:40 +000011474 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011475 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11476 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11477 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011478 }
John McCall755d8492011-04-12 00:42:48 +000011479
John McCall379b5152011-04-11 07:02:50 +000011480 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011481 E->setType(DestType.getNonReferenceType());
11482 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011483
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011484 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011485}
11486
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011487ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011488 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011489 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011490 assert(E->getValueKind() == VK_RValue);
11491 assert(E->getObjectKind() == OK_Ordinary);
11492
11493 E->setType(DestType);
11494
11495 // Rebuild the sub-expression as the pointee (function) type.
11496 DestType = DestType->castAs<PointerType>()->getPointeeType();
11497
11498 ExprResult Result = Visit(E->getSubExpr());
11499 if (!Result.isUsable()) return ExprError();
11500
11501 E->setSubExpr(Result.take());
11502 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011503 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011504 assert(E->getValueKind() == VK_RValue);
11505 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011506
Sean Callanance9c8312012-03-06 21:34:12 +000011507 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011508
Sean Callanance9c8312012-03-06 21:34:12 +000011509 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011510
Sean Callanance9c8312012-03-06 21:34:12 +000011511 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11512 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011513
Sean Callanance9c8312012-03-06 21:34:12 +000011514 ExprResult Result = Visit(E->getSubExpr());
11515 if (!Result.isUsable()) return ExprError();
11516
11517 E->setSubExpr(Result.take());
11518 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011519 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011520 llvm_unreachable("Unhandled cast type!");
11521 }
John McCall379b5152011-04-11 07:02:50 +000011522}
11523
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011524ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11525 ExprValueKind ValueKind = VK_LValue;
11526 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011527
11528 // We know how to make this work for certain kinds of decls:
11529
11530 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11532 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11533 DestType = Ptr->getPointeeType();
11534 ExprResult Result = resolveDecl(E, VD);
11535 if (Result.isInvalid()) return ExprError();
11536 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011537 CK_FunctionToPointerDecay, VK_RValue);
11538 }
11539
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011540 if (!Type->isFunctionType()) {
11541 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11542 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011543 return ExprError();
11544 }
John McCall379b5152011-04-11 07:02:50 +000011545
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011546 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11547 if (MD->isInstance()) {
11548 ValueKind = VK_RValue;
11549 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011550 }
11551
John McCall379b5152011-04-11 07:02:50 +000011552 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011553 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011555
11556 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011557 } else if (isa<VarDecl>(VD)) {
11558 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11559 Type = RefTy->getPointeeType();
11560 } else if (Type->isFunctionType()) {
11561 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11562 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011563 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011564 }
11565
11566 // - nothing else
11567 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011568 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11569 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011570 return ExprError();
11571 }
11572
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011573 VD->setType(DestType);
11574 E->setType(Type);
11575 E->setValueKind(ValueKind);
11576 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011577}
11578
John McCall1de4d4e2011-04-07 08:22:57 +000011579/// Check a cast of an unknown-any type. We intentionally only
11580/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011581ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11582 Expr *CastExpr, CastKind &CastKind,
11583 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011584 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011585 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011586 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011587
Richard Trieuccd891a2011-09-09 01:45:06 +000011588 CastExpr = result.take();
11589 VK = CastExpr->getValueKind();
11590 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011591
Richard Trieuccd891a2011-09-09 01:45:06 +000011592 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011593}
11594
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011595ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11596 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11597}
11598
Richard Trieuccd891a2011-09-09 01:45:06 +000011599static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11600 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011601 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011602 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011603 E = E->IgnoreParenImpCasts();
11604 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11605 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011606 diagID = diag::err_uncasted_call_of_unknown_any;
11607 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011608 break;
John McCall379b5152011-04-11 07:02:50 +000011609 }
John McCall1de4d4e2011-04-07 08:22:57 +000011610 }
11611
John McCall379b5152011-04-11 07:02:50 +000011612 SourceLocation loc;
11613 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011614 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011615 loc = ref->getLocation();
11616 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011617 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011618 loc = mem->getMemberLoc();
11619 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011620 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011621 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011622 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011623 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011624 if (!d) {
11625 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11626 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11627 << orig->getSourceRange();
11628 return ExprError();
11629 }
John McCall379b5152011-04-11 07:02:50 +000011630 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011631 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11632 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011633 return ExprError();
11634 }
11635
11636 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011637
11638 // Never recoverable.
11639 return ExprError();
11640}
11641
John McCall2a984ca2010-10-12 00:20:44 +000011642/// Check for operands with placeholder types and complain if found.
11643/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011644ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011645 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11646 if (!placeholderType) return Owned(E);
11647
11648 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011649
John McCall1de4d4e2011-04-07 08:22:57 +000011650 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011651 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011652 // Try to resolve a single function template specialization.
11653 // This is obligatory.
11654 ExprResult result = Owned(E);
11655 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11656 return result;
11657
11658 // If that failed, try to recover with a call.
11659 } else {
11660 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11661 /*complain*/ true);
11662 return result;
11663 }
11664 }
John McCall1de4d4e2011-04-07 08:22:57 +000011665
John McCall864c0412011-04-26 20:42:42 +000011666 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011667 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011668 ExprResult result = Owned(E);
11669 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11670 /*complain*/ true);
11671 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011672 }
11673
11674 // ARC unbridged casts.
11675 case BuiltinType::ARCUnbridgedCast: {
11676 Expr *realCast = stripARCUnbridgedCast(E);
11677 diagnoseARCUnbridgedCast(realCast);
11678 return Owned(realCast);
11679 }
John McCall864c0412011-04-26 20:42:42 +000011680
John McCall1de4d4e2011-04-07 08:22:57 +000011681 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011682 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011683 return diagnoseUnknownAnyExpr(*this, E);
11684
John McCall3c3b7f92011-10-25 17:37:35 +000011685 // Pseudo-objects.
11686 case BuiltinType::PseudoObject:
11687 return checkPseudoObjectRValue(E);
11688
John McCalle0a22d02011-10-18 21:02:43 +000011689 // Everything else should be impossible.
11690#define BUILTIN_TYPE(Id, SingletonId) \
11691 case BuiltinType::Id:
11692#define PLACEHOLDER_TYPE(Id, SingletonId)
11693#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011694 break;
11695 }
11696
11697 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011698}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011699
Richard Trieuccd891a2011-09-09 01:45:06 +000011700bool Sema::CheckCaseExpression(Expr *E) {
11701 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011702 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011703 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11704 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011705 return false;
11706}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011707
11708/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11709ExprResult
11710Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11711 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11712 "Unknown Objective-C Boolean value!");
11713 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian93a49942012-04-16 21:03:30 +000011714 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011715}